blob: 799056139316045c668849516dfbd6dba1449bd1 [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 ){
drhca424112008-01-25 15:04:48 +0000358 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000359 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000360 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000361 }else{
drhca424112008-01-25 15:04:48 +0000362 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000363 }
drha6ecd332004-06-10 00:29:09 +0000364 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000365 }
drhe933b832014-09-10 17:34:28 +0000366#if SQLITE_USER_AUTHENICATION
367 else if( pParse->db->auth.authLevel<UAUTH_User ){
368 sqlite3ErrorMsg(pParse, "user not authenticated");
369 p = 0;
370 }
371#endif
drha69d9162003-04-17 22:57:53 +0000372 return p;
373}
374
375/*
dan41fb5cd2012-10-04 19:33:00 +0000376** Locate the table identified by *p.
377**
378** This is a wrapper around sqlite3LocateTable(). The difference between
379** sqlite3LocateTable() and this function is that this function restricts
380** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
381** non-NULL if it is part of a view or trigger program definition. See
382** sqlite3FixSrcList() for details.
383*/
384Table *sqlite3LocateTableItem(
385 Parse *pParse,
386 int isView,
387 struct SrcList_item *p
388){
389 const char *zDb;
390 assert( p->pSchema==0 || p->zDatabase==0 );
391 if( p->pSchema ){
392 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
393 zDb = pParse->db->aDb[iDb].zName;
394 }else{
395 zDb = p->zDatabase;
396 }
397 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
398}
399
400/*
drha69d9162003-04-17 22:57:53 +0000401** Locate the in-memory structure that describes
402** a particular index given the name of that index
403** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000404** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000405**
406** If zDatabase is 0, all databases are searched for the
407** table and the first matching index is returned. (No checking
408** for duplicate index names is done.) The search order is
409** TEMP first, then MAIN, then any auxiliary databases added
410** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000411*/
drh9bb575f2004-09-06 17:24:11 +0000412Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000413 Index *p = 0;
414 int i;
drh21206082011-04-04 18:22:02 +0000415 /* All mutexes are required for schema access. Make sure we hold them. */
416 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000417 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000418 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000419 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000420 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000421 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000422 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000423 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000424 if( p ) break;
425 }
drh74e24cd2002-01-09 03:19:59 +0000426 return p;
drh75897232000-05-29 14:26:00 +0000427}
428
429/*
drh956bc922004-07-24 17:38:29 +0000430** Reclaim the memory used by an index
431*/
dan1feeaed2010-07-23 15:41:47 +0000432static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000433#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000434 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000435#endif
drh1fe05372013-07-31 18:12:26 +0000436 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000437 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000438 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh75b170b2014-10-04 00:07:44 +0000439#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
440 sqlite3_free(p->aiRowEst);
441#endif
drh633e6d52008-07-28 19:34:53 +0000442 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000443}
444
445/*
drhc96d8532005-05-03 12:30:33 +0000446** For the index called zIdxName which is found in the database iDb,
447** unlike that index from its Table then remove the index from
448** the index hash table and free all memory structures associated
449** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000450*/
drh9bb575f2004-09-06 17:24:11 +0000451void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000452 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000453 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000454
drh21206082011-04-04 18:22:02 +0000455 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
456 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000457 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000458 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000459 if( pIndex->pTable->pIndex==pIndex ){
460 pIndex->pTable->pIndex = pIndex->pNext;
461 }else{
462 Index *p;
drh04491712009-05-13 17:21:13 +0000463 /* Justification of ALWAYS(); The index must be on the list of
464 ** indices. */
465 p = pIndex->pTable->pIndex;
466 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
467 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000468 p->pNext = pIndex->pNext;
469 }
drh5e00f6c2001-09-13 13:46:56 +0000470 }
dan1feeaed2010-07-23 15:41:47 +0000471 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000472 }
drh956bc922004-07-24 17:38:29 +0000473 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000474}
475
476/*
drh81028a42012-05-15 18:28:27 +0000477** Look through the list of open database files in db->aDb[] and if
478** any have been closed, remove them from the list. Reallocate the
479** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000480**
drh81028a42012-05-15 18:28:27 +0000481** Entry 0 (the "main" database) and entry 1 (the "temp" database)
482** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000483*/
drh81028a42012-05-15 18:28:27 +0000484void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000485 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000486 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000487 struct Db *pDb = &db->aDb[i];
488 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000489 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000490 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000491 continue;
492 }
493 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000494 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000495 }
drh8bf8dc92003-05-17 17:35:10 +0000496 j++;
drh1c2d8412003-03-31 00:30:47 +0000497 }
498 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
499 db->nDb = j;
500 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
501 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000502 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000503 db->aDb = db->aDbStatic;
504 }
drhe0bc4042002-06-25 01:09:11 +0000505}
506
507/*
drh81028a42012-05-15 18:28:27 +0000508** Reset the schema for the database at index iDb. Also reset the
509** TEMP schema.
510*/
511void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000512 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000513 assert( iDb<db->nDb );
514
515 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000516 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000517 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
518 assert( pDb->pSchema!=0 );
519 sqlite3SchemaClear(pDb->pSchema);
520
521 /* If any database other than TEMP is reset, then also reset TEMP
522 ** since TEMP might be holding triggers that reference tables in the
523 ** other database.
524 */
525 if( iDb!=1 ){
526 pDb = &db->aDb[1];
527 assert( pDb->pSchema!=0 );
528 sqlite3SchemaClear(pDb->pSchema);
529 }
530 return;
531}
532
533/*
534** Erase all schema information from all attached databases (including
535** "main" and "temp") for a single database connection.
536*/
537void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
538 int i;
539 sqlite3BtreeEnterAll(db);
540 for(i=0; i<db->nDb; i++){
541 Db *pDb = &db->aDb[i];
542 if( pDb->pSchema ){
543 sqlite3SchemaClear(pDb->pSchema);
544 }
545 }
546 db->flags &= ~SQLITE_InternChanges;
547 sqlite3VtabUnlockList(db);
548 sqlite3BtreeLeaveAll(db);
549 sqlite3CollapseDatabaseArray(db);
550}
551
552/*
drhe0bc4042002-06-25 01:09:11 +0000553** This routine is called when a commit occurs.
554*/
drh9bb575f2004-09-06 17:24:11 +0000555void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000556 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000557}
558
559/*
dand46def72010-07-24 11:28:28 +0000560** Delete memory allocated for the column names of a table or view (the
561** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000562*/
dand46def72010-07-24 11:28:28 +0000563static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000564 int i;
565 Column *pCol;
566 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000567 if( (pCol = pTable->aCol)!=0 ){
568 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000569 sqlite3DbFree(db, pCol->zName);
570 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000571 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000572 sqlite3DbFree(db, pCol->zType);
573 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000574 }
drh633e6d52008-07-28 19:34:53 +0000575 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000576 }
drh956bc922004-07-24 17:38:29 +0000577}
578
579/*
drh75897232000-05-29 14:26:00 +0000580** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000581** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000582**
583** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000584** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000585** memory structures of the indices and foreign keys associated with
586** the table.
drh29ddd3a2012-05-15 12:49:32 +0000587**
588** The db parameter is optional. It is needed if the Table object
589** contains lookaside memory. (Table objects in the schema do not use
590** lookaside memory, but some ephemeral Table objects do.) Or the
591** db parameter can be used with db->pnBytesFreed to measure the memory
592** used by the Table object.
drh75897232000-05-29 14:26:00 +0000593*/
dan1feeaed2010-07-23 15:41:47 +0000594void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000595 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000596 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000597
dand46def72010-07-24 11:28:28 +0000598 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000599
drhed8a3bb2005-06-06 21:19:56 +0000600 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000601 if( !pTable ) return;
602 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000603
drh29ddd3a2012-05-15 12:49:32 +0000604 /* Record the number of outstanding lookaside allocations in schema Tables
605 ** prior to doing any free() operations. Since schema Tables do not use
606 ** lookaside, this number should not change. */
607 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
608 db->lookaside.nOut : 0 );
609
dand46def72010-07-24 11:28:28 +0000610 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000611 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
612 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000613 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000614 if( !db || db->pnBytesFreed==0 ){
615 char *zName = pIndex->zName;
616 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000617 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000618 );
drh21206082011-04-04 18:22:02 +0000619 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000620 assert( pOld==pIndex || pOld==0 );
621 }
622 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000623 }
624
dan1da40a32009-09-19 17:00:31 +0000625 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000626 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000627
628 /* Delete the Table structure itself.
629 */
dand46def72010-07-24 11:28:28 +0000630 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000631 sqlite3DbFree(db, pTable->zName);
632 sqlite3DbFree(db, pTable->zColAff);
633 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000634#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000635 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000636#endif
drh078e4082010-07-28 19:17:51 +0000637#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000638 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000639#endif
drh633e6d52008-07-28 19:34:53 +0000640 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000641
642 /* Verify that no lookaside memory was used by schema tables */
643 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000644}
645
646/*
drh5edc3122001-09-13 21:53:09 +0000647** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000648** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000649*/
drh9bb575f2004-09-06 17:24:11 +0000650void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000651 Table *p;
drh956bc922004-07-24 17:38:29 +0000652 Db *pDb;
653
drhd229ca92002-01-09 13:30:41 +0000654 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000655 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000656 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000657 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000658 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000659 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000660 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000661 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000662 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000663}
664
665/*
drha99db3b2004-06-19 14:49:12 +0000666** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000667** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000668** is obtained from sqliteMalloc() and must be freed by the calling
669** function.
drh75897232000-05-29 14:26:00 +0000670**
drh24fb6272009-05-01 21:13:36 +0000671** Any quotation marks (ex: "name", 'name', [name], or `name`) that
672** surround the body of the token are removed.
673**
drhc96d8532005-05-03 12:30:33 +0000674** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000675** are not \000 terminated and are not persistent. The returned string
676** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000677*/
drh17435752007-08-16 04:30:38 +0000678char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000679 char *zName;
680 if( pName ){
drh17435752007-08-16 04:30:38 +0000681 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000682 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000683 }else{
684 zName = 0;
685 }
drh75897232000-05-29 14:26:00 +0000686 return zName;
687}
688
689/*
danielk1977cbb18d22004-05-28 11:37:27 +0000690** Open the sqlite_master table stored in database number iDb for
691** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000692*/
danielk1977c00da102006-01-07 13:21:04 +0000693void sqlite3OpenMasterTable(Parse *p, int iDb){
694 Vdbe *v = sqlite3GetVdbe(p);
695 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000696 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000697 if( p->nTab==0 ){
698 p->nTab = 1;
699 }
drhe0bc4042002-06-25 01:09:11 +0000700}
701
702/*
danielk197704103022009-02-03 16:51:24 +0000703** Parameter zName points to a nul-terminated buffer containing the name
704** of a database ("main", "temp" or the name of an attached db). This
705** function returns the index of the named database in db->aDb[], or
706** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000707*/
danielk197704103022009-02-03 16:51:24 +0000708int sqlite3FindDbName(sqlite3 *db, const char *zName){
709 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000710 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000711 Db *pDb;
712 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000713 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000714 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000715 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000716 break;
drh73c42a12004-11-20 18:13:10 +0000717 }
danielk1977cbb18d22004-05-28 11:37:27 +0000718 }
719 }
danielk1977576ec6b2005-01-21 11:55:25 +0000720 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000721}
722
danielk197704103022009-02-03 16:51:24 +0000723/*
724** The token *pName contains the name of a database (either "main" or
725** "temp" or the name of an attached db). This routine returns the
726** index of the named database in db->aDb[], or -1 if the named db
727** does not exist.
728*/
729int sqlite3FindDb(sqlite3 *db, Token *pName){
730 int i; /* Database number */
731 char *zName; /* Name we are searching for */
732 zName = sqlite3NameFromToken(db, pName);
733 i = sqlite3FindDbName(db, zName);
734 sqlite3DbFree(db, zName);
735 return i;
736}
737
drh0e3d7472004-06-19 17:33:07 +0000738/* The table or view or trigger name is passed to this routine via tokens
739** pName1 and pName2. If the table name was fully qualified, for example:
740**
741** CREATE TABLE xxx.yyy (...);
742**
743** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
744** the table name is not fully qualified, i.e.:
745**
746** CREATE TABLE yyy(...);
747**
748** Then pName1 is set to "yyy" and pName2 is "".
749**
750** This routine sets the *ppUnqual pointer to point at the token (pName1 or
751** pName2) that stores the unqualified table name. The index of the
752** database "xxx" is returned.
753*/
danielk1977ef2cb632004-05-29 02:37:19 +0000754int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000755 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000756 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000757 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
758 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000759){
drh0e3d7472004-06-19 17:33:07 +0000760 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000761 sqlite3 *db = pParse->db;
762
drhc4a64fa2009-05-11 20:53:28 +0000763 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000764 if( db->init.busy ) {
765 sqlite3ErrorMsg(pParse, "corrupt database");
shanedcc50b72008-11-13 18:29:50 +0000766 return -1;
767 }
danielk1977cbb18d22004-05-28 11:37:27 +0000768 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000769 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000770 if( iDb<0 ){
771 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000772 return -1;
773 }
774 }else{
775 assert( db->init.iDb==0 || db->init.busy );
776 iDb = db->init.iDb;
777 *pUnqual = pName1;
778 }
779 return iDb;
780}
781
782/*
danielk1977d8123362004-06-12 09:25:12 +0000783** This routine is used to check if the UTF-8 string zName is a legal
784** unqualified name for a new schema object (table, index, view or
785** trigger). All names are legal except those that begin with the string
786** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
787** is reserved for internal use.
788*/
789int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000790 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000791 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000792 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000793 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
794 return SQLITE_ERROR;
795 }
796 return SQLITE_OK;
797}
798
799/*
drh44156282013-10-23 22:23:03 +0000800** Return the PRIMARY KEY index of a table
801*/
802Index *sqlite3PrimaryKeyIndex(Table *pTab){
803 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000804 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000805 return p;
806}
807
808/*
809** Return the column of index pIdx that corresponds to table
810** column iCol. Return -1 if not found.
811*/
812i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
813 int i;
814 for(i=0; i<pIdx->nColumn; i++){
815 if( iCol==pIdx->aiColumn[i] ) return i;
816 }
817 return -1;
818}
819
820/*
drh75897232000-05-29 14:26:00 +0000821** Begin constructing a new table representation in memory. This is
822** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000823** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000824** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000825** flag is true if the table should be stored in the auxiliary database
826** file instead of in the main database file. This is normally the case
827** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000828** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000829**
drhf57b3392001-10-08 13:22:32 +0000830** The new table record is initialized and put in pParse->pNewTable.
831** As more of the CREATE TABLE statement is parsed, additional action
832** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000833** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000834** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000835*/
danielk19774adee202004-05-08 08:23:19 +0000836void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000837 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000838 Token *pName1, /* First part of the name of the table or view */
839 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000840 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000841 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000842 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000843 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000844){
drh75897232000-05-29 14:26:00 +0000845 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000846 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000847 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000848 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000849 int iDb; /* Database number to create the table in */
850 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000851
danielk1977cbb18d22004-05-28 11:37:27 +0000852 /* The table or view name to create is passed to this routine via tokens
853 ** pName1 and pName2. If the table name was fully qualified, for example:
854 **
855 ** CREATE TABLE xxx.yyy (...);
856 **
857 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
858 ** the table name is not fully qualified, i.e.:
859 **
860 ** CREATE TABLE yyy(...);
861 **
862 ** Then pName1 is set to "yyy" and pName2 is "".
863 **
864 ** The call below sets the pName pointer to point at the token (pName1 or
865 ** pName2) that stores the unqualified table name. The variable iDb is
866 ** set to the index of the database that the table or view is to be
867 ** created in.
868 */
danielk1977ef2cb632004-05-29 02:37:19 +0000869 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000870 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000871 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
872 /* If creating a temp table, the name may not be qualified. Unless
873 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000874 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000875 return;
876 }
danielk197753c0f742005-03-29 03:10:59 +0000877 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000878
879 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000880 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000881 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000882 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000883 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000884 }
drh1d85d932004-02-14 23:05:52 +0000885 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000886#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000887 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000888 {
889 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000890 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000891 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000892 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000893 }
drhe5f9c642003-01-13 23:27:31 +0000894 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000895 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000896 code = SQLITE_CREATE_TEMP_VIEW;
897 }else{
898 code = SQLITE_CREATE_VIEW;
899 }
900 }else{
danielk197753c0f742005-03-29 03:10:59 +0000901 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000902 code = SQLITE_CREATE_TEMP_TABLE;
903 }else{
904 code = SQLITE_CREATE_TABLE;
905 }
906 }
danielk1977f1a381e2006-06-16 08:01:02 +0000907 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000908 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000909 }
910 }
911#endif
drhf57b3392001-10-08 13:22:32 +0000912
drhf57b3392001-10-08 13:22:32 +0000913 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000914 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000915 ** it does. The exception is if the statement being parsed was passed
916 ** to an sqlite3_declare_vtab() call. In that case only the column names
917 ** and types will be used, so there is no need to test for namespace
918 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000919 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000920 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000921 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000922 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
923 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000924 }
dana16d1062010-09-28 17:37:28 +0000925 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000926 if( pTable ){
927 if( !noErr ){
928 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000929 }else{
drh33c59ec2015-04-19 20:39:17 +0000930 assert( !db->init.busy || CORRUPT_DB );
dan7687c832011-04-09 15:39:02 +0000931 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000932 }
933 goto begin_table_error;
934 }
drh8a8a0d12010-09-28 20:26:44 +0000935 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000936 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
937 goto begin_table_error;
938 }
drh75897232000-05-29 14:26:00 +0000939 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000940
danielk197726783a52007-08-29 14:06:22 +0000941 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000942 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000943 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000944 pParse->rc = SQLITE_NOMEM;
945 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000946 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000947 }
drh75897232000-05-29 14:26:00 +0000948 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000949 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000950 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000951 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000952 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000953 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000954 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000955
drh4794f732004-11-05 17:17:50 +0000956 /* If this is the magic sqlite_sequence table used by autoincrement,
957 ** then record a pointer to this table in the main database structure
958 ** so that INSERT can find the table easily.
959 */
960#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000961 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000962 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000963 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000964 }
965#endif
966
drh17f71932002-02-21 12:01:27 +0000967 /* Begin generating the code that will insert the table record into
968 ** the SQLITE_MASTER table. Note in particular that we must go ahead
969 ** and allocate the record number for the table entry now. Before any
970 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
971 ** indices to be created and the table record must come before the
972 ** indices. Hence, the record number for the table must be allocated
973 ** now.
974 */
danielk19774adee202004-05-08 08:23:19 +0000975 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000976 int j1;
drhe321c292006-01-12 01:56:43 +0000977 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000978 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000979 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000980
danielk197720b1eaf2006-07-26 16:22:14 +0000981#ifndef SQLITE_OMIT_VIRTUALTABLE
982 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000983 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000984 }
985#endif
986
danielk197736963fd2005-02-19 08:18:05 +0000987 /* If the file format and encoding in the database have not been set,
988 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000989 */
drhb7654112008-01-12 12:48:07 +0000990 reg1 = pParse->regRowid = ++pParse->nMem;
991 reg2 = pParse->regRoot = ++pParse->nMem;
992 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000993 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000994 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000995 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000996 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000997 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000998 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000999 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001000 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001001 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001002 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001003
drh4794f732004-11-05 17:17:50 +00001004 /* This just creates a place-holder record in the sqlite_master table.
1005 ** The record created does not contain anything yet. It will be replaced
1006 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001007 **
drh0fa991b2009-03-21 16:19:26 +00001008 ** The rowid for the new entry is left in register pParse->regRowid.
1009 ** The root page number of the new table is left in reg pParse->regRoot.
1010 ** The rowid and root page number values are needed by the code that
1011 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001012 */
danielk1977f1a381e2006-06-16 08:01:02 +00001013#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1014 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001015 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001016 }else
1017#endif
1018 {
drh8a120f82013-11-01 17:59:53 +00001019 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001020 }
danielk1977c00da102006-01-07 13:21:04 +00001021 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001022 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1023 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1024 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1025 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001026 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001027 }
drh23bf66d2004-12-14 03:34:34 +00001028
1029 /* Normal (non-error) return. */
1030 return;
1031
1032 /* If an error occurs, we jump here */
1033begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001034 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001035 return;
drh75897232000-05-29 14:26:00 +00001036}
1037
1038/*
danielk1977c60e9b82005-01-31 12:42:29 +00001039** This macro is used to compare two strings in a case-insensitive manner.
1040** It is slightly faster than calling sqlite3StrICmp() directly, but
1041** produces larger code.
1042**
1043** WARNING: This macro is not compatible with the strcmp() family. It
1044** returns true if the two strings are equal, otherwise false.
1045*/
1046#define STRICMP(x, y) (\
1047sqlite3UpperToLower[*(unsigned char *)(x)]== \
1048sqlite3UpperToLower[*(unsigned char *)(y)] \
1049&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1050
1051/*
drh75897232000-05-29 14:26:00 +00001052** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001053**
1054** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001055** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001056** first to get things going. Then this routine is called for each
1057** column.
drh75897232000-05-29 14:26:00 +00001058*/
danielk19774adee202004-05-08 08:23:19 +00001059void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001060 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001061 int i;
drha99db3b2004-06-19 14:49:12 +00001062 char *z;
drhc9b84a12002-06-20 11:36:48 +00001063 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001064 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001065 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001066#if SQLITE_MAX_COLUMN
1067 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001068 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1069 return;
1070 }
drhbb4957f2008-03-20 14:03:29 +00001071#endif
danielk1977ae74e032008-12-23 11:11:51 +00001072 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001073 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001074 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001075 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001076 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001077 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001078 return;
1079 }
1080 }
drh75897232000-05-29 14:26:00 +00001081 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001082 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001083 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001084 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001085 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001086 return;
1087 }
drh6d4abfb2001-10-22 02:58:08 +00001088 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001089 }
drhc9b84a12002-06-20 11:36:48 +00001090 pCol = &p->aCol[p->nCol];
1091 memset(pCol, 0, sizeof(p->aCol[0]));
1092 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001093
1094 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001095 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1096 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001097 */
danielk19774f057f92004-06-08 00:02:33 +00001098 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001099 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001100 p->nCol++;
drh75897232000-05-29 14:26:00 +00001101}
1102
1103/*
drh382c0242001-10-06 16:33:02 +00001104** This routine is called by the parser while in the middle of
1105** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1106** been seen on a column. This routine sets the notNull flag on
1107** the column currently under construction.
1108*/
danielk19774adee202004-05-08 08:23:19 +00001109void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001110 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001111 p = pParse->pNewTable;
1112 if( p==0 || NEVER(p->nCol<1) ) return;
1113 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001114}
1115
1116/*
danielk197752a83fb2005-01-31 12:56:44 +00001117** Scan the column type name zType (length nType) and return the
1118** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001119**
1120** This routine does a case-independent search of zType for the
1121** substrings in the following table. If one of the substrings is
1122** found, the corresponding affinity is returned. If zType contains
1123** more than one of the substrings, entries toward the top of
1124** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001125** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001126**
1127** Substring | Affinity
1128** --------------------------------
1129** 'INT' | SQLITE_AFF_INTEGER
1130** 'CHAR' | SQLITE_AFF_TEXT
1131** 'CLOB' | SQLITE_AFF_TEXT
1132** 'TEXT' | SQLITE_AFF_TEXT
1133** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001134** 'REAL' | SQLITE_AFF_REAL
1135** 'FLOA' | SQLITE_AFF_REAL
1136** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001137**
1138** If none of the substrings in the above table are found,
1139** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001140*/
drhfdaac672013-10-04 15:30:21 +00001141char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001142 u32 h = 0;
1143 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001144 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001145
drhfdaac672013-10-04 15:30:21 +00001146 if( zIn==0 ) return aff;
1147 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001148 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001149 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001150 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001151 aff = SQLITE_AFF_TEXT;
1152 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001153 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1154 aff = SQLITE_AFF_TEXT;
1155 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1156 aff = SQLITE_AFF_TEXT;
1157 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001158 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001159 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001160 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001161#ifndef SQLITE_OMIT_FLOATING_POINT
1162 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1163 && aff==SQLITE_AFF_NUMERIC ){
1164 aff = SQLITE_AFF_REAL;
1165 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1166 && aff==SQLITE_AFF_NUMERIC ){
1167 aff = SQLITE_AFF_REAL;
1168 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1169 && aff==SQLITE_AFF_NUMERIC ){
1170 aff = SQLITE_AFF_REAL;
1171#endif
danielk1977201f7162005-02-01 02:13:29 +00001172 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001173 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001174 break;
danielk197752a83fb2005-01-31 12:56:44 +00001175 }
1176 }
drhd3037a42013-10-04 18:29:25 +00001177
1178 /* If pszEst is not NULL, store an estimate of the field size. The
1179 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001180 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001181 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001182 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001183 if( zChar ){
1184 while( zChar[0] ){
1185 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001186 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001187 sqlite3GetInt32(zChar, &v);
1188 v = v/4 + 1;
1189 if( v>255 ) v = 255;
1190 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1191 break;
1192 }
1193 zChar++;
drhfdaac672013-10-04 15:30:21 +00001194 }
drhd3037a42013-10-04 18:29:25 +00001195 }else{
1196 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001197 }
drhfdaac672013-10-04 15:30:21 +00001198 }
1199 }
danielk1977b3dff962005-02-01 01:21:55 +00001200 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001201}
1202
1203/*
drh382c0242001-10-06 16:33:02 +00001204** This routine is called by the parser while in the middle of
1205** parsing a CREATE TABLE statement. The pFirst token is the first
1206** token in the sequence of tokens that describe the type of the
1207** column currently under construction. pLast is the last token
1208** in the sequence. Use this information to construct a string
1209** that contains the typename of the column and store that string
1210** in zType.
1211*/
drh487e2622005-06-25 18:42:14 +00001212void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001213 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001214 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001215
drhc4a64fa2009-05-11 20:53:28 +00001216 p = pParse->pNewTable;
1217 if( p==0 || NEVER(p->nCol<1) ) return;
1218 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001219 assert( pCol->zType==0 || CORRUPT_DB );
1220 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001221 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001222 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001223}
1224
1225/*
danielk19777977a172004-11-09 12:44:37 +00001226** The expression is the default value for the most recently added column
1227** of the table currently under construction.
1228**
1229** Default value expressions must be constant. Raise an exception if this
1230** is not the case.
drhd9b02572001-04-15 00:37:09 +00001231**
1232** This routine is called by the parser while in the middle of
1233** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001234*/
drhb7916a72009-05-27 10:31:29 +00001235void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001236 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001237 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001238 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001239 p = pParse->pNewTable;
1240 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001241 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001242 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001243 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1244 pCol->zName);
1245 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001246 /* A copy of pExpr is used instead of the original, as pExpr contains
1247 ** tokens that point to volatile memory. The 'span' of the expression
1248 ** is required by pragma table_info.
1249 */
drh633e6d52008-07-28 19:34:53 +00001250 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001251 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1252 sqlite3DbFree(db, pCol->zDflt);
1253 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001254 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001255 }
danielk19777977a172004-11-09 12:44:37 +00001256 }
drhb7916a72009-05-27 10:31:29 +00001257 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001258}
1259
1260/*
drh4a324312001-12-21 14:30:42 +00001261** Designate the PRIMARY KEY for the table. pList is a list of names
1262** of columns that form the primary key. If pList is NULL, then the
1263** most recently added column of the table is the primary key.
1264**
1265** A table can have at most one primary key. If the table already has
1266** a primary key (and this is the second primary key) then create an
1267** error.
1268**
1269** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001270** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001271** field of the table under construction to be the index of the
1272** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1273** no INTEGER PRIMARY KEY.
1274**
1275** If the key is not an INTEGER PRIMARY KEY, then create a unique
1276** index for the key. No index is created for INTEGER PRIMARY KEYs.
1277*/
drh205f48e2004-11-05 00:43:11 +00001278void sqlite3AddPrimaryKey(
1279 Parse *pParse, /* Parsing context */
1280 ExprList *pList, /* List of field names to be indexed */
1281 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001282 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1283 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001284){
drh4a324312001-12-21 14:30:42 +00001285 Table *pTab = pParse->pNewTable;
1286 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001287 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001288 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001289 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001290 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001291 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001292 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001293 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001294 }
drh7d10d5a2008-08-20 16:35:10 +00001295 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001296 if( pList==0 ){
1297 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001298 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001299 zType = pTab->aCol[iCol].zType;
1300 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001301 }else{
drh8ea30bf2013-10-22 01:18:17 +00001302 nTerm = pList->nExpr;
1303 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001304 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001305 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001306 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1307 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001308 break;
1309 }
drh78100cc2003-08-23 22:40:53 +00001310 }
drh4a324312001-12-21 14:30:42 +00001311 }
1312 }
drh8ea30bf2013-10-22 01:18:17 +00001313 if( nTerm==1
1314 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1315 && sortOrder==SQLITE_SO_ASC
1316 ){
drh4a324312001-12-21 14:30:42 +00001317 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001318 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001319 assert( autoInc==0 || autoInc==1 );
1320 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001321 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001322 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001323#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001324 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1325 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001326#endif
drh4a324312001-12-21 14:30:42 +00001327 }else{
drhc6bd4e42013-11-02 14:37:18 +00001328 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001329 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001330 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001331 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001332 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001333 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001334 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001335 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001336 }
drhe0194f22003-02-26 13:52:51 +00001337 pList = 0;
drh4a324312001-12-21 14:30:42 +00001338 }
drhe0194f22003-02-26 13:52:51 +00001339
1340primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001341 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001342 return;
drh4a324312001-12-21 14:30:42 +00001343}
1344
1345/*
drhffe07b22005-11-03 00:41:17 +00001346** Add a new CHECK constraint to the table currently under construction.
1347*/
1348void sqlite3AddCheckConstraint(
1349 Parse *pParse, /* Parsing context */
1350 Expr *pCheckExpr /* The check expression */
1351){
1352#ifndef SQLITE_OMIT_CHECK
1353 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001354 sqlite3 *db = pParse->db;
1355 if( pTab && !IN_DECLARE_VTAB
1356 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1357 ){
drh2938f922012-03-07 19:13:29 +00001358 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1359 if( pParse->constraintName.n ){
1360 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1361 }
drh33e619f2009-05-28 01:00:55 +00001362 }else
drhffe07b22005-11-03 00:41:17 +00001363#endif
drh33e619f2009-05-28 01:00:55 +00001364 {
drh2938f922012-03-07 19:13:29 +00001365 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001366 }
drhffe07b22005-11-03 00:41:17 +00001367}
1368
1369/*
drhd3d39e92004-05-20 22:16:29 +00001370** Set the collation function of the most recently parsed table column
1371** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001372*/
danielk197739002502007-11-12 09:50:26 +00001373void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001374 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001375 int i;
danielk197739002502007-11-12 09:50:26 +00001376 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001377 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001378
danielk1977b8cbb872006-06-19 05:33:45 +00001379 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001380 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001381 db = pParse->db;
1382 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001383 if( !zColl ) return;
1384
drhc4a64fa2009-05-11 20:53:28 +00001385 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001386 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001387 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001388 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001389
1390 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1391 ** then an index may have been created on this column before the
1392 ** collation type was added. Correct this if it is the case.
1393 */
1394 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001395 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001396 if( pIdx->aiColumn[0]==i ){
1397 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001398 }
1399 }
danielk197739002502007-11-12 09:50:26 +00001400 }else{
drh633e6d52008-07-28 19:34:53 +00001401 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001402 }
danielk19777cedc8d2004-06-10 10:50:08 +00001403}
1404
danielk1977466be562004-06-10 02:16:01 +00001405/*
1406** This function returns the collation sequence for database native text
1407** encoding identified by the string zName, length nName.
1408**
1409** If the requested collation sequence is not available, or not available
1410** in the database native encoding, the collation factory is invoked to
1411** request it. If the collation factory does not supply such a sequence,
1412** and the sequence is available in another text encoding, then that is
1413** returned instead.
1414**
1415** If no versions of the requested collations sequence are available, or
1416** another error occurs, NULL is returned and an error message written into
1417** pParse.
drha34001c2007-02-02 12:44:37 +00001418**
1419** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1420** invokes the collation factory if the named collation cannot be found
1421** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001422**
1423** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001424*/
drhc4a64fa2009-05-11 20:53:28 +00001425CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001426 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001427 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001428 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001429 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001430
drhc4a64fa2009-05-11 20:53:28 +00001431 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001432 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001433 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001434 }
1435
danielk19770202b292004-06-09 09:55:16 +00001436 return pColl;
1437}
1438
1439
drh8e2ca022002-06-17 17:07:19 +00001440/*
drh3f7d4e42004-07-24 14:35:58 +00001441** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001442**
1443** The schema cookie is used to determine when the schema for the
1444** database changes. After each schema change, the cookie value
1445** changes. When a process first reads the schema it records the
1446** cookie. Thereafter, whenever it goes to access the database,
1447** it checks the cookie to make sure the schema has not changed
1448** since it was last read.
1449**
1450** This plan is not completely bullet-proof. It is possible for
1451** the schema to change multiple times and for the cookie to be
1452** set back to prior value. But schema changes are infrequent
1453** and the probability of hitting the same cookie value is only
1454** 1 chance in 2^32. So we're safe enough.
1455*/
drh9cbf3422008-01-17 16:22:13 +00001456void sqlite3ChangeCookie(Parse *pParse, int iDb){
1457 int r1 = sqlite3GetTempReg(pParse);
1458 sqlite3 *db = pParse->db;
1459 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001460 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001461 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001462 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001463 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001464}
1465
1466/*
drh969fa7c2002-02-18 18:30:32 +00001467** Measure the number of characters needed to output the given
1468** identifier. The number returned includes any quotes used
1469** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001470**
1471** The estimate is conservative. It might be larger that what is
1472** really needed.
drh969fa7c2002-02-18 18:30:32 +00001473*/
1474static int identLength(const char *z){
1475 int n;
drh17f71932002-02-21 12:01:27 +00001476 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001477 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001478 }
drh234c39d2004-07-24 03:30:47 +00001479 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001480}
1481
1482/*
danielk19771b870de2009-03-14 08:37:23 +00001483** The first parameter is a pointer to an output buffer. The second
1484** parameter is a pointer to an integer that contains the offset at
1485** which to write into the output buffer. This function copies the
1486** nul-terminated string pointed to by the third parameter, zSignedIdent,
1487** to the specified offset in the buffer and updates *pIdx to refer
1488** to the first byte after the last byte written before returning.
1489**
1490** If the string zSignedIdent consists entirely of alpha-numeric
1491** characters, does not begin with a digit and is not an SQL keyword,
1492** then it is copied to the output buffer exactly as it is. Otherwise,
1493** it is quoted using double-quotes.
1494*/
drhc4a64fa2009-05-11 20:53:28 +00001495static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001496 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001497 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001498 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001499
drh17f71932002-02-21 12:01:27 +00001500 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001501 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001502 }
drhc7407522014-01-10 20:38:12 +00001503 needQuote = sqlite3Isdigit(zIdent[0])
1504 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1505 || zIdent[j]!=0
1506 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001507
drh234c39d2004-07-24 03:30:47 +00001508 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001509 for(j=0; zIdent[j]; j++){
1510 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001511 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001512 }
drh234c39d2004-07-24 03:30:47 +00001513 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001514 z[i] = 0;
1515 *pIdx = i;
1516}
1517
1518/*
1519** Generate a CREATE TABLE statement appropriate for the given
1520** table. Memory to hold the text of the statement is obtained
1521** from sqliteMalloc() and must be freed by the calling function.
1522*/
drh1d34fde2009-02-03 15:50:33 +00001523static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001524 int i, k, n;
1525 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001526 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001527 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001528 n = 0;
drh234c39d2004-07-24 03:30:47 +00001529 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001530 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001531 }
1532 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001533 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001534 zSep = "";
1535 zSep2 = ",";
1536 zEnd = ")";
1537 }else{
1538 zSep = "\n ";
1539 zSep2 = ",\n ";
1540 zEnd = "\n)";
1541 }
drhe0bc4042002-06-25 01:09:11 +00001542 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001543 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001544 if( zStmt==0 ){
1545 db->mallocFailed = 1;
1546 return 0;
1547 }
drhbdb339f2009-02-02 18:03:21 +00001548 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001549 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001550 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001551 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001552 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001553 static const char * const azType[] = {
drhc4a64fa2009-05-11 20:53:28 +00001554 /* SQLITE_AFF_NONE */ "",
drh7ea31cc2014-09-18 14:36:00 +00001555 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001556 /* SQLITE_AFF_NUMERIC */ " NUM",
1557 /* SQLITE_AFF_INTEGER */ " INT",
1558 /* SQLITE_AFF_REAL */ " REAL"
1559 };
1560 int len;
1561 const char *zType;
1562
drh5bb3eb92007-05-04 13:15:55 +00001563 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001564 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001565 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001566 identPut(zStmt, &k, pCol->zName);
drh7ea31cc2014-09-18 14:36:00 +00001567 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1568 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001569 testcase( pCol->affinity==SQLITE_AFF_NONE );
drh7ea31cc2014-09-18 14:36:00 +00001570 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001571 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1572 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1573 testcase( pCol->affinity==SQLITE_AFF_REAL );
1574
drh7ea31cc2014-09-18 14:36:00 +00001575 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
drhc4a64fa2009-05-11 20:53:28 +00001576 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001577 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001578 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001579 memcpy(&zStmt[k], zType, len);
1580 k += len;
1581 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001582 }
drh5bb3eb92007-05-04 13:15:55 +00001583 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001584 return zStmt;
1585}
1586
1587/*
drh7f9c5db2013-10-23 00:32:58 +00001588** Resize an Index object to hold N columns total. Return SQLITE_OK
1589** on success and SQLITE_NOMEM on an OOM error.
1590*/
1591static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1592 char *zExtra;
1593 int nByte;
1594 if( pIdx->nColumn>=N ) return SQLITE_OK;
1595 assert( pIdx->isResized==0 );
1596 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1597 zExtra = sqlite3DbMallocZero(db, nByte);
1598 if( zExtra==0 ) return SQLITE_NOMEM;
1599 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1600 pIdx->azColl = (char**)zExtra;
1601 zExtra += sizeof(char*)*N;
1602 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1603 pIdx->aiColumn = (i16*)zExtra;
1604 zExtra += sizeof(i16)*N;
1605 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1606 pIdx->aSortOrder = (u8*)zExtra;
1607 pIdx->nColumn = N;
1608 pIdx->isResized = 1;
1609 return SQLITE_OK;
1610}
1611
1612/*
drhfdaac672013-10-04 15:30:21 +00001613** Estimate the total row width for a table.
1614*/
drhe13e9f52013-10-05 19:18:00 +00001615static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001616 unsigned wTable = 0;
1617 const Column *pTabCol;
1618 int i;
1619 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1620 wTable += pTabCol->szEst;
1621 }
1622 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001623 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001624}
1625
1626/*
drhe13e9f52013-10-05 19:18:00 +00001627** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001628*/
drhe13e9f52013-10-05 19:18:00 +00001629static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001630 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001631 int i;
1632 const Column *aCol = pIdx->pTable->aCol;
1633 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001634 i16 x = pIdx->aiColumn[i];
1635 assert( x<pIdx->pTable->nCol );
1636 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001637 }
drhe13e9f52013-10-05 19:18:00 +00001638 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001639}
1640
drh7f9c5db2013-10-23 00:32:58 +00001641/* Return true if value x is found any of the first nCol entries of aiCol[]
1642*/
1643static int hasColumn(const i16 *aiCol, int nCol, int x){
1644 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1645 return 0;
1646}
1647
1648/*
drhc6bd4e42013-11-02 14:37:18 +00001649** This routine runs at the end of parsing a CREATE TABLE statement that
1650** has a WITHOUT ROWID clause. The job of this routine is to convert both
1651** internal schema data structures and the generated VDBE code so that they
1652** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1653** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001654**
drhc6bd4e42013-11-02 14:37:18 +00001655** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1656** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1657** data storage is a covering index btree.
1658** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001659** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001660** identified by the sqlite_master table entry of the table itself.
1661** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1662** schema to the rootpage from the main table.
1663** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1664** (5) Add all table columns to the PRIMARY KEY Index object
1665** so that the PRIMARY KEY is a covering index. The surplus
1666** columns are part of KeyInfo.nXField and are not used for
1667** sorting or lookup or uniqueness checks.
1668** (6) Replace the rowid tail on all automatically generated UNIQUE
1669** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001670*/
1671static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1672 Index *pIdx;
1673 Index *pPk;
1674 int nPk;
1675 int i, j;
1676 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001677 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001678
1679 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001680 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001681 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001682 */
1683 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001684 assert( v );
1685 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1686 }
1687
1688 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1689 ** table entry.
1690 */
1691 if( pParse->addrSkipPK ){
1692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001694 }
1695
1696 /* 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;
1701 pList = sqlite3ExprListAppend(pParse, 0, 0);
1702 if( pList==0 ) return;
1703 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1704 pTab->aCol[pTab->iPKey].zName);
1705 pList->a[0].sortOrder = pParse->iPkSortOrder;
1706 assert( pParse->pNewTable==pTab );
1707 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1708 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001709 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001710 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001711 }else{
1712 pPk = sqlite3PrimaryKeyIndex(pTab);
drhe385d882014-12-28 22:10:51 +00001713 /*
1714 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1715 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1716 ** code assumes the PRIMARY KEY contains no repeated columns.
1717 */
1718 for(i=j=1; i<pPk->nKeyCol; i++){
1719 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1720 pPk->nColumn--;
1721 }else{
1722 pPk->aiColumn[j++] = pPk->aiColumn[i];
1723 }
1724 }
1725 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001726 }
drh12826092013-11-05 22:39:17 +00001727 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001728 assert( pPk!=0 );
1729 nPk = pPk->nKeyCol;
1730
drh1ffede82015-01-30 20:59:27 +00001731 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1732 ** do not enforce this for imposter tables.) */
1733 if( !db->init.imposterTable ){
1734 for(i=0; i<nPk; i++){
1735 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1736 }
1737 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001738 }
1739
drhc6bd4e42013-11-02 14:37:18 +00001740 /* The root page of the PRIMARY KEY is the table root page */
1741 pPk->tnum = pTab->tnum;
1742
drh7f9c5db2013-10-23 00:32:58 +00001743 /* Update the in-memory representation of all UNIQUE indices by converting
1744 ** the final rowid column into one or more columns of the PRIMARY KEY.
1745 */
1746 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1747 int n;
drh48dd1d82014-05-27 18:18:58 +00001748 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001749 for(i=n=0; i<nPk; i++){
1750 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1751 }
drh5a9a37b2013-11-05 17:30:04 +00001752 if( n==0 ){
1753 /* This index is a superset of the primary key */
1754 pIdx->nColumn = pIdx->nKeyCol;
1755 continue;
1756 }
drh7f9c5db2013-10-23 00:32:58 +00001757 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1758 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001759 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001760 pIdx->aiColumn[j] = pPk->aiColumn[i];
1761 pIdx->azColl[j] = pPk->azColl[i];
1762 j++;
1763 }
1764 }
drh00012df2013-11-05 01:59:07 +00001765 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1766 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001767 }
1768
1769 /* Add all table columns to the PRIMARY KEY index
1770 */
1771 if( nPk<pTab->nCol ){
1772 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1773 for(i=0, j=nPk; i<pTab->nCol; i++){
1774 if( !hasColumn(pPk->aiColumn, j, i) ){
1775 assert( j<pPk->nColumn );
1776 pPk->aiColumn[j] = i;
1777 pPk->azColl[j] = "BINARY";
1778 j++;
1779 }
1780 }
1781 assert( pPk->nColumn==j );
1782 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001783 }else{
1784 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001785 }
1786}
1787
drhfdaac672013-10-04 15:30:21 +00001788/*
drh75897232000-05-29 14:26:00 +00001789** This routine is called to report the final ")" that terminates
1790** a CREATE TABLE statement.
1791**
drhf57b3392001-10-08 13:22:32 +00001792** The table structure that other action routines have been building
1793** is added to the internal hash tables, assuming no errors have
1794** occurred.
drh75897232000-05-29 14:26:00 +00001795**
drh1d85d932004-02-14 23:05:52 +00001796** An entry for the table is made in the master table on disk, unless
1797** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001798** it means we are reading the sqlite_master table because we just
1799** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001800** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001801** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001802**
1803** If the pSelect argument is not NULL, it means that this routine
1804** was called to create a table generated from a
1805** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1806** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001807*/
danielk197719a8e7e2005-03-17 05:03:38 +00001808void sqlite3EndTable(
1809 Parse *pParse, /* Parse context */
1810 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001811 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1812 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001813 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1814){
drhfdaac672013-10-04 15:30:21 +00001815 Table *p; /* The new table */
1816 sqlite3 *db = pParse->db; /* The database connection */
1817 int iDb; /* Database in which the table lives */
1818 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001819
drh5969da42013-10-21 02:14:45 +00001820 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1821 return;
danielk1977261919c2005-12-06 12:52:59 +00001822 }
drh28037572000-08-02 13:47:41 +00001823 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001824 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001825
danielk1977517eb642004-06-07 10:00:31 +00001826 assert( !db->init.busy || !pSelect );
1827
drhc6bd4e42013-11-02 14:37:18 +00001828 /* If the db->init.busy is 1 it means we are reading the SQL off the
1829 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1830 ** So do not write to the disk again. Extract the root page number
1831 ** for the table from the db->init.newTnum field. (The page number
1832 ** should have been put there by the sqliteOpenCb routine.)
1833 */
1834 if( db->init.busy ){
1835 p->tnum = db->init.newTnum;
1836 }
1837
1838 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001839 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001840 if( (p->tabFlags & TF_Autoincrement) ){
1841 sqlite3ErrorMsg(pParse,
1842 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1843 return;
1844 }
drh5969da42013-10-21 02:14:45 +00001845 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001846 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001847 }else{
1848 p->tabFlags |= TF_WithoutRowid;
1849 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001850 }
1851 }
1852
drhb9bb7c12006-06-11 23:41:55 +00001853 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001854
drhffe07b22005-11-03 00:41:17 +00001855#ifndef SQLITE_OMIT_CHECK
1856 /* Resolve names in all CHECK constraint expressions.
1857 */
1858 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001859 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001860 }
1861#endif /* !defined(SQLITE_OMIT_CHECK) */
1862
drhe13e9f52013-10-05 19:18:00 +00001863 /* Estimate the average row size for the table and for all implied indices */
1864 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001865 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001866 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001867 }
1868
drhe3c41372001-09-17 20:25:58 +00001869 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001870 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001871 **
drhe0bc4042002-06-25 01:09:11 +00001872 ** If this is a TEMPORARY table, write the entry into the auxiliary
1873 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001874 */
drh1d85d932004-02-14 23:05:52 +00001875 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001876 int n;
drhd8bc7082000-06-07 23:51:50 +00001877 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001878 char *zType; /* "view" or "table" */
1879 char *zType2; /* "VIEW" or "TABLE" */
1880 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001881
danielk19774adee202004-05-08 08:23:19 +00001882 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001883 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001884
drh66a51672008-01-03 00:01:23 +00001885 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001886
drh0fa991b2009-03-21 16:19:26 +00001887 /*
1888 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001889 */
drh4ff6dfa2002-03-03 23:06:00 +00001890 if( p->pSelect==0 ){
1891 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001892 zType = "table";
1893 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001894#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001895 }else{
1896 /* A view */
drh4794f732004-11-05 17:17:50 +00001897 zType = "view";
1898 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001899#endif
drh4ff6dfa2002-03-03 23:06:00 +00001900 }
danielk1977517eb642004-06-07 10:00:31 +00001901
danielk1977517eb642004-06-07 10:00:31 +00001902 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1903 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001904 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001905 **
1906 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1907 ** suitable state to query for the column names and types to be used
1908 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001909 **
1910 ** A shared-cache write-lock is not required to write to the new table,
1911 ** as a schema-lock must have already been obtained to create it. Since
1912 ** a schema-lock excludes all other database users, the write-lock would
1913 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001914 */
1915 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001916 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001917 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001918
danielk19776ab3a2e2009-02-19 14:39:25 +00001919 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001920 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001921 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001922 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001923 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001924 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001925 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001926 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001927 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001928 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001929 assert( p->aCol==0 );
1930 p->nCol = pSelTab->nCol;
1931 p->aCol = pSelTab->aCol;
1932 pSelTab->nCol = 0;
1933 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001934 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001935 }
1936 }
drh4794f732004-11-05 17:17:50 +00001937
drh4794f732004-11-05 17:17:50 +00001938 /* Compute the complete text of the CREATE statement */
1939 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001940 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001941 }else{
drh8ea30bf2013-10-22 01:18:17 +00001942 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1943 n = (int)(pEnd2->z - pParse->sNameToken.z);
1944 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001945 zStmt = sqlite3MPrintf(db,
1946 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1947 );
drh4794f732004-11-05 17:17:50 +00001948 }
1949
1950 /* A slot for the record has already been allocated in the
1951 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001952 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001953 */
1954 sqlite3NestedParse(pParse,
1955 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001956 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1957 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001958 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001959 zType,
1960 p->zName,
1961 p->zName,
drhb7654112008-01-12 12:48:07 +00001962 pParse->regRoot,
1963 zStmt,
1964 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001965 );
drh633e6d52008-07-28 19:34:53 +00001966 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001967 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001968
1969#ifndef SQLITE_OMIT_AUTOINCREMENT
1970 /* Check to see if we need to create an sqlite_sequence table for
1971 ** keeping track of autoincrement keys.
1972 */
drh7d10d5a2008-08-20 16:35:10 +00001973 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001974 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001975 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001976 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001977 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001978 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1979 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001980 );
1981 }
1982 }
1983#endif
drh4794f732004-11-05 17:17:50 +00001984
1985 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001986 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001987 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001988 }
drh17e9e292003-02-01 13:53:28 +00001989
drh2958a4e2004-11-12 03:56:15 +00001990
drh17e9e292003-02-01 13:53:28 +00001991 /* Add the table to the in-memory representation of the database.
1992 */
drh8af73d42009-05-13 22:58:28 +00001993 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001994 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001995 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001996 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00001997 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00001998 if( pOld ){
1999 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002000 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002001 return;
drh17e9e292003-02-01 13:53:28 +00002002 }
drh17e9e292003-02-01 13:53:28 +00002003 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002004 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002005
2006#ifndef SQLITE_OMIT_ALTERTABLE
2007 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002008 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002009 int nName;
drh5969da42013-10-21 02:14:45 +00002010 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002011 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002012 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002013 }
drh1bd10f82008-12-10 21:19:56 +00002014 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002015 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002016 }
2017#endif
drh17e9e292003-02-01 13:53:28 +00002018 }
drh75897232000-05-29 14:26:00 +00002019}
2020
drhb7f91642004-10-31 02:22:47 +00002021#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002022/*
drha76b5df2002-02-23 02:32:10 +00002023** The parser calls this routine in order to create a new VIEW
2024*/
danielk19774adee202004-05-08 08:23:19 +00002025void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002026 Parse *pParse, /* The parsing context */
2027 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002028 Token *pName1, /* The token that holds the name of the view */
2029 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002030 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002031 int isTemp, /* TRUE for a TEMPORARY view */
2032 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002033){
drha76b5df2002-02-23 02:32:10 +00002034 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002035 int n;
drhb7916a72009-05-27 10:31:29 +00002036 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002037 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002038 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002039 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002040 int iDb;
drh17435752007-08-16 04:30:38 +00002041 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002042
drh7c3d64f2005-06-06 15:32:08 +00002043 if( pParse->nVar>0 ){
2044 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002045 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002046 return;
2047 }
drhfdd48a72006-09-11 23:45:48 +00002048 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002049 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002050 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002051 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002052 return;
2053 }
danielk1977ef2cb632004-05-29 02:37:19 +00002054 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002055 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002056 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2057 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002058 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002059 return;
2060 }
drh174b6192002-12-03 02:22:52 +00002061
drh4b59ab52002-08-24 18:24:51 +00002062 /* Make a copy of the entire SELECT statement that defines the view.
2063 ** This will force all the Expr.token.z values to be dynamically
2064 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002065 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002066 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002067 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002068 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002069 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002070 return;
2071 }
drh17435752007-08-16 04:30:38 +00002072 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002073 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002074 }
drh4b59ab52002-08-24 18:24:51 +00002075
2076 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2077 ** the end.
2078 */
drha76b5df2002-02-23 02:32:10 +00002079 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002080 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002081 sEnd.z += sEnd.n;
2082 }
2083 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002084 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002085 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002086 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002087 sEnd.z = &z[n-1];
2088 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002089
danielk19774adee202004-05-08 08:23:19 +00002090 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002091 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002092 return;
drh417be792002-03-03 18:59:40 +00002093}
drhb7f91642004-10-31 02:22:47 +00002094#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002095
danielk1977fe3fcbe22006-06-12 12:08:45 +00002096#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002097/*
2098** The Table structure pTable is really a VIEW. Fill in the names of
2099** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002100** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002101*/
danielk19774adee202004-05-08 08:23:19 +00002102int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002103 Table *pSelTab; /* A fake table from which we get the result set */
2104 Select *pSel; /* Copy of the SELECT that implements the view */
2105 int nErr = 0; /* Number of errors encountered */
2106 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002107 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002108 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002109
2110 assert( pTable );
2111
danielk1977fe3fcbe22006-06-12 12:08:45 +00002112#ifndef SQLITE_OMIT_VIRTUALTABLE
2113 if( sqlite3VtabCallConnect(pParse, pTable) ){
2114 return SQLITE_ERROR;
2115 }
drh4cbdda92006-06-14 19:00:20 +00002116 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002117#endif
2118
2119#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002120 /* A positive nCol means the columns names for this view are
2121 ** already known.
2122 */
2123 if( pTable->nCol>0 ) return 0;
2124
2125 /* A negative nCol is a special marker meaning that we are currently
2126 ** trying to compute the column names. If we enter this routine with
2127 ** a negative nCol, it means two or more views form a loop, like this:
2128 **
2129 ** CREATE VIEW one AS SELECT * FROM two;
2130 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002131 **
drh768578e2009-05-12 00:40:12 +00002132 ** Actually, the error above is now caught prior to reaching this point.
2133 ** But the following test is still important as it does come up
2134 ** in the following:
2135 **
2136 ** CREATE TABLE main.ex1(a);
2137 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2138 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002139 */
2140 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002141 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002142 return 1;
2143 }
drh85c23c62005-08-20 03:03:04 +00002144 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002145
2146 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002147 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2148 ** "*" elements in the results set of the view and will assign cursors
2149 ** to the elements of the FROM clause. But we do not want these changes
2150 ** to be permanent. So the computation is done on a copy of the SELECT
2151 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002152 */
drh9b3187e2005-01-18 14:45:47 +00002153 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002154 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002155 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002156 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002157 n = pParse->nTab;
2158 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2159 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002160 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002161#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002162 xAuth = db->xAuth;
2163 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002164 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002165 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002166#else
drh7d10d5a2008-08-20 16:35:10 +00002167 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002168#endif
drhd9da78a2009-03-24 15:08:09 +00002169 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002170 pParse->nTab = n;
2171 if( pSelTab ){
2172 assert( pTable->aCol==0 );
2173 pTable->nCol = pSelTab->nCol;
2174 pTable->aCol = pSelTab->aCol;
2175 pSelTab->nCol = 0;
2176 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002177 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002178 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002179 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002180 }else{
2181 pTable->nCol = 0;
2182 nErr++;
2183 }
drh633e6d52008-07-28 19:34:53 +00002184 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002185 } else {
drh417be792002-03-03 18:59:40 +00002186 nErr++;
2187 }
drhb7f91642004-10-31 02:22:47 +00002188#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002189 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002190}
2191#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002192
drhb7f91642004-10-31 02:22:47 +00002193#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002194/*
drh8bf8dc92003-05-17 17:35:10 +00002195** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002196*/
drh9bb575f2004-09-06 17:24:11 +00002197static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002198 HashElem *i;
drh21206082011-04-04 18:22:02 +00002199 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002200 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002201 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002202 Table *pTab = sqliteHashData(i);
2203 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002204 sqliteDeleteColumnNames(db, pTab);
2205 pTab->aCol = 0;
2206 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002207 }
2208 }
drh8bf8dc92003-05-17 17:35:10 +00002209 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002210}
drhb7f91642004-10-31 02:22:47 +00002211#else
2212# define sqliteViewResetAll(A,B)
2213#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002214
drh75897232000-05-29 14:26:00 +00002215/*
danielk1977a0bf2652004-11-04 14:30:04 +00002216** This function is called by the VDBE to adjust the internal schema
2217** used by SQLite when the btree layer moves a table root page. The
2218** root-page of a table or index in database iDb has changed from iFrom
2219** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002220**
2221** Ticket #1728: The symbol table might still contain information
2222** on tables and/or indices that are the process of being deleted.
2223** If you are unlucky, one of those deleted indices or tables might
2224** have the same rootpage number as the real table or index that is
2225** being moved. So we cannot stop searching after the first match
2226** because the first match might be for one of the deleted indices
2227** or tables and not the table/index that is actually being moved.
2228** We must continue looping until all tables and indices with
2229** rootpage==iFrom have been converted to have a rootpage of iTo
2230** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002231*/
2232#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002233void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002234 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002235 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002236 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002237
drhcdf011d2011-04-04 21:25:28 +00002238 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2239 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002240 pHash = &pDb->pSchema->tblHash;
2241 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002242 Table *pTab = sqliteHashData(pElem);
2243 if( pTab->tnum==iFrom ){
2244 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002245 }
2246 }
danielk1977da184232006-01-05 11:34:32 +00002247 pHash = &pDb->pSchema->idxHash;
2248 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002249 Index *pIdx = sqliteHashData(pElem);
2250 if( pIdx->tnum==iFrom ){
2251 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002252 }
2253 }
danielk1977a0bf2652004-11-04 14:30:04 +00002254}
2255#endif
2256
2257/*
2258** Write code to erase the table with root-page iTable from database iDb.
2259** Also write code to modify the sqlite_master table and internal schema
2260** if a root-page of another table is moved by the btree-layer whilst
2261** erasing iTable (this can happen with an auto-vacuum database).
2262*/
drh4e0cff62004-11-05 05:10:28 +00002263static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2264 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002265 int r1 = sqlite3GetTempReg(pParse);
2266 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002267 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002268#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002269 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002270 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002271 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002272 ** reflect this.
2273 **
drh0fa991b2009-03-21 16:19:26 +00002274 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002275 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2276 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002277 */
danielk197763e3e9f2004-11-05 09:19:27 +00002278 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002279 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2280 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002281#endif
drhb7654112008-01-12 12:48:07 +00002282 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002283}
2284
2285/*
2286** Write VDBE code to erase table pTab and all associated indices on disk.
2287** Code to update the sqlite_master tables and internal schema definitions
2288** in case a root-page belonging to another table is moved by the btree layer
2289** is also added (this can happen with an auto-vacuum database).
2290*/
drh4e0cff62004-11-05 05:10:28 +00002291static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002292#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002293 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002294 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2295 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002296 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002297 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002298 }
2299#else
2300 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2301 ** is not defined), then it is important to call OP_Destroy on the
2302 ** table and index root-pages in order, starting with the numerically
2303 ** largest root-page number. This guarantees that none of the root-pages
2304 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2305 ** following were coded:
2306 **
2307 ** OP_Destroy 4 0
2308 ** ...
2309 ** OP_Destroy 5 0
2310 **
2311 ** and root page 5 happened to be the largest root-page number in the
2312 ** database, then root page 5 would be moved to page 4 by the
2313 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2314 ** a free-list page.
2315 */
2316 int iTab = pTab->tnum;
2317 int iDestroyed = 0;
2318
2319 while( 1 ){
2320 Index *pIdx;
2321 int iLargest = 0;
2322
2323 if( iDestroyed==0 || iTab<iDestroyed ){
2324 iLargest = iTab;
2325 }
2326 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2327 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002328 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002329 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2330 iLargest = iIdx;
2331 }
2332 }
danielk1977da184232006-01-05 11:34:32 +00002333 if( iLargest==0 ){
2334 return;
2335 }else{
2336 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002337 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002338 destroyRootPage(pParse, iLargest, iDb);
2339 iDestroyed = iLargest;
2340 }
danielk1977a0bf2652004-11-04 14:30:04 +00002341 }
2342#endif
2343}
2344
2345/*
drh74e7c8f2011-10-21 19:06:32 +00002346** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002347** after a DROP INDEX or DROP TABLE command.
2348*/
2349static void sqlite3ClearStatTables(
2350 Parse *pParse, /* The parsing context */
2351 int iDb, /* The database number */
2352 const char *zType, /* "idx" or "tbl" */
2353 const char *zName /* Name of index or table */
2354){
drha5ae4c32011-08-07 01:31:52 +00002355 int i;
2356 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002357 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002358 char zTab[24];
2359 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2360 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002361 sqlite3NestedParse(pParse,
2362 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002363 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002364 );
2365 }
2366 }
2367}
2368
2369/*
drhfaacf172011-08-12 01:51:45 +00002370** Generate code to drop a table.
2371*/
2372void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2373 Vdbe *v;
2374 sqlite3 *db = pParse->db;
2375 Trigger *pTrigger;
2376 Db *pDb = &db->aDb[iDb];
2377
2378 v = sqlite3GetVdbe(pParse);
2379 assert( v!=0 );
2380 sqlite3BeginWriteOperation(pParse, 1, iDb);
2381
2382#ifndef SQLITE_OMIT_VIRTUALTABLE
2383 if( IsVirtual(pTab) ){
2384 sqlite3VdbeAddOp0(v, OP_VBegin);
2385 }
2386#endif
2387
2388 /* Drop all triggers associated with the table being dropped. Code
2389 ** is generated to remove entries from sqlite_master and/or
2390 ** sqlite_temp_master if required.
2391 */
2392 pTrigger = sqlite3TriggerList(pParse, pTab);
2393 while( pTrigger ){
2394 assert( pTrigger->pSchema==pTab->pSchema ||
2395 pTrigger->pSchema==db->aDb[1].pSchema );
2396 sqlite3DropTriggerPtr(pParse, pTrigger);
2397 pTrigger = pTrigger->pNext;
2398 }
2399
2400#ifndef SQLITE_OMIT_AUTOINCREMENT
2401 /* Remove any entries of the sqlite_sequence table associated with
2402 ** the table being dropped. This is done before the table is dropped
2403 ** at the btree level, in case the sqlite_sequence table needs to
2404 ** move as a result of the drop (can happen in auto-vacuum mode).
2405 */
2406 if( pTab->tabFlags & TF_Autoincrement ){
2407 sqlite3NestedParse(pParse,
2408 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2409 pDb->zName, pTab->zName
2410 );
2411 }
2412#endif
2413
2414 /* Drop all SQLITE_MASTER table and index entries that refer to the
2415 ** table. The program name loops through the master table and deletes
2416 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002417 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002418 ** created in the temp database that refers to a table in another
2419 ** database.
2420 */
2421 sqlite3NestedParse(pParse,
2422 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2423 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002424 if( !isView && !IsVirtual(pTab) ){
2425 destroyTable(pParse, pTab);
2426 }
2427
2428 /* Remove the table entry from SQLite's internal schema and modify
2429 ** the schema cookie.
2430 */
2431 if( IsVirtual(pTab) ){
2432 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2433 }
2434 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2435 sqlite3ChangeCookie(pParse, iDb);
2436 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002437}
2438
2439/*
drh75897232000-05-29 14:26:00 +00002440** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002441** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002442*/
drha0733842005-12-29 01:11:36 +00002443void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002444 Table *pTab;
drh75897232000-05-29 14:26:00 +00002445 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002446 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002447 int iDb;
drh75897232000-05-29 14:26:00 +00002448
drh8af73d42009-05-13 22:58:28 +00002449 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002450 goto exit_drop_table;
2451 }
drh8af73d42009-05-13 22:58:28 +00002452 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002453 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002454 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002455 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002456 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002457 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002458
drha0733842005-12-29 01:11:36 +00002459 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002460 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002461 goto exit_drop_table;
2462 }
danielk1977da184232006-01-05 11:34:32 +00002463 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002464 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002465
2466 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2467 ** it is initialized.
2468 */
2469 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2470 goto exit_drop_table;
2471 }
drhe5f9c642003-01-13 23:27:31 +00002472#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002473 {
2474 int code;
danielk1977da184232006-01-05 11:34:32 +00002475 const char *zTab = SCHEMA_TABLE(iDb);
2476 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002477 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002478 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002479 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002480 }
drhe5f9c642003-01-13 23:27:31 +00002481 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002482 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002483 code = SQLITE_DROP_TEMP_VIEW;
2484 }else{
2485 code = SQLITE_DROP_VIEW;
2486 }
danielk19774b2688a2006-06-20 11:01:07 +00002487#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002488 }else if( IsVirtual(pTab) ){
2489 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002490 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002491#endif
drhe5f9c642003-01-13 23:27:31 +00002492 }else{
danielk197753c0f742005-03-29 03:10:59 +00002493 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002494 code = SQLITE_DROP_TEMP_TABLE;
2495 }else{
2496 code = SQLITE_DROP_TABLE;
2497 }
2498 }
danielk1977f1a381e2006-06-16 08:01:02 +00002499 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002500 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002501 }
danielk1977a8858102004-05-28 12:11:21 +00002502 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2503 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002504 }
drhe5f9c642003-01-13 23:27:31 +00002505 }
2506#endif
drh08ccfaa2011-10-07 23:52:25 +00002507 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2508 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002509 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002510 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002511 }
danielk1977576ec6b2005-01-21 11:55:25 +00002512
2513#ifndef SQLITE_OMIT_VIEW
2514 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2515 ** on a table.
2516 */
danielk1977a8858102004-05-28 12:11:21 +00002517 if( isView && pTab->pSelect==0 ){
2518 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2519 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002520 }
danielk1977a8858102004-05-28 12:11:21 +00002521 if( !isView && pTab->pSelect ){
2522 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2523 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002524 }
danielk1977576ec6b2005-01-21 11:55:25 +00002525#endif
drh75897232000-05-29 14:26:00 +00002526
drh1ccde152000-06-17 13:12:39 +00002527 /* Generate code to remove the table from the master table
2528 ** on disk.
2529 */
danielk19774adee202004-05-08 08:23:19 +00002530 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002531 if( v ){
drh77658e22007-12-04 16:54:52 +00002532 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002533 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002534 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002535 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002536 }
danielk1977a8858102004-05-28 12:11:21 +00002537
2538exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002539 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002540}
2541
2542/*
drhc2eef3b2002-08-31 18:53:06 +00002543** This routine is called to create a new foreign key on the table
2544** currently under construction. pFromCol determines which columns
2545** in the current table point to the foreign key. If pFromCol==0 then
2546** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002547** the table referred to (a.k.a the "parent" table). pToCol is a list
2548** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002549** information about the conflict resolution algorithms specified
2550** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2551**
2552** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002553** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002554**
2555** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002556** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002557*/
danielk19774adee202004-05-08 08:23:19 +00002558void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002559 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002560 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002561 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002562 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002563 int flags /* Conflict resolution algorithms. */
2564){
danielk197718576932008-08-06 13:47:40 +00002565 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002566#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002567 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002568 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002569 Table *p = pParse->pNewTable;
2570 int nByte;
2571 int i;
2572 int nCol;
2573 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002574
2575 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002576 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002577 if( pFromCol==0 ){
2578 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002579 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002580 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002581 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002582 " should reference only one column of table %T",
2583 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002584 goto fk_end;
2585 }
2586 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002587 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002588 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002589 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002590 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002591 goto fk_end;
2592 }else{
danielk19770202b292004-06-09 09:55:16 +00002593 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002594 }
drhe61922a2009-05-02 13:29:37 +00002595 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002596 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002597 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002598 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002599 }
2600 }
drh633e6d52008-07-28 19:34:53 +00002601 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002602 if( pFKey==0 ){
2603 goto fk_end;
2604 }
drhc2eef3b2002-08-31 18:53:06 +00002605 pFKey->pFrom = p;
2606 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002607 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002608 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002609 memcpy(z, pTo->z, pTo->n);
2610 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002611 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002612 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002613 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002614 if( pFromCol==0 ){
2615 pFKey->aCol[0].iFrom = p->nCol-1;
2616 }else{
2617 for(i=0; i<nCol; i++){
2618 int j;
2619 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002620 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002621 pFKey->aCol[i].iFrom = j;
2622 break;
2623 }
2624 }
2625 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002626 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002627 "unknown column \"%s\" in foreign key definition",
2628 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002629 goto fk_end;
2630 }
2631 }
2632 }
2633 if( pToCol ){
2634 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002635 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002636 pFKey->aCol[i].zCol = z;
2637 memcpy(z, pToCol->a[i].zName, n);
2638 z[n] = 0;
2639 z += n+1;
2640 }
2641 }
2642 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002643 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2644 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002645
drh21206082011-04-04 18:22:02 +00002646 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002647 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002648 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002649 );
danf59c5ca2009-09-22 16:55:38 +00002650 if( pNextTo==pFKey ){
2651 db->mallocFailed = 1;
2652 goto fk_end;
2653 }
dan1da40a32009-09-19 17:00:31 +00002654 if( pNextTo ){
2655 assert( pNextTo->pPrevTo==0 );
2656 pFKey->pNextTo = pNextTo;
2657 pNextTo->pPrevTo = pFKey;
2658 }
2659
drhc2eef3b2002-08-31 18:53:06 +00002660 /* Link the foreign key to the table as the last step.
2661 */
2662 p->pFKey = pFKey;
2663 pFKey = 0;
2664
2665fk_end:
drh633e6d52008-07-28 19:34:53 +00002666 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002667#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002668 sqlite3ExprListDelete(db, pFromCol);
2669 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002670}
2671
2672/*
2673** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2674** clause is seen as part of a foreign key definition. The isDeferred
2675** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2676** The behavior of the most recently created foreign key is adjusted
2677** accordingly.
2678*/
danielk19774adee202004-05-08 08:23:19 +00002679void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002680#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002681 Table *pTab;
2682 FKey *pFKey;
2683 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002684 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002685 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002686#endif
drhc2eef3b2002-08-31 18:53:06 +00002687}
2688
2689/*
drh063336a2004-11-05 20:58:39 +00002690** Generate code that will erase and refill index *pIdx. This is
2691** used to initialize a newly created index or to recompute the
2692** content of an index in response to a REINDEX command.
2693**
2694** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002695** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002696** root page number of the index. If memRootPage is negative, then
2697** the index already exists and must be cleared before being refilled and
2698** the root page number of the index is taken from pIndex->tnum.
2699*/
2700static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2701 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002702 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2703 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002704 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002705 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002706 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002707 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002708 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002709 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002710 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002711 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002712 sqlite3 *db = pParse->db; /* The database connection */
2713 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002714
danielk19771d54df82004-11-23 15:41:16 +00002715#ifndef SQLITE_OMIT_AUTHORIZATION
2716 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002717 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002718 return;
2719 }
2720#endif
2721
danielk1977c00da102006-01-07 13:21:04 +00002722 /* Require a write-lock on the table to perform this operation */
2723 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2724
drh063336a2004-11-05 20:58:39 +00002725 v = sqlite3GetVdbe(pParse);
2726 if( v==0 ) return;
2727 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002728 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002729 }else{
2730 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002731 }
drh2ec2fb22013-11-06 19:59:23 +00002732 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002733
dan689ab892011-08-12 15:02:00 +00002734 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002735 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002736 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002737 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002738
2739 /* Open the table. Loop through all rows of the table, inserting index
2740 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002741 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002742 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002743 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002744
drh1c2c0b72014-01-04 19:27:05 +00002745 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002746 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002747 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002748 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002749 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002750 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2751 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002752 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002753 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2754
drh688852a2014-02-17 22:40:43 +00002755 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002756 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002757 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002758 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2759 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2760 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002761 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002762 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002763 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002764 }else{
2765 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002766 }
drh6cf4a7d2014-10-13 13:00:58 +00002767 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002768 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2769 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002770 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002771 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002772 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002773 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002774
drh66a51672008-01-03 00:01:23 +00002775 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2776 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002777 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002778}
2779
2780/*
drh77e57df2013-10-22 14:28:02 +00002781** Allocate heap space to hold an Index object with nCol columns.
2782**
2783** Increase the allocation size to provide an extra nExtra bytes
2784** of 8-byte aligned space after the Index object and return a
2785** pointer to this extra space in *ppExtra.
2786*/
2787Index *sqlite3AllocateIndexObject(
2788 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002789 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002790 int nExtra, /* Number of bytes of extra space to alloc */
2791 char **ppExtra /* Pointer to the "extra" space */
2792){
2793 Index *p; /* Allocated index object */
2794 int nByte; /* Bytes of space for Index object + arrays */
2795
2796 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2797 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002798 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002799 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002800 sizeof(u8)*nCol); /* Index.aSortOrder */
2801 p = sqlite3DbMallocZero(db, nByte + nExtra);
2802 if( p ){
2803 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002804 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2805 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2806 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002807 p->aSortOrder = (u8*)pExtra;
2808 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002809 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002810 *ppExtra = ((char*)p) + nByte;
2811 }
2812 return p;
2813}
2814
2815/*
drh23bf66d2004-12-14 03:34:34 +00002816** Create a new index for an SQL table. pName1.pName2 is the name of the index
2817** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002818** be NULL for a primary key or an index that is created to satisfy a
2819** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002820** as the table to be indexed. pParse->pNewTable is a table that is
2821** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002822**
drh382c0242001-10-06 16:33:02 +00002823** pList is a list of columns to be indexed. pList will be NULL if this
2824** is a primary key or unique-constraint on the most recent column added
2825** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002826**
2827** If the index is created successfully, return a pointer to the new Index
2828** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002829** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002830*/
dan1da40a32009-09-19 17:00:31 +00002831Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002832 Parse *pParse, /* All information about this parse */
2833 Token *pName1, /* First part of index name. May be NULL */
2834 Token *pName2, /* Second part of index name. May be NULL */
2835 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002836 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002837 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002838 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002839 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002840 int sortOrder, /* Sort order of primary key when pList==NULL */
2841 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002842){
dan1da40a32009-09-19 17:00:31 +00002843 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002844 Table *pTab = 0; /* Table to be indexed */
2845 Index *pIndex = 0; /* The index to be created */
2846 char *zName = 0; /* Name of the index */
2847 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002848 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002849 DbFixer sFix; /* For assigning database names to pTable */
2850 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002851 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002852 Db *pDb; /* The specific table containing the indexed database */
2853 int iDb; /* Index of the database that is being written */
2854 Token *pName = 0; /* Unqualified name of the index to create */
2855 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002856 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002857 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002858 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002859 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002860 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002861
drh7088d502015-04-18 17:43:29 +00002862 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002863 goto exit_create_index;
2864 }
2865 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002866 goto exit_create_index;
2867 }
drhdaffd0e2001-04-11 14:28:42 +00002868
drh75897232000-05-29 14:26:00 +00002869 /*
2870 ** Find the table that is to be indexed. Return early if not found.
2871 */
danielk1977cbb18d22004-05-28 11:37:27 +00002872 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002873
2874 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002875 ** to search for the table. 'Fix' the table name to this db
2876 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002877 */
2878 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002879 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002880 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002881 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002882
danielk197753c0f742005-03-29 03:10:59 +00002883#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002884 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002885 ** is a temp table. If so, set the database to 1. Do not do this
2886 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002887 */
danielk1977fe910332007-12-02 11:46:34 +00002888 if( !db->init.busy ){
2889 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002890 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002891 iDb = 1;
2892 }
danielk1977ef2cb632004-05-29 02:37:19 +00002893 }
danielk197753c0f742005-03-29 03:10:59 +00002894#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002895
drhd100f692013-10-03 15:39:44 +00002896 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2897 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002898 /* Because the parser constructs pTblName from a single identifier,
2899 ** sqlite3FixSrcList can never fail. */
2900 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002901 }
dan41fb5cd2012-10-04 19:33:00 +00002902 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002903 assert( db->mallocFailed==0 || pTab==0 );
2904 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002905 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2906 sqlite3ErrorMsg(pParse,
2907 "cannot create a TEMP index on non-TEMP table \"%s\"",
2908 pTab->zName);
2909 goto exit_create_index;
2910 }
drh44156282013-10-23 22:23:03 +00002911 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002912 }else{
drhe3c41372001-09-17 20:25:58 +00002913 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002914 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002915 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002916 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002917 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002918 }
drhfdd6e852005-12-16 01:06:16 +00002919 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002920
drhd3001712009-05-12 17:46:53 +00002921 assert( pTab!=0 );
2922 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002923 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002924 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002925#if SQLITE_USER_AUTHENTICATION
2926 && sqlite3UserAuthTable(pTab->zName)==0
2927#endif
drh503a6862013-03-01 01:07:17 +00002928 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002929 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002930 goto exit_create_index;
2931 }
danielk1977576ec6b2005-01-21 11:55:25 +00002932#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002933 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002934 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002935 goto exit_create_index;
2936 }
danielk1977576ec6b2005-01-21 11:55:25 +00002937#endif
danielk19775ee9d692006-06-21 12:36:25 +00002938#ifndef SQLITE_OMIT_VIRTUALTABLE
2939 if( IsVirtual(pTab) ){
2940 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2941 goto exit_create_index;
2942 }
2943#endif
drh75897232000-05-29 14:26:00 +00002944
2945 /*
2946 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002947 ** index or table with the same name.
2948 **
2949 ** Exception: If we are reading the names of permanent indices from the
2950 ** sqlite_master table (because some other process changed the schema) and
2951 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002952 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002953 **
2954 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002955 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2956 ** own name.
drh75897232000-05-29 14:26:00 +00002957 */
danielk1977d8123362004-06-12 09:25:12 +00002958 if( pName ){
drh17435752007-08-16 04:30:38 +00002959 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002960 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002961 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002962 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002963 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002964 }
danielk1977d8123362004-06-12 09:25:12 +00002965 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002966 if( sqlite3FindTable(db, zName, 0)!=0 ){
2967 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2968 goto exit_create_index;
2969 }
2970 }
danielk197759a33f92007-03-17 10:26:59 +00002971 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2972 if( !ifNotExist ){
2973 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002974 }else{
2975 assert( !db->init.busy );
2976 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002977 }
danielk197759a33f92007-03-17 10:26:59 +00002978 goto exit_create_index;
2979 }
danielk1977a21c6b62005-01-24 10:25:59 +00002980 }else{
drhadbca9c2001-09-27 15:11:53 +00002981 int n;
2982 Index *pLoop;
2983 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002984 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002985 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002986 goto exit_create_index;
2987 }
drh75897232000-05-29 14:26:00 +00002988 }
2989
drhe5f9c642003-01-13 23:27:31 +00002990 /* Check for authorization to create an index.
2991 */
2992#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002993 {
drhfdd6e852005-12-16 01:06:16 +00002994 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002995 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002996 goto exit_create_index;
2997 }
2998 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002999 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003000 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003001 goto exit_create_index;
3002 }
drhe5f9c642003-01-13 23:27:31 +00003003 }
3004#endif
3005
drh75897232000-05-29 14:26:00 +00003006 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003007 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003008 ** So create a fake list to simulate this.
3009 */
3010 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00003011 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00003012 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00003013 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
3014 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00003015 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00003016 }
3017
danielk1977b3bf5562006-01-10 17:58:23 +00003018 /* Figure out how many bytes of space are required to store explicitly
3019 ** specified collation sequence names.
3020 */
3021 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003022 Expr *pExpr = pList->a[i].pExpr;
3023 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00003024 assert( pExpr->op==TK_COLLATE );
3025 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003026 }
3027 }
3028
drh75897232000-05-29 14:26:00 +00003029 /*
3030 ** Allocate the index structure.
3031 */
drhea678832008-12-10 19:26:22 +00003032 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003033 nExtraCol = pPk ? pPk->nKeyCol : 1;
3034 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003035 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003036 if( db->mallocFailed ){
3037 goto exit_create_index;
3038 }
dancfc9df72014-04-25 15:01:01 +00003039 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003040 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003041 pIndex->zName = zExtra;
3042 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003043 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003044 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003045 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003046 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003047 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003048 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003049 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003050 if( pPIWhere ){
3051 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3052 pIndex->pPartIdxWhere = pPIWhere;
3053 pPIWhere = 0;
3054 }
drh21206082011-04-04 18:22:02 +00003055 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003056
drhfdd6e852005-12-16 01:06:16 +00003057 /* Check to see if we should honor DESC requests on index columns
3058 */
danielk1977da184232006-01-05 11:34:32 +00003059 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003060 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003061 }else{
3062 sortOrderMask = 0; /* Ignore DESC */
3063 }
3064
drh1ccde152000-06-17 13:12:39 +00003065 /* Scan the names of the columns of the table to be indexed and
3066 ** load the column indices into the Index structure. Report an error
3067 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003068 **
3069 ** TODO: Add a test to make sure that the same column is not named
3070 ** more than once within the same index. Only the first instance of
3071 ** the column will ever be used by the optimizer. Note that using the
3072 ** same column more than once cannot be an error because that would
3073 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003074 */
drhfdd6e852005-12-16 01:06:16 +00003075 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3076 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003077 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003078 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003079
drhfdd6e852005-12-16 01:06:16 +00003080 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3081 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003082 }
3083 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003084 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003085 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003086 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003087 goto exit_create_index;
3088 }
drhbf20a352014-04-04 22:44:59 +00003089 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003090 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003091 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003092 int nColl;
dan911ce412013-05-15 15:16:50 +00003093 assert( pListItem->pExpr->op==TK_COLLATE );
3094 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003095 nColl = sqlite3Strlen30(zColl) + 1;
3096 assert( nExtra>=nColl );
3097 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003098 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003099 zExtra += nColl;
3100 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003101 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003102 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003103 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003104 }
drhb7f24de2009-05-13 17:35:23 +00003105 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003106 goto exit_create_index;
3107 }
danielk1977b3bf5562006-01-10 17:58:23 +00003108 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003109 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003110 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003111 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003112 }
drh44156282013-10-23 22:23:03 +00003113 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003114 for(j=0; j<pPk->nKeyCol; j++){
3115 int x = pPk->aiColumn[j];
3116 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3117 pIndex->nColumn--;
3118 }else{
3119 pIndex->aiColumn[i] = x;
3120 pIndex->azColl[i] = pPk->azColl[j];
3121 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3122 i++;
3123 }
drh44156282013-10-23 22:23:03 +00003124 }
drh7913e412013-11-01 20:30:36 +00003125 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003126 }else{
3127 pIndex->aiColumn[i] = -1;
3128 pIndex->azColl[i] = "BINARY";
3129 }
drh51147ba2005-07-23 22:59:55 +00003130 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003131 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003132
danielk1977d8123362004-06-12 09:25:12 +00003133 if( pTab==pParse->pNewTable ){
3134 /* This routine has been called to create an automatic index as a
3135 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3136 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3137 ** i.e. one of:
3138 **
3139 ** CREATE TABLE t(x PRIMARY KEY, y);
3140 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3141 **
3142 ** Either way, check to see if the table already has such an index. If
3143 ** so, don't bother creating this one. This only applies to
3144 ** automatically created indices. Users can do as they wish with
3145 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003146 **
3147 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3148 ** (and thus suppressing the second one) even if they have different
3149 ** sort orders.
3150 **
3151 ** If there are different collating sequences or if the columns of
3152 ** the constraint occur in different orders, then the constraints are
3153 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003154 */
3155 Index *pIdx;
3156 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3157 int k;
drh5f1d1d92014-07-31 22:59:04 +00003158 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003159 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003160 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003161
drhbbbdc832013-10-22 18:01:40 +00003162 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3163 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003164 const char *z1;
3165 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003166 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003167 z1 = pIdx->azColl[k];
3168 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003169 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003170 }
drhbbbdc832013-10-22 18:01:40 +00003171 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003172 if( pIdx->onError!=pIndex->onError ){
3173 /* This constraint creates the same index as a previous
3174 ** constraint specified somewhere in the CREATE TABLE statement.
3175 ** However the ON CONFLICT clauses are different. If both this
3176 ** constraint and the previous equivalent constraint have explicit
3177 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003178 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003179 */
3180 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3181 sqlite3ErrorMsg(pParse,
3182 "conflicting ON CONFLICT clauses specified", 0);
3183 }
3184 if( pIdx->onError==OE_Default ){
3185 pIdx->onError = pIndex->onError;
3186 }
3187 }
drhf0636852015-03-21 02:58:20 +00003188 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003189 goto exit_create_index;
3190 }
3191 }
3192 }
3193
drh75897232000-05-29 14:26:00 +00003194 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003195 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003196 */
drh234c39d2004-07-24 03:30:47 +00003197 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003198 Index *p;
drh21206082011-04-04 18:22:02 +00003199 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003200 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003201 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003202 if( p ){
3203 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003204 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003205 goto exit_create_index;
3206 }
drh5e00f6c2001-09-13 13:46:56 +00003207 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003208 if( pTblName!=0 ){
3209 pIndex->tnum = db->init.newTnum;
3210 }
drhd78eeee2001-09-13 16:18:53 +00003211 }
3212
drh58383402013-11-04 17:00:50 +00003213 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3214 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3215 ** emit code to allocate the index rootpage on disk and make an entry for
3216 ** the index in the sqlite_master table and populate the index with
3217 ** content. But, do not do this if we are simply reading the sqlite_master
3218 ** table to parse the schema, or if this index is the PRIMARY KEY index
3219 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003220 **
drh58383402013-11-04 17:00:50 +00003221 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3222 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003223 ** has just been created, it contains no data and the index initialization
3224 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003225 */
drh58383402013-11-04 17:00:50 +00003226 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003227 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003228 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003229 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003230
danielk19774adee202004-05-08 08:23:19 +00003231 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003232 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003233
drhfdd6e852005-12-16 01:06:16 +00003234
drh063336a2004-11-05 20:58:39 +00003235 /* Create the rootpage for the index
3236 */
drhaee128d2005-02-14 20:48:18 +00003237 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003238 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003239
3240 /* Gather the complete text of the CREATE INDEX statement into
3241 ** the zStmt variable
3242 */
drhd3001712009-05-12 17:46:53 +00003243 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003244 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003245 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003246 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003247 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003248 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003249 }else{
3250 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003251 /* zStmt = sqlite3MPrintf(""); */
3252 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003253 }
drh063336a2004-11-05 20:58:39 +00003254
3255 /* Add an entry in sqlite_master for this index
3256 */
3257 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003258 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003259 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3260 pIndex->zName,
3261 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003262 iMem,
drh063336a2004-11-05 20:58:39 +00003263 zStmt
3264 );
drh633e6d52008-07-28 19:34:53 +00003265 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003266
danielk1977a21c6b62005-01-24 10:25:59 +00003267 /* Fill the index with data and reparse the schema. Code an OP_Expire
3268 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003269 */
danielk1977cbb18d22004-05-28 11:37:27 +00003270 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003271 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003272 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003273 sqlite3VdbeAddParseSchemaOp(v, iDb,
3274 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003275 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003276 }
drh75897232000-05-29 14:26:00 +00003277 }
3278
danielk1977d8123362004-06-12 09:25:12 +00003279 /* When adding an index to the list of indices for a table, make
3280 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003281 ** OE_Ignore. This is necessary for the correct constraint check
3282 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3283 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003284 */
drh234c39d2004-07-24 03:30:47 +00003285 if( db->init.busy || pTblName==0 ){
3286 if( onError!=OE_Replace || pTab->pIndex==0
3287 || pTab->pIndex->onError==OE_Replace){
3288 pIndex->pNext = pTab->pIndex;
3289 pTab->pIndex = pIndex;
3290 }else{
3291 Index *pOther = pTab->pIndex;
3292 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3293 pOther = pOther->pNext;
3294 }
3295 pIndex->pNext = pOther->pNext;
3296 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003297 }
dan1da40a32009-09-19 17:00:31 +00003298 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003299 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003300 }
danielk1977d8123362004-06-12 09:25:12 +00003301
drh75897232000-05-29 14:26:00 +00003302 /* Clean up before exiting */
3303exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003304 if( pIndex ) freeIndex(db, pIndex);
3305 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003306 sqlite3ExprListDelete(db, pList);
3307 sqlite3SrcListDelete(db, pTblName);
3308 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003309 return pRet;
drh75897232000-05-29 14:26:00 +00003310}
3311
3312/*
drh51147ba2005-07-23 22:59:55 +00003313** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003314** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003315**
peter.d.reid60ec9142014-09-06 16:39:46 +00003316** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003317** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3318** number of rows in the table that match any particular value of the
3319** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003320** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003321** of the index. And so forth. It must always be the case that
3322*
3323** aiRowEst[N]<=aiRowEst[N-1]
3324** aiRowEst[N]>=1
3325**
3326** Apart from that, we have little to go on besides intuition as to
3327** how aiRowEst[] should be initialized. The numbers generated here
3328** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003329*/
3330void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003331 /* 10, 9, 8, 7, 6 */
3332 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003333 LogEst *a = pIdx->aiRowLogEst;
3334 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003335 int i;
dancfc9df72014-04-25 15:01:01 +00003336
dan264d2b92014-04-29 19:01:57 +00003337 /* Set the first entry (number of rows in the index) to the estimated
3338 ** number of rows in the table. Or 10, if the estimated number of rows
3339 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003340 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003341 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3342
3343 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3344 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003345 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003346 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3347 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003348 }
dan264d2b92014-04-29 19:01:57 +00003349
3350 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003351 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003352}
3353
3354/*
drh74e24cd2002-01-09 03:19:59 +00003355** This routine will drop an existing named index. This routine
3356** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003357*/
drh4d91a702006-01-04 15:54:36 +00003358void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003359 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003360 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003361 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003362 int iDb;
drh75897232000-05-29 14:26:00 +00003363
drh8af73d42009-05-13 22:58:28 +00003364 assert( pParse->nErr==0 ); /* Never called with prior errors */
3365 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003366 goto exit_drop_index;
3367 }
drhd24cc422003-03-27 12:51:24 +00003368 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003369 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3370 goto exit_drop_index;
3371 }
danielk19774adee202004-05-08 08:23:19 +00003372 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003373 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003374 if( !ifExists ){
3375 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003376 }else{
3377 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003378 }
drha6ecd332004-06-10 00:29:09 +00003379 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003380 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003381 }
drh48dd1d82014-05-27 18:18:58 +00003382 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003383 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003384 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003385 goto exit_drop_index;
3386 }
danielk1977da184232006-01-05 11:34:32 +00003387 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003388#ifndef SQLITE_OMIT_AUTHORIZATION
3389 {
3390 int code = SQLITE_DROP_INDEX;
3391 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003392 const char *zDb = db->aDb[iDb].zName;
3393 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003394 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003395 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003396 }
danielk1977da184232006-01-05 11:34:32 +00003397 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003398 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003399 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003400 }
drhed6c8672003-01-12 18:02:16 +00003401 }
drhe5f9c642003-01-13 23:27:31 +00003402#endif
drh75897232000-05-29 14:26:00 +00003403
3404 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003405 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003406 if( v ){
drh77658e22007-12-04 16:54:52 +00003407 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003408 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003409 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003410 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003411 );
drha5ae4c32011-08-07 01:31:52 +00003412 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003413 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003414 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003415 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003416 }
3417
drhd24cc422003-03-27 12:51:24 +00003418exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003419 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003420}
3421
3422/*
dan9ace1122012-03-29 07:51:45 +00003423** pArray is a pointer to an array of objects. Each object in the
3424** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3425** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003426**
dan9ace1122012-03-29 07:51:45 +00003427** When this function is called, *pnEntry contains the current size of
3428** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3429** in total).
drh13449892005-09-07 21:22:45 +00003430**
dan9ace1122012-03-29 07:51:45 +00003431** If the realloc() is successful (i.e. if no OOM condition occurs), the
3432** space allocated for the new object is zeroed, *pnEntry updated to
3433** reflect the new size of the array and a pointer to the new allocation
3434** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003435**
dan9ace1122012-03-29 07:51:45 +00003436** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3437** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003438*/
drhcf643722007-03-27 13:36:37 +00003439void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003440 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003441 void *pArray, /* Array of objects. Might be reallocated */
3442 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003443 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003444 int *pIdx /* Write the index of a new slot here */
3445){
3446 char *z;
drh6c535152012-02-02 03:38:30 +00003447 int n = *pnEntry;
3448 if( (n & (n-1))==0 ){
3449 int sz = (n==0) ? 1 : 2*n;
3450 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003451 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003452 *pIdx = -1;
3453 return pArray;
drh13449892005-09-07 21:22:45 +00003454 }
drhcf643722007-03-27 13:36:37 +00003455 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003456 }
drhcf643722007-03-27 13:36:37 +00003457 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003458 memset(&z[n * szEntry], 0, szEntry);
3459 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003460 ++*pnEntry;
3461 return pArray;
drh13449892005-09-07 21:22:45 +00003462}
3463
3464/*
drh75897232000-05-29 14:26:00 +00003465** Append a new element to the given IdList. Create a new IdList if
3466** need be.
drhdaffd0e2001-04-11 14:28:42 +00003467**
3468** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003469*/
drh17435752007-08-16 04:30:38 +00003470IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003471 int i;
drh75897232000-05-29 14:26:00 +00003472 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003473 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003474 if( pList==0 ) return 0;
3475 }
drhcf643722007-03-27 13:36:37 +00003476 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003477 db,
drhcf643722007-03-27 13:36:37 +00003478 pList->a,
3479 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003480 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003481 &i
3482 );
drh13449892005-09-07 21:22:45 +00003483 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003484 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003485 return 0;
drh75897232000-05-29 14:26:00 +00003486 }
drh17435752007-08-16 04:30:38 +00003487 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003488 return pList;
3489}
3490
3491/*
drhfe05af82005-07-21 03:14:59 +00003492** Delete an IdList.
3493*/
drh633e6d52008-07-28 19:34:53 +00003494void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003495 int i;
3496 if( pList==0 ) return;
3497 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003498 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003499 }
drh633e6d52008-07-28 19:34:53 +00003500 sqlite3DbFree(db, pList->a);
3501 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003502}
3503
3504/*
3505** Return the index in pList of the identifier named zId. Return -1
3506** if not found.
3507*/
3508int sqlite3IdListIndex(IdList *pList, const char *zName){
3509 int i;
3510 if( pList==0 ) return -1;
3511 for(i=0; i<pList->nId; i++){
3512 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3513 }
3514 return -1;
3515}
3516
3517/*
drha78c22c2008-11-11 18:28:58 +00003518** Expand the space allocated for the given SrcList object by
3519** creating nExtra new slots beginning at iStart. iStart is zero based.
3520** New slots are zeroed.
3521**
3522** For example, suppose a SrcList initially contains two entries: A,B.
3523** To append 3 new entries onto the end, do this:
3524**
3525** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3526**
3527** After the call above it would contain: A, B, nil, nil, nil.
3528** If the iStart argument had been 1 instead of 2, then the result
3529** would have been: A, nil, nil, nil, B. To prepend the new slots,
3530** the iStart value would be 0. The result then would
3531** be: nil, nil, nil, A, B.
3532**
3533** If a memory allocation fails the SrcList is unchanged. The
3534** db->mallocFailed flag will be set to true.
3535*/
3536SrcList *sqlite3SrcListEnlarge(
3537 sqlite3 *db, /* Database connection to notify of OOM errors */
3538 SrcList *pSrc, /* The SrcList to be enlarged */
3539 int nExtra, /* Number of new slots to add to pSrc->a[] */
3540 int iStart /* Index in pSrc->a[] of first new slot */
3541){
3542 int i;
3543
3544 /* Sanity checking on calling parameters */
3545 assert( iStart>=0 );
3546 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003547 assert( pSrc!=0 );
3548 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003549
3550 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003551 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003552 SrcList *pNew;
3553 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003554 int nGot;
drha78c22c2008-11-11 18:28:58 +00003555 pNew = sqlite3DbRealloc(db, pSrc,
3556 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3557 if( pNew==0 ){
3558 assert( db->mallocFailed );
3559 return pSrc;
3560 }
3561 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003562 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003563 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003564 }
3565
3566 /* Move existing slots that come after the newly inserted slots
3567 ** out of the way */
3568 for(i=pSrc->nSrc-1; i>=iStart; i--){
3569 pSrc->a[i+nExtra] = pSrc->a[i];
3570 }
drh6d1626e2014-03-05 15:52:43 +00003571 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003572
3573 /* Zero the newly allocated slots */
3574 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3575 for(i=iStart; i<iStart+nExtra; i++){
3576 pSrc->a[i].iCursor = -1;
3577 }
3578
3579 /* Return a pointer to the enlarged SrcList */
3580 return pSrc;
3581}
3582
3583
3584/*
drhad3cab52002-05-24 02:04:32 +00003585** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003586** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003587**
drha78c22c2008-11-11 18:28:58 +00003588** A SrcList is returned, or NULL if there is an OOM error. The returned
3589** SrcList might be the same as the SrcList that was input or it might be
3590** a new one. If an OOM error does occurs, then the prior value of pList
3591** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003592**
3593** If pDatabase is not null, it means that the table has an optional
3594** database name prefix. Like this: "database.table". The pDatabase
3595** points to the table name and the pTable points to the database name.
3596** The SrcList.a[].zName field is filled with the table name which might
3597** come from pTable (if pDatabase is NULL) or from pDatabase.
3598** SrcList.a[].zDatabase is filled with the database name from pTable,
3599** or with NULL if no database is specified.
3600**
3601** In other words, if call like this:
3602**
drh17435752007-08-16 04:30:38 +00003603** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003604**
3605** Then B is a table name and the database name is unspecified. If called
3606** like this:
3607**
drh17435752007-08-16 04:30:38 +00003608** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003609**
drhd3001712009-05-12 17:46:53 +00003610** Then C is the table name and B is the database name. If C is defined
3611** then so is B. In other words, we never have a case where:
3612**
3613** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003614**
3615** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3616** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003617*/
drh17435752007-08-16 04:30:38 +00003618SrcList *sqlite3SrcListAppend(
3619 sqlite3 *db, /* Connection to notify of malloc failures */
3620 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3621 Token *pTable, /* Table to append */
3622 Token *pDatabase /* Database of the table */
3623){
drha99db3b2004-06-19 14:49:12 +00003624 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003625 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003626 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003627 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003628 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003629 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003630 }
drha78c22c2008-11-11 18:28:58 +00003631 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3632 if( db->mallocFailed ){
3633 sqlite3SrcListDelete(db, pList);
3634 return 0;
drhad3cab52002-05-24 02:04:32 +00003635 }
drha78c22c2008-11-11 18:28:58 +00003636 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003637 if( pDatabase && pDatabase->z==0 ){
3638 pDatabase = 0;
3639 }
drhd3001712009-05-12 17:46:53 +00003640 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003641 Token *pTemp = pDatabase;
3642 pDatabase = pTable;
3643 pTable = pTemp;
3644 }
drh17435752007-08-16 04:30:38 +00003645 pItem->zName = sqlite3NameFromToken(db, pTable);
3646 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003647 return pList;
3648}
3649
3650/*
drhdfe88ec2008-11-03 20:55:06 +00003651** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003652*/
danielk19774adee202004-05-08 08:23:19 +00003653void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003654 int i;
drh9b3187e2005-01-18 14:45:47 +00003655 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003656 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003657 if( pList ){
3658 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3659 if( pItem->iCursor>=0 ) break;
3660 pItem->iCursor = pParse->nTab++;
3661 if( pItem->pSelect ){
3662 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3663 }
drh63eb5f22003-04-29 16:20:44 +00003664 }
3665 }
3666}
3667
3668/*
drhad3cab52002-05-24 02:04:32 +00003669** Delete an entire SrcList including all its substructure.
3670*/
drh633e6d52008-07-28 19:34:53 +00003671void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003672 int i;
drhbe5c89a2004-07-26 00:31:09 +00003673 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003674 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003675 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003676 sqlite3DbFree(db, pItem->zDatabase);
3677 sqlite3DbFree(db, pItem->zName);
3678 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003679 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003680 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003681 sqlite3SelectDelete(db, pItem->pSelect);
3682 sqlite3ExprDelete(db, pItem->pOn);
3683 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003684 }
drh633e6d52008-07-28 19:34:53 +00003685 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003686}
3687
drh982cef72000-05-30 16:27:03 +00003688/*
drh61dfc312006-12-16 16:25:15 +00003689** This routine is called by the parser to add a new term to the
3690** end of a growing FROM clause. The "p" parameter is the part of
3691** the FROM clause that has already been constructed. "p" is NULL
3692** if this is the first term of the FROM clause. pTable and pDatabase
3693** are the name of the table and database named in the FROM clause term.
3694** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003695** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003696** alias token. If the term is a subquery, then pSubquery is the
3697** SELECT statement that the subquery encodes. The pTable and
3698** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3699** parameters are the content of the ON and USING clauses.
3700**
3701** Return a new SrcList which encodes is the FROM with the new
3702** term added.
3703*/
3704SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003705 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003706 SrcList *p, /* The left part of the FROM clause already seen */
3707 Token *pTable, /* Name of the table to add to the FROM clause */
3708 Token *pDatabase, /* Name of the database containing pTable */
3709 Token *pAlias, /* The right-hand side of the AS subexpression */
3710 Select *pSubquery, /* A subquery used in place of a table name */
3711 Expr *pOn, /* The ON clause of a join */
3712 IdList *pUsing /* The USING clause of a join */
3713){
3714 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003715 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003716 if( !p && (pOn || pUsing) ){
3717 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3718 (pOn ? "ON" : "USING")
3719 );
3720 goto append_from_error;
3721 }
drh17435752007-08-16 04:30:38 +00003722 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003723 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003724 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003725 }
3726 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003727 assert( pAlias!=0 );
3728 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003729 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003730 }
3731 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003732 pItem->pOn = pOn;
3733 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003734 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003735
3736 append_from_error:
3737 assert( p==0 );
3738 sqlite3ExprDelete(db, pOn);
3739 sqlite3IdListDelete(db, pUsing);
3740 sqlite3SelectDelete(db, pSubquery);
3741 return 0;
drh61dfc312006-12-16 16:25:15 +00003742}
3743
3744/*
danielk1977b1c685b2008-10-06 16:18:39 +00003745** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3746** element of the source-list passed as the second argument.
3747*/
3748void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003749 assert( pIndexedBy!=0 );
3750 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003751 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3752 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3753 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3754 /* A "NOT INDEXED" clause was supplied. See parse.y
3755 ** construct "indexed_opt" for details. */
3756 pItem->notIndexed = 1;
3757 }else{
3758 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3759 }
3760 }
3761}
3762
3763/*
drh61dfc312006-12-16 16:25:15 +00003764** When building up a FROM clause in the parser, the join operator
3765** is initially attached to the left operand. But the code generator
3766** expects the join operator to be on the right operand. This routine
3767** Shifts all join operators from left to right for an entire FROM
3768** clause.
3769**
3770** Example: Suppose the join is like this:
3771**
3772** A natural cross join B
3773**
3774** The operator is "natural cross join". The A and B operands are stored
3775** in p->a[0] and p->a[1], respectively. The parser initially stores the
3776** operator with A. This routine shifts that operator over to B.
3777*/
3778void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003779 if( p ){
drh61dfc312006-12-16 16:25:15 +00003780 int i;
3781 for(i=p->nSrc-1; i>0; i--){
3782 p->a[i].jointype = p->a[i-1].jointype;
3783 }
3784 p->a[0].jointype = 0;
3785 }
3786}
3787
3788/*
drhc4a3c772001-04-04 11:48:57 +00003789** Begin a transaction
3790*/
drh684917c2004-10-05 02:41:42 +00003791void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003792 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003793 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003794 int i;
drh5e00f6c2001-09-13 13:46:56 +00003795
drhd3001712009-05-12 17:46:53 +00003796 assert( pParse!=0 );
3797 db = pParse->db;
3798 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003799/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003800 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3801 return;
3802 }
danielk19771d850a72004-05-31 08:26:49 +00003803 v = sqlite3GetVdbe(pParse);
3804 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003805 if( type!=TK_DEFERRED ){
3806 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003807 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003808 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003809 }
3810 }
drh66a51672008-01-03 00:01:23 +00003811 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003812}
3813
3814/*
3815** Commit a transaction
3816*/
danielk19774adee202004-05-08 08:23:19 +00003817void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003818 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003819
drhd3001712009-05-12 17:46:53 +00003820 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003821 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003822 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3823 return;
3824 }
danielk19771d850a72004-05-31 08:26:49 +00003825 v = sqlite3GetVdbe(pParse);
3826 if( v ){
drh66a51672008-01-03 00:01:23 +00003827 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003828 }
drhc4a3c772001-04-04 11:48:57 +00003829}
3830
3831/*
3832** Rollback a transaction
3833*/
danielk19774adee202004-05-08 08:23:19 +00003834void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003835 Vdbe *v;
3836
drhd3001712009-05-12 17:46:53 +00003837 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003838 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003839 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3840 return;
3841 }
danielk19774adee202004-05-08 08:23:19 +00003842 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003843 if( v ){
drh66a51672008-01-03 00:01:23 +00003844 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003845 }
drhc4a3c772001-04-04 11:48:57 +00003846}
drhf57b14a2001-09-14 18:54:08 +00003847
3848/*
danielk1977fd7f0452008-12-17 17:30:26 +00003849** This function is called by the parser when it parses a command to create,
3850** release or rollback an SQL savepoint.
3851*/
3852void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003853 char *zName = sqlite3NameFromToken(pParse->db, pName);
3854 if( zName ){
3855 Vdbe *v = sqlite3GetVdbe(pParse);
3856#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003857 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003858 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3859#endif
3860 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3861 sqlite3DbFree(pParse->db, zName);
3862 return;
3863 }
3864 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003865 }
3866}
3867
3868/*
drhdc3ff9c2004-08-18 02:10:15 +00003869** Make sure the TEMP database is open and available for use. Return
3870** the number of errors. Leave any error messages in the pParse structure.
3871*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003872int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003873 sqlite3 *db = pParse->db;
3874 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003875 int rc;
drh10a76c92010-01-26 01:25:26 +00003876 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003877 static const int flags =
3878 SQLITE_OPEN_READWRITE |
3879 SQLITE_OPEN_CREATE |
3880 SQLITE_OPEN_EXCLUSIVE |
3881 SQLITE_OPEN_DELETEONCLOSE |
3882 SQLITE_OPEN_TEMP_DB;
3883
dan3a6d8ae2011-04-23 15:54:54 +00003884 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003885 if( rc!=SQLITE_OK ){
3886 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3887 "file for storing temporary tables");
3888 pParse->rc = rc;
3889 return 1;
3890 }
drh10a76c92010-01-26 01:25:26 +00003891 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003892 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003893 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3894 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003895 return 1;
drh10a76c92010-01-26 01:25:26 +00003896 }
drhdc3ff9c2004-08-18 02:10:15 +00003897 }
3898 return 0;
3899}
3900
3901/*
drhaceb31b2014-02-08 01:40:27 +00003902** Record the fact that the schema cookie will need to be verified
3903** for database iDb. The code to actually verify the schema cookie
3904** will occur at the end of the top-level VDBE and will be generated
3905** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003906*/
danielk19774adee202004-05-08 08:23:19 +00003907void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003908 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003909 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003910
drhaceb31b2014-02-08 01:40:27 +00003911 assert( iDb>=0 && iDb<db->nDb );
3912 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3913 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3914 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003915 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3916 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003917 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3918 if( !OMIT_TEMPDB && iDb==1 ){
3919 sqlite3OpenTempDatabase(pToplevel);
3920 }
drh001bbcb2003-03-19 03:14:00 +00003921 }
drh001bbcb2003-03-19 03:14:00 +00003922}
3923
3924/*
dan57966752011-04-09 17:32:58 +00003925** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3926** attached database. Otherwise, invoke it for the database named zDb only.
3927*/
3928void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3929 sqlite3 *db = pParse->db;
3930 int i;
3931 for(i=0; i<db->nDb; i++){
3932 Db *pDb = &db->aDb[i];
3933 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3934 sqlite3CodeVerifySchema(pParse, i);
3935 }
3936 }
3937}
3938
3939/*
drh1c928532002-01-31 15:54:21 +00003940** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003941** might change the database.
3942**
3943** This routine starts a new transaction if we are not already within
3944** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003945** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003946** be set for operations that might fail (due to a constraint) part of
3947** the way through and which will need to undo some writes without having to
3948** rollback the whole transaction. For operations where all constraints
3949** can be checked before any changes are made to the database, it is never
3950** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003951*/
drh7f0f12e2004-05-21 13:39:50 +00003952void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003953 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003954 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003955 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003956 pToplevel->isMultiWrite |= setStatement;
3957}
3958
drhff738bc2009-09-24 00:09:58 +00003959/*
3960** Indicate that the statement currently under construction might write
3961** more than one entry (example: deleting one row then inserting another,
3962** inserting multiple rows in a table, or inserting a row and index entries.)
3963** If an abort occurs after some of these writes have completed, then it will
3964** be necessary to undo the completed writes.
3965*/
3966void sqlite3MultiWrite(Parse *pParse){
3967 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3968 pToplevel->isMultiWrite = 1;
3969}
3970
dane0af83a2009-09-08 19:15:01 +00003971/*
drhff738bc2009-09-24 00:09:58 +00003972** The code generator calls this routine if is discovers that it is
3973** possible to abort a statement prior to completion. In order to
3974** perform this abort without corrupting the database, we need to make
3975** sure that the statement is protected by a statement transaction.
3976**
3977** Technically, we only need to set the mayAbort flag if the
3978** isMultiWrite flag was previously set. There is a time dependency
3979** such that the abort must occur after the multiwrite. This makes
3980** some statements involving the REPLACE conflict resolution algorithm
3981** go a little faster. But taking advantage of this time dependency
3982** makes it more difficult to prove that the code is correct (in
3983** particular, it prevents us from writing an effective
3984** implementation of sqlite3AssertMayAbort()) and so we have chosen
3985** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003986*/
3987void sqlite3MayAbort(Parse *pParse){
3988 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3989 pToplevel->mayAbort = 1;
3990}
3991
3992/*
3993** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3994** error. The onError parameter determines which (if any) of the statement
3995** and/or current transaction is rolled back.
3996*/
drhd91c1a12013-02-09 13:58:25 +00003997void sqlite3HaltConstraint(
3998 Parse *pParse, /* Parsing context */
3999 int errCode, /* extended error code */
4000 int onError, /* Constraint type */
4001 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004002 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4003 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004004){
dane0af83a2009-09-08 19:15:01 +00004005 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004006 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004007 if( onError==OE_Abort ){
4008 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004009 }
drhd91c1a12013-02-09 13:58:25 +00004010 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004011 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4012}
4013
4014/*
4015** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4016*/
4017void sqlite3UniqueConstraint(
4018 Parse *pParse, /* Parsing context */
4019 int onError, /* Constraint type */
4020 Index *pIdx /* The index that triggers the constraint */
4021){
4022 char *zErr;
4023 int j;
4024 StrAccum errMsg;
4025 Table *pTab = pIdx->pTable;
4026
drhc0490572015-05-02 11:45:53 +00004027 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drhf9c8ce32013-11-05 13:33:55 +00004028 for(j=0; j<pIdx->nKeyCol; j++){
4029 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4030 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004031 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004032 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004033 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004034 }
4035 zErr = sqlite3StrAccumFinish(&errMsg);
4036 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004037 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4038 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004039 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004040}
4041
4042
4043/*
4044** Code an OP_Halt due to non-unique rowid.
4045*/
4046void sqlite3RowidConstraint(
4047 Parse *pParse, /* Parsing context */
4048 int onError, /* Conflict resolution algorithm */
4049 Table *pTab /* The table with the non-unique rowid */
4050){
4051 char *zMsg;
4052 int rc;
4053 if( pTab->iPKey>=0 ){
4054 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4055 pTab->aCol[pTab->iPKey].zName);
4056 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4057 }else{
4058 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4059 rc = SQLITE_CONSTRAINT_ROWID;
4060 }
4061 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4062 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004063}
4064
drh4343fea2004-11-05 23:46:15 +00004065/*
4066** Check to see if pIndex uses the collating sequence pColl. Return
4067** true if it does and false if it does not.
4068*/
4069#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004070static int collationMatch(const char *zColl, Index *pIndex){
4071 int i;
drh04491712009-05-13 17:21:13 +00004072 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004073 for(i=0; i<pIndex->nColumn; i++){
4074 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004075 assert( z!=0 || pIndex->aiColumn[i]<0 );
4076 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004077 return 1;
4078 }
drh4343fea2004-11-05 23:46:15 +00004079 }
4080 return 0;
4081}
4082#endif
4083
4084/*
4085** Recompute all indices of pTab that use the collating sequence pColl.
4086** If pColl==0 then recompute all indices of pTab.
4087*/
4088#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004089static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004090 Index *pIndex; /* An index associated with pTab */
4091
4092 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004093 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004094 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4095 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004096 sqlite3RefillIndex(pParse, pIndex, -1);
4097 }
4098 }
4099}
4100#endif
4101
4102/*
4103** Recompute all indices of all tables in all databases where the
4104** indices use the collating sequence pColl. If pColl==0 then recompute
4105** all indices everywhere.
4106*/
4107#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004108static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004109 Db *pDb; /* A single database */
4110 int iDb; /* The database index number */
4111 sqlite3 *db = pParse->db; /* The database connection */
4112 HashElem *k; /* For looping over tables in pDb */
4113 Table *pTab; /* A table in the database */
4114
drh21206082011-04-04 18:22:02 +00004115 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004116 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004117 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004118 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004119 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004120 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004121 }
4122 }
4123}
4124#endif
4125
4126/*
drheee46cf2004-11-06 00:02:48 +00004127** Generate code for the REINDEX command.
4128**
4129** REINDEX -- 1
4130** REINDEX <collation> -- 2
4131** REINDEX ?<database>.?<tablename> -- 3
4132** REINDEX ?<database>.?<indexname> -- 4
4133**
4134** Form 1 causes all indices in all attached databases to be rebuilt.
4135** Form 2 rebuilds all indices in all databases that use the named
4136** collating function. Forms 3 and 4 rebuild the named index or all
4137** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004138*/
4139#ifndef SQLITE_OMIT_REINDEX
4140void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4141 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4142 char *z; /* Name of a table or index */
4143 const char *zDb; /* Name of the database */
4144 Table *pTab; /* A table in the database */
4145 Index *pIndex; /* An index associated with pTab */
4146 int iDb; /* The database index number */
4147 sqlite3 *db = pParse->db; /* The database connection */
4148 Token *pObjName; /* Name of the table or index to be reindexed */
4149
danielk197733a5edc2005-01-27 00:22:02 +00004150 /* Read the database schema. If an error occurs, leave an error message
4151 ** and code in pParse and return NULL. */
4152 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004153 return;
danielk197733a5edc2005-01-27 00:22:02 +00004154 }
4155
drh8af73d42009-05-13 22:58:28 +00004156 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004157 reindexDatabases(pParse, 0);
4158 return;
drhd3001712009-05-12 17:46:53 +00004159 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004160 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004161 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004162 zColl = sqlite3NameFromToken(pParse->db, pName1);
4163 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004164 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004165 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004166 reindexDatabases(pParse, zColl);
4167 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004168 return;
4169 }
drh633e6d52008-07-28 19:34:53 +00004170 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004171 }
4172 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4173 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004174 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004175 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004176 zDb = db->aDb[iDb].zName;
4177 pTab = sqlite3FindTable(db, z, zDb);
4178 if( pTab ){
4179 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004180 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004181 return;
4182 }
4183 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004184 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004185 if( pIndex ){
4186 sqlite3BeginWriteOperation(pParse, 0, iDb);
4187 sqlite3RefillIndex(pParse, pIndex, -1);
4188 return;
4189 }
4190 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4191}
4192#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004193
4194/*
drh2ec2fb22013-11-06 19:59:23 +00004195** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004196**
drh2ec2fb22013-11-06 19:59:23 +00004197** The KeyInfo structure for an index is cached in the Index object.
4198** So there might be multiple references to the returned pointer. The
4199** caller should not try to modify the KeyInfo object.
4200**
4201** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4202** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004203*/
drh2ec2fb22013-11-06 19:59:23 +00004204KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004205 int i;
4206 int nCol = pIdx->nColumn;
4207 int nKey = pIdx->nKeyCol;
4208 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004209 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004210 if( pIdx->uniqNotNull ){
4211 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4212 }else{
4213 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004214 }
drh18b67f32014-12-12 00:20:37 +00004215 if( pKey ){
4216 assert( sqlite3KeyInfoIsWriteable(pKey) );
4217 for(i=0; i<nCol; i++){
4218 char *zColl = pIdx->azColl[i];
4219 assert( zColl!=0 );
4220 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4221 sqlite3LocateCollSeq(pParse, zColl);
4222 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004223 }
drh18b67f32014-12-12 00:20:37 +00004224 if( pParse->nErr ){
4225 sqlite3KeyInfoUnref(pKey);
4226 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004227 }
danielk1977b3bf5562006-01-10 17:58:23 +00004228 }
drh18b67f32014-12-12 00:20:37 +00004229 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004230}
drh8b471862014-01-11 13:22:17 +00004231
4232#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004233/*
4234** This routine is invoked once per CTE by the parser while parsing a
4235** WITH clause.
drh8b471862014-01-11 13:22:17 +00004236*/
dan7d562db2014-01-11 19:19:36 +00004237With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004238 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004239 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004240 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004241 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004242 Select *pQuery /* Query used to initialize the table */
4243){
dan4e9119d2014-01-13 15:12:23 +00004244 sqlite3 *db = pParse->db;
4245 With *pNew;
4246 char *zName;
4247
4248 /* Check that the CTE name is unique within this WITH clause. If
4249 ** not, store an error in the Parse structure. */
4250 zName = sqlite3NameFromToken(pParse->db, pName);
4251 if( zName && pWith ){
4252 int i;
4253 for(i=0; i<pWith->nCte; i++){
4254 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004255 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004256 }
4257 }
4258 }
4259
4260 if( pWith ){
4261 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4262 pNew = sqlite3DbRealloc(db, pWith, nByte);
4263 }else{
4264 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4265 }
4266 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004267 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004268
4269 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004270 sqlite3ExprListDelete(db, pArglist);
4271 sqlite3SelectDelete(db, pQuery);
4272 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004273 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004274 }else{
4275 pNew->a[pNew->nCte].pSelect = pQuery;
4276 pNew->a[pNew->nCte].pCols = pArglist;
4277 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004278 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004279 pNew->nCte++;
4280 }
4281
4282 return pNew;
drh8b471862014-01-11 13:22:17 +00004283}
4284
dan7d562db2014-01-11 19:19:36 +00004285/*
4286** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004287*/
dan7d562db2014-01-11 19:19:36 +00004288void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004289 if( pWith ){
4290 int i;
4291 for(i=0; i<pWith->nCte; i++){
4292 struct Cte *pCte = &pWith->a[i];
4293 sqlite3ExprListDelete(db, pCte->pCols);
4294 sqlite3SelectDelete(db, pCte->pSelect);
4295 sqlite3DbFree(db, pCte->zName);
4296 }
4297 sqlite3DbFree(db, pWith);
4298 }
drh8b471862014-01-11 13:22:17 +00004299}
4300#endif /* !defined(SQLITE_OMIT_CTE) */