blob: 0c02a56fe75d95a34961835ea3aac0d39285e4a9 [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;
145 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000146 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000147 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000148
drh80242052004-06-09 00:48:12 +0000149 /* Begin by generating some termination code at the end of the
150 ** vdbe program
151 */
drh80242052004-06-09 00:48:12 +0000152 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000153 assert( !pParse->isMultiWrite
154 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000155 if( v ){
drh61019c72014-01-04 16:49:02 +0000156 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
drh66a51672008-01-03 00:01:23 +0000157 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000158
drhb2445d52014-09-11 14:01:41 +0000159#if SQLITE_USER_AUTHENTICATION
160 if( pParse->nTableLock>0 && db->init.busy==0 ){
drh7883ecf2014-09-11 16:19:31 +0000161 sqlite3UserAuthInit(db);
drhb2445d52014-09-11 14:01:41 +0000162 if( db->auth.authLevel<UAUTH_User ){
drh7883ecf2014-09-11 16:19:31 +0000163 pParse->rc = SQLITE_AUTH_USER;
164 sqlite3ErrorMsg(pParse, "user not authenticated");
165 return;
drhb2445d52014-09-11 14:01:41 +0000166 }
167 }
168#endif
169
drh0e3d7472004-06-19 17:33:07 +0000170 /* The cookie mask contains one bit for each database file open.
171 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
172 ** set for each database that is used. Generate code to start a
173 ** transaction on each used database and to verify the schema cookie
174 ** on each used database.
175 */
drha7ab6d82014-07-21 15:44:39 +0000176 if( db->mallocFailed==0
177 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
178 ){
drhaceb31b2014-02-08 01:40:27 +0000179 int iDb, i;
180 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
181 sqlite3VdbeJumpHere(v, 0);
drha7ab6d82014-07-21 15:44:39 +0000182 for(iDb=0; iDb<db->nDb; iDb++){
183 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000184 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000185 sqlite3VdbeAddOp4Int(v,
186 OP_Transaction, /* Opcode */
187 iDb, /* P1 */
drha7ab6d82014-07-21 15:44:39 +0000188 DbMaskTest(pParse->writeMask,iDb), /* P2 */
drhb22f7c82014-02-06 23:56:27 +0000189 pParse->cookieValue[iDb], /* P3 */
190 db->aDb[iDb].pSchema->iGeneration /* P4 */
191 );
192 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
drh80242052004-06-09 00:48:12 +0000193 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000194#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000195 for(i=0; i<pParse->nVtabLock; i++){
196 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
197 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000198 }
drhf30a9692013-11-15 01:10:18 +0000199 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000200#endif
danielk1977c00da102006-01-07 13:21:04 +0000201
202 /* Once all the cookies have been verified and transactions opened,
203 ** obtain the required table-locks. This is a no-op unless the
204 ** shared-cache feature is enabled.
205 */
206 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000207
208 /* Initialize any AUTOINCREMENT data structures required.
209 */
210 sqlite3AutoincrementBegin(pParse);
211
drhf30a9692013-11-15 01:10:18 +0000212 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000213 if( pParse->pConstExpr ){
214 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000215 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000216 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000217 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000218 }
219 }
220
drh0b9f50d2009-06-23 20:28:53 +0000221 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000222 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000223 }
drh71c697e2004-08-08 23:39:19 +0000224 }
225
drh3f7d4e42004-07-24 14:35:58 +0000226
drh80242052004-06-09 00:48:12 +0000227 /* Get the VDBE program ready for execution
228 */
drh04491712009-05-13 17:21:13 +0000229 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000230 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000231 /* A minimum of one cursor is required if autoincrement is used
232 * See ticket [a696379c1f08866] */
233 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000234 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000235 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000236 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000237 }else{
drh483750b2003-01-29 18:46:51 +0000238 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000239 }
drha226d052002-09-25 19:04:07 +0000240 pParse->nTab = 0;
241 pParse->nMem = 0;
242 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000243 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000244 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000245}
246
247/*
drh205f48e2004-11-05 00:43:11 +0000248** Run the parser and code generator recursively in order to generate
249** code for the SQL statement given onto the end of the pParse context
250** currently under construction. When the parser is run recursively
251** this way, the final OP_Halt is not appended and other initialization
252** and finalization steps are omitted because those are handling by the
253** outermost parser.
254**
255** Not everything is nestable. This facility is designed to permit
256** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000257** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000258*/
259void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
260 va_list ap;
261 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000262 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000263 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000264# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
265 char saveBuf[SAVE_SZ];
266
drh205f48e2004-11-05 00:43:11 +0000267 if( pParse->nErr ) return;
268 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
269 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000270 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000271 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000272 if( zSql==0 ){
273 return; /* A malloc must have failed */
274 }
drh205f48e2004-11-05 00:43:11 +0000275 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000276 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
277 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000278 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000279 sqlite3DbFree(db, zErrMsg);
280 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000281 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000282 pParse->nested--;
283}
284
drhd4530972014-09-09 14:47:53 +0000285#if SQLITE_USER_AUTHENTICATION
286/*
287** Return TRUE if zTable is the name of the system table that stores the
288** list of users and their access credentials.
289*/
290int sqlite3UserAuthTable(const char *zTable){
291 return sqlite3_stricmp(zTable, "sqlite_user")==0;
292}
293#endif
294
drh205f48e2004-11-05 00:43:11 +0000295/*
danielk19778a414492004-06-29 08:59:35 +0000296** Locate the in-memory structure that describes a particular database
297** table given the name of that table and (optionally) the name of the
298** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000299**
danielk19778a414492004-06-29 08:59:35 +0000300** If zDatabase is 0, all databases are searched for the table and the
301** first matching table is returned. (No checking for duplicate table
302** names is done.) The search order is TEMP first, then MAIN, then any
303** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000304**
danielk19774adee202004-05-08 08:23:19 +0000305** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000306*/
drh9bb575f2004-09-06 17:24:11 +0000307Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000308 Table *p = 0;
309 int i;
drh645f63e2004-06-22 13:22:40 +0000310 assert( zName!=0 );
drh21206082011-04-04 18:22:02 +0000311 /* All mutexes are required for schema access. Make sure we hold them. */
312 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000313#if SQLITE_USER_AUTHENTICATION
314 /* Only the admin user is allowed to know that the sqlite_user table
315 ** exists */
drhe933b832014-09-10 17:34:28 +0000316 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
317 return 0;
318 }
drhd4530972014-09-09 14:47:53 +0000319#endif
danielk197753c0f742005-03-29 03:10:59 +0000320 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000321 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000322 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000323 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000324 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000325 if( p ) break;
326 }
drh74e24cd2002-01-09 03:19:59 +0000327 return p;
drh75897232000-05-29 14:26:00 +0000328}
329
330/*
danielk19778a414492004-06-29 08:59:35 +0000331** Locate the in-memory structure that describes a particular database
332** table given the name of that table and (optionally) the name of the
333** database containing the table. Return NULL if not found. Also leave an
334** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000335**
danielk19778a414492004-06-29 08:59:35 +0000336** The difference between this routine and sqlite3FindTable() is that this
337** routine leaves an error message in pParse->zErrMsg where
338** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000339*/
drhca424112008-01-25 15:04:48 +0000340Table *sqlite3LocateTable(
341 Parse *pParse, /* context in which to report errors */
342 int isView, /* True if looking for a VIEW rather than a TABLE */
343 const char *zName, /* Name of the table we are looking for */
344 const char *zDbase /* Name of the database. Might be NULL */
345){
drha69d9162003-04-17 22:57:53 +0000346 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000347
danielk19778a414492004-06-29 08:59:35 +0000348 /* Read the database schema. If an error occurs, leave an error message
349 ** and code in pParse and return NULL. */
350 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
351 return 0;
352 }
353
danielk19774adee202004-05-08 08:23:19 +0000354 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000355 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000356 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000357 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000358 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000359 }else{
drhca424112008-01-25 15:04:48 +0000360 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000361 }
drha6ecd332004-06-10 00:29:09 +0000362 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000363 }
drhe933b832014-09-10 17:34:28 +0000364#if SQLITE_USER_AUTHENICATION
365 else if( pParse->db->auth.authLevel<UAUTH_User ){
366 sqlite3ErrorMsg(pParse, "user not authenticated");
367 p = 0;
368 }
369#endif
drha69d9162003-04-17 22:57:53 +0000370 return p;
371}
372
373/*
dan41fb5cd2012-10-04 19:33:00 +0000374** Locate the table identified by *p.
375**
376** This is a wrapper around sqlite3LocateTable(). The difference between
377** sqlite3LocateTable() and this function is that this function restricts
378** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
379** non-NULL if it is part of a view or trigger program definition. See
380** sqlite3FixSrcList() for details.
381*/
382Table *sqlite3LocateTableItem(
383 Parse *pParse,
384 int isView,
385 struct SrcList_item *p
386){
387 const char *zDb;
388 assert( p->pSchema==0 || p->zDatabase==0 );
389 if( p->pSchema ){
390 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
391 zDb = pParse->db->aDb[iDb].zName;
392 }else{
393 zDb = p->zDatabase;
394 }
395 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
396}
397
398/*
drha69d9162003-04-17 22:57:53 +0000399** Locate the in-memory structure that describes
400** a particular index given the name of that index
401** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000402** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000403**
404** If zDatabase is 0, all databases are searched for the
405** table and the first matching index is returned. (No checking
406** for duplicate index names is done.) The search order is
407** TEMP first, then MAIN, then any auxiliary databases added
408** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000409*/
drh9bb575f2004-09-06 17:24:11 +0000410Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000411 Index *p = 0;
412 int i;
drh21206082011-04-04 18:22:02 +0000413 /* All mutexes are required for schema access. Make sure we hold them. */
414 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000415 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000416 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000417 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000418 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000419 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000420 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000421 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000422 if( p ) break;
423 }
drh74e24cd2002-01-09 03:19:59 +0000424 return p;
drh75897232000-05-29 14:26:00 +0000425}
426
427/*
drh956bc922004-07-24 17:38:29 +0000428** Reclaim the memory used by an index
429*/
dan1feeaed2010-07-23 15:41:47 +0000430static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000431#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000432 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000433#endif
drh2ec2fb22013-11-06 19:59:23 +0000434 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
drh1fe05372013-07-31 18:12:26 +0000435 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000436 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000437 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh633e6d52008-07-28 19:34:53 +0000438 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000439}
440
441/*
drhc96d8532005-05-03 12:30:33 +0000442** For the index called zIdxName which is found in the database iDb,
443** unlike that index from its Table then remove the index from
444** the index hash table and free all memory structures associated
445** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000446*/
drh9bb575f2004-09-06 17:24:11 +0000447void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000448 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000449 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000450
drh21206082011-04-04 18:22:02 +0000451 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
452 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000453 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000454 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000455 if( pIndex->pTable->pIndex==pIndex ){
456 pIndex->pTable->pIndex = pIndex->pNext;
457 }else{
458 Index *p;
drh04491712009-05-13 17:21:13 +0000459 /* Justification of ALWAYS(); The index must be on the list of
460 ** indices. */
461 p = pIndex->pTable->pIndex;
462 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
463 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000464 p->pNext = pIndex->pNext;
465 }
drh5e00f6c2001-09-13 13:46:56 +0000466 }
dan1feeaed2010-07-23 15:41:47 +0000467 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000468 }
drh956bc922004-07-24 17:38:29 +0000469 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000470}
471
472/*
drh81028a42012-05-15 18:28:27 +0000473** Look through the list of open database files in db->aDb[] and if
474** any have been closed, remove them from the list. Reallocate the
475** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000476**
drh81028a42012-05-15 18:28:27 +0000477** Entry 0 (the "main" database) and entry 1 (the "temp" database)
478** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000479*/
drh81028a42012-05-15 18:28:27 +0000480void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000481 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000482 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000483 struct Db *pDb = &db->aDb[i];
484 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000485 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000486 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000487 continue;
488 }
489 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000490 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000491 }
drh8bf8dc92003-05-17 17:35:10 +0000492 j++;
drh1c2d8412003-03-31 00:30:47 +0000493 }
494 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
495 db->nDb = j;
496 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
497 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000498 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000499 db->aDb = db->aDbStatic;
500 }
drhe0bc4042002-06-25 01:09:11 +0000501}
502
503/*
drh81028a42012-05-15 18:28:27 +0000504** Reset the schema for the database at index iDb. Also reset the
505** TEMP schema.
506*/
507void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000508 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000509 assert( iDb<db->nDb );
510
511 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000512 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000513 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
514 assert( pDb->pSchema!=0 );
515 sqlite3SchemaClear(pDb->pSchema);
516
517 /* If any database other than TEMP is reset, then also reset TEMP
518 ** since TEMP might be holding triggers that reference tables in the
519 ** other database.
520 */
521 if( iDb!=1 ){
522 pDb = &db->aDb[1];
523 assert( pDb->pSchema!=0 );
524 sqlite3SchemaClear(pDb->pSchema);
525 }
526 return;
527}
528
529/*
530** Erase all schema information from all attached databases (including
531** "main" and "temp") for a single database connection.
532*/
533void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
534 int i;
535 sqlite3BtreeEnterAll(db);
536 for(i=0; i<db->nDb; i++){
537 Db *pDb = &db->aDb[i];
538 if( pDb->pSchema ){
539 sqlite3SchemaClear(pDb->pSchema);
540 }
541 }
542 db->flags &= ~SQLITE_InternChanges;
543 sqlite3VtabUnlockList(db);
544 sqlite3BtreeLeaveAll(db);
545 sqlite3CollapseDatabaseArray(db);
546}
547
548/*
drhe0bc4042002-06-25 01:09:11 +0000549** This routine is called when a commit occurs.
550*/
drh9bb575f2004-09-06 17:24:11 +0000551void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000552 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000553}
554
555/*
dand46def72010-07-24 11:28:28 +0000556** Delete memory allocated for the column names of a table or view (the
557** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000558*/
dand46def72010-07-24 11:28:28 +0000559static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000560 int i;
561 Column *pCol;
562 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000563 if( (pCol = pTable->aCol)!=0 ){
564 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000565 sqlite3DbFree(db, pCol->zName);
566 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000567 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000568 sqlite3DbFree(db, pCol->zType);
569 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000570 }
drh633e6d52008-07-28 19:34:53 +0000571 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000572 }
drh956bc922004-07-24 17:38:29 +0000573}
574
575/*
drh75897232000-05-29 14:26:00 +0000576** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000577** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000578**
579** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000580** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000581** memory structures of the indices and foreign keys associated with
582** the table.
drh29ddd3a2012-05-15 12:49:32 +0000583**
584** The db parameter is optional. It is needed if the Table object
585** contains lookaside memory. (Table objects in the schema do not use
586** lookaside memory, but some ephemeral Table objects do.) Or the
587** db parameter can be used with db->pnBytesFreed to measure the memory
588** used by the Table object.
drh75897232000-05-29 14:26:00 +0000589*/
dan1feeaed2010-07-23 15:41:47 +0000590void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000591 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000592 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000593
dand46def72010-07-24 11:28:28 +0000594 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000595
drhed8a3bb2005-06-06 21:19:56 +0000596 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000597 if( !pTable ) return;
598 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000599
drh29ddd3a2012-05-15 12:49:32 +0000600 /* Record the number of outstanding lookaside allocations in schema Tables
601 ** prior to doing any free() operations. Since schema Tables do not use
602 ** lookaside, this number should not change. */
603 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
604 db->lookaside.nOut : 0 );
605
dand46def72010-07-24 11:28:28 +0000606 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000607 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
608 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000609 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000610 if( !db || db->pnBytesFreed==0 ){
611 char *zName = pIndex->zName;
612 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000613 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000614 );
drh21206082011-04-04 18:22:02 +0000615 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000616 assert( pOld==pIndex || pOld==0 );
617 }
618 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000619 }
620
dan1da40a32009-09-19 17:00:31 +0000621 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000622 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000623
624 /* Delete the Table structure itself.
625 */
dand46def72010-07-24 11:28:28 +0000626 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000627 sqlite3DbFree(db, pTable->zName);
628 sqlite3DbFree(db, pTable->zColAff);
629 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000630#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000631 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000632#endif
drh078e4082010-07-28 19:17:51 +0000633#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000634 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000635#endif
drh633e6d52008-07-28 19:34:53 +0000636 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000637
638 /* Verify that no lookaside memory was used by schema tables */
639 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000640}
641
642/*
drh5edc3122001-09-13 21:53:09 +0000643** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000644** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000645*/
drh9bb575f2004-09-06 17:24:11 +0000646void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000647 Table *p;
drh956bc922004-07-24 17:38:29 +0000648 Db *pDb;
649
drhd229ca92002-01-09 13:30:41 +0000650 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000651 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000652 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000653 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000654 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000655 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000656 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000657 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000658 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000659}
660
661/*
drha99db3b2004-06-19 14:49:12 +0000662** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000663** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000664** is obtained from sqliteMalloc() and must be freed by the calling
665** function.
drh75897232000-05-29 14:26:00 +0000666**
drh24fb6272009-05-01 21:13:36 +0000667** Any quotation marks (ex: "name", 'name', [name], or `name`) that
668** surround the body of the token are removed.
669**
drhc96d8532005-05-03 12:30:33 +0000670** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000671** are not \000 terminated and are not persistent. The returned string
672** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000673*/
drh17435752007-08-16 04:30:38 +0000674char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000675 char *zName;
676 if( pName ){
drh17435752007-08-16 04:30:38 +0000677 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000678 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000679 }else{
680 zName = 0;
681 }
drh75897232000-05-29 14:26:00 +0000682 return zName;
683}
684
685/*
danielk1977cbb18d22004-05-28 11:37:27 +0000686** Open the sqlite_master table stored in database number iDb for
687** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000688*/
danielk1977c00da102006-01-07 13:21:04 +0000689void sqlite3OpenMasterTable(Parse *p, int iDb){
690 Vdbe *v = sqlite3GetVdbe(p);
691 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000692 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000693 if( p->nTab==0 ){
694 p->nTab = 1;
695 }
drhe0bc4042002-06-25 01:09:11 +0000696}
697
698/*
danielk197704103022009-02-03 16:51:24 +0000699** Parameter zName points to a nul-terminated buffer containing the name
700** of a database ("main", "temp" or the name of an attached db). This
701** function returns the index of the named database in db->aDb[], or
702** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000703*/
danielk197704103022009-02-03 16:51:24 +0000704int sqlite3FindDbName(sqlite3 *db, const char *zName){
705 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000706 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000707 Db *pDb;
708 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000709 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000710 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000711 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000712 break;
drh73c42a12004-11-20 18:13:10 +0000713 }
danielk1977cbb18d22004-05-28 11:37:27 +0000714 }
715 }
danielk1977576ec6b2005-01-21 11:55:25 +0000716 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000717}
718
danielk197704103022009-02-03 16:51:24 +0000719/*
720** The token *pName contains the name of a database (either "main" or
721** "temp" or the name of an attached db). This routine returns the
722** index of the named database in db->aDb[], or -1 if the named db
723** does not exist.
724*/
725int sqlite3FindDb(sqlite3 *db, Token *pName){
726 int i; /* Database number */
727 char *zName; /* Name we are searching for */
728 zName = sqlite3NameFromToken(db, pName);
729 i = sqlite3FindDbName(db, zName);
730 sqlite3DbFree(db, zName);
731 return i;
732}
733
drh0e3d7472004-06-19 17:33:07 +0000734/* The table or view or trigger name is passed to this routine via tokens
735** pName1 and pName2. If the table name was fully qualified, for example:
736**
737** CREATE TABLE xxx.yyy (...);
738**
739** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
740** the table name is not fully qualified, i.e.:
741**
742** CREATE TABLE yyy(...);
743**
744** Then pName1 is set to "yyy" and pName2 is "".
745**
746** This routine sets the *ppUnqual pointer to point at the token (pName1 or
747** pName2) that stores the unqualified table name. The index of the
748** database "xxx" is returned.
749*/
danielk1977ef2cb632004-05-29 02:37:19 +0000750int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000751 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000752 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000753 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
754 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000755){
drh0e3d7472004-06-19 17:33:07 +0000756 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000757 sqlite3 *db = pParse->db;
758
drhc4a64fa2009-05-11 20:53:28 +0000759 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000760 if( db->init.busy ) {
761 sqlite3ErrorMsg(pParse, "corrupt database");
762 pParse->nErr++;
763 return -1;
764 }
danielk1977cbb18d22004-05-28 11:37:27 +0000765 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000766 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000767 if( iDb<0 ){
768 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
769 pParse->nErr++;
770 return -1;
771 }
772 }else{
773 assert( db->init.iDb==0 || db->init.busy );
774 iDb = db->init.iDb;
775 *pUnqual = pName1;
776 }
777 return iDb;
778}
779
780/*
danielk1977d8123362004-06-12 09:25:12 +0000781** This routine is used to check if the UTF-8 string zName is a legal
782** unqualified name for a new schema object (table, index, view or
783** trigger). All names are legal except those that begin with the string
784** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
785** is reserved for internal use.
786*/
787int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000788 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000789 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000790 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000791 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
792 return SQLITE_ERROR;
793 }
794 return SQLITE_OK;
795}
796
797/*
drh44156282013-10-23 22:23:03 +0000798** Return the PRIMARY KEY index of a table
799*/
800Index *sqlite3PrimaryKeyIndex(Table *pTab){
801 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000802 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000803 return p;
804}
805
806/*
807** Return the column of index pIdx that corresponds to table
808** column iCol. Return -1 if not found.
809*/
810i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
811 int i;
812 for(i=0; i<pIdx->nColumn; i++){
813 if( iCol==pIdx->aiColumn[i] ) return i;
814 }
815 return -1;
816}
817
818/*
drh75897232000-05-29 14:26:00 +0000819** Begin constructing a new table representation in memory. This is
820** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000821** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000822** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000823** flag is true if the table should be stored in the auxiliary database
824** file instead of in the main database file. This is normally the case
825** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000826** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000827**
drhf57b3392001-10-08 13:22:32 +0000828** The new table record is initialized and put in pParse->pNewTable.
829** As more of the CREATE TABLE statement is parsed, additional action
830** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000831** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000832** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000833*/
danielk19774adee202004-05-08 08:23:19 +0000834void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000835 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000836 Token *pName1, /* First part of the name of the table or view */
837 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000838 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000839 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000840 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000841 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000842){
drh75897232000-05-29 14:26:00 +0000843 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000844 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000845 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000846 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000847 int iDb; /* Database number to create the table in */
848 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000849
danielk1977cbb18d22004-05-28 11:37:27 +0000850 /* The table or view name to create is passed to this routine via tokens
851 ** pName1 and pName2. If the table name was fully qualified, for example:
852 **
853 ** CREATE TABLE xxx.yyy (...);
854 **
855 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
856 ** the table name is not fully qualified, i.e.:
857 **
858 ** CREATE TABLE yyy(...);
859 **
860 ** Then pName1 is set to "yyy" and pName2 is "".
861 **
862 ** The call below sets the pName pointer to point at the token (pName1 or
863 ** pName2) that stores the unqualified table name. The variable iDb is
864 ** set to the index of the database that the table or view is to be
865 ** created in.
866 */
danielk1977ef2cb632004-05-29 02:37:19 +0000867 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000868 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000869 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
870 /* If creating a temp table, the name may not be qualified. Unless
871 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000872 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000873 return;
874 }
danielk197753c0f742005-03-29 03:10:59 +0000875 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000876
877 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000878 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000879 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000880 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000881 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000882 }
drh1d85d932004-02-14 23:05:52 +0000883 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000884#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000885 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000886 {
887 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000888 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000889 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000890 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000891 }
drhe5f9c642003-01-13 23:27:31 +0000892 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000893 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000894 code = SQLITE_CREATE_TEMP_VIEW;
895 }else{
896 code = SQLITE_CREATE_VIEW;
897 }
898 }else{
danielk197753c0f742005-03-29 03:10:59 +0000899 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000900 code = SQLITE_CREATE_TEMP_TABLE;
901 }else{
902 code = SQLITE_CREATE_TABLE;
903 }
904 }
danielk1977f1a381e2006-06-16 08:01:02 +0000905 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000906 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000907 }
908 }
909#endif
drhf57b3392001-10-08 13:22:32 +0000910
drhf57b3392001-10-08 13:22:32 +0000911 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000912 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000913 ** it does. The exception is if the statement being parsed was passed
914 ** to an sqlite3_declare_vtab() call. In that case only the column names
915 ** and types will be used, so there is no need to test for namespace
916 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000917 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000918 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000919 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000920 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
921 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000922 }
dana16d1062010-09-28 17:37:28 +0000923 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000924 if( pTable ){
925 if( !noErr ){
926 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000927 }else{
928 assert( !db->init.busy );
929 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000930 }
931 goto begin_table_error;
932 }
drh8a8a0d12010-09-28 20:26:44 +0000933 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000934 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
935 goto begin_table_error;
936 }
drh75897232000-05-29 14:26:00 +0000937 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000938
danielk197726783a52007-08-29 14:06:22 +0000939 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000940 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000941 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000942 pParse->rc = SQLITE_NOMEM;
943 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000944 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000945 }
drh75897232000-05-29 14:26:00 +0000946 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000947 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000948 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000949 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000950 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000951 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000952 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000953
drh4794f732004-11-05 17:17:50 +0000954 /* If this is the magic sqlite_sequence table used by autoincrement,
955 ** then record a pointer to this table in the main database structure
956 ** so that INSERT can find the table easily.
957 */
958#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000959 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000960 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000961 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000962 }
963#endif
964
drh17f71932002-02-21 12:01:27 +0000965 /* Begin generating the code that will insert the table record into
966 ** the SQLITE_MASTER table. Note in particular that we must go ahead
967 ** and allocate the record number for the table entry now. Before any
968 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
969 ** indices to be created and the table record must come before the
970 ** indices. Hence, the record number for the table must be allocated
971 ** now.
972 */
danielk19774adee202004-05-08 08:23:19 +0000973 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000974 int j1;
drhe321c292006-01-12 01:56:43 +0000975 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000976 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000977 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000978
danielk197720b1eaf2006-07-26 16:22:14 +0000979#ifndef SQLITE_OMIT_VIRTUALTABLE
980 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000981 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000982 }
983#endif
984
danielk197736963fd2005-02-19 08:18:05 +0000985 /* If the file format and encoding in the database have not been set,
986 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000987 */
drhb7654112008-01-12 12:48:07 +0000988 reg1 = pParse->regRowid = ++pParse->nMem;
989 reg2 = pParse->regRoot = ++pParse->nMem;
990 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000991 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000992 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000993 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000994 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000995 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000996 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000997 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +0000998 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000999 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001000 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001001
drh4794f732004-11-05 17:17:50 +00001002 /* This just creates a place-holder record in the sqlite_master table.
1003 ** The record created does not contain anything yet. It will be replaced
1004 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001005 **
drh0fa991b2009-03-21 16:19:26 +00001006 ** The rowid for the new entry is left in register pParse->regRowid.
1007 ** The root page number of the new table is left in reg pParse->regRoot.
1008 ** The rowid and root page number values are needed by the code that
1009 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001010 */
danielk1977f1a381e2006-06-16 08:01:02 +00001011#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1012 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001013 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001014 }else
1015#endif
1016 {
drh8a120f82013-11-01 17:59:53 +00001017 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001018 }
danielk1977c00da102006-01-07 13:21:04 +00001019 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001020 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1021 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1022 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1023 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001024 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001025 }
drh23bf66d2004-12-14 03:34:34 +00001026
1027 /* Normal (non-error) return. */
1028 return;
1029
1030 /* If an error occurs, we jump here */
1031begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001032 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001033 return;
drh75897232000-05-29 14:26:00 +00001034}
1035
1036/*
danielk1977c60e9b82005-01-31 12:42:29 +00001037** This macro is used to compare two strings in a case-insensitive manner.
1038** It is slightly faster than calling sqlite3StrICmp() directly, but
1039** produces larger code.
1040**
1041** WARNING: This macro is not compatible with the strcmp() family. It
1042** returns true if the two strings are equal, otherwise false.
1043*/
1044#define STRICMP(x, y) (\
1045sqlite3UpperToLower[*(unsigned char *)(x)]== \
1046sqlite3UpperToLower[*(unsigned char *)(y)] \
1047&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1048
1049/*
drh75897232000-05-29 14:26:00 +00001050** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001051**
1052** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001053** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001054** first to get things going. Then this routine is called for each
1055** column.
drh75897232000-05-29 14:26:00 +00001056*/
danielk19774adee202004-05-08 08:23:19 +00001057void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001058 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001059 int i;
drha99db3b2004-06-19 14:49:12 +00001060 char *z;
drhc9b84a12002-06-20 11:36:48 +00001061 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001062 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001063 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001064#if SQLITE_MAX_COLUMN
1065 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001066 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1067 return;
1068 }
drhbb4957f2008-03-20 14:03:29 +00001069#endif
danielk1977ae74e032008-12-23 11:11:51 +00001070 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001071 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001072 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001073 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001074 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001075 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001076 return;
1077 }
1078 }
drh75897232000-05-29 14:26:00 +00001079 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001080 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001081 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001082 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001083 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001084 return;
1085 }
drh6d4abfb2001-10-22 02:58:08 +00001086 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001087 }
drhc9b84a12002-06-20 11:36:48 +00001088 pCol = &p->aCol[p->nCol];
1089 memset(pCol, 0, sizeof(p->aCol[0]));
1090 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001091
1092 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001093 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1094 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001095 */
danielk19774f057f92004-06-08 00:02:33 +00001096 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001097 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001098 p->nCol++;
drh75897232000-05-29 14:26:00 +00001099}
1100
1101/*
drh382c0242001-10-06 16:33:02 +00001102** This routine is called by the parser while in the middle of
1103** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1104** been seen on a column. This routine sets the notNull flag on
1105** the column currently under construction.
1106*/
danielk19774adee202004-05-08 08:23:19 +00001107void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001108 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001109 p = pParse->pNewTable;
1110 if( p==0 || NEVER(p->nCol<1) ) return;
1111 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001112}
1113
1114/*
danielk197752a83fb2005-01-31 12:56:44 +00001115** Scan the column type name zType (length nType) and return the
1116** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001117**
1118** This routine does a case-independent search of zType for the
1119** substrings in the following table. If one of the substrings is
1120** found, the corresponding affinity is returned. If zType contains
1121** more than one of the substrings, entries toward the top of
1122** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001123** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001124**
1125** Substring | Affinity
1126** --------------------------------
1127** 'INT' | SQLITE_AFF_INTEGER
1128** 'CHAR' | SQLITE_AFF_TEXT
1129** 'CLOB' | SQLITE_AFF_TEXT
1130** 'TEXT' | SQLITE_AFF_TEXT
1131** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001132** 'REAL' | SQLITE_AFF_REAL
1133** 'FLOA' | SQLITE_AFF_REAL
1134** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001135**
1136** If none of the substrings in the above table are found,
1137** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001138*/
drhfdaac672013-10-04 15:30:21 +00001139char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001140 u32 h = 0;
1141 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001142 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001143
drhfdaac672013-10-04 15:30:21 +00001144 if( zIn==0 ) return aff;
1145 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001146 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001147 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001148 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001149 aff = SQLITE_AFF_TEXT;
1150 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001151 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1152 aff = SQLITE_AFF_TEXT;
1153 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1154 aff = SQLITE_AFF_TEXT;
1155 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001156 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001157 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001158 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001159#ifndef SQLITE_OMIT_FLOATING_POINT
1160 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1161 && aff==SQLITE_AFF_NUMERIC ){
1162 aff = SQLITE_AFF_REAL;
1163 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1164 && aff==SQLITE_AFF_NUMERIC ){
1165 aff = SQLITE_AFF_REAL;
1166 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1167 && aff==SQLITE_AFF_NUMERIC ){
1168 aff = SQLITE_AFF_REAL;
1169#endif
danielk1977201f7162005-02-01 02:13:29 +00001170 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001171 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001172 break;
danielk197752a83fb2005-01-31 12:56:44 +00001173 }
1174 }
drhd3037a42013-10-04 18:29:25 +00001175
1176 /* If pszEst is not NULL, store an estimate of the field size. The
1177 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001178 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001179 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001180 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001181 if( zChar ){
1182 while( zChar[0] ){
1183 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001184 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001185 sqlite3GetInt32(zChar, &v);
1186 v = v/4 + 1;
1187 if( v>255 ) v = 255;
1188 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1189 break;
1190 }
1191 zChar++;
drhfdaac672013-10-04 15:30:21 +00001192 }
drhd3037a42013-10-04 18:29:25 +00001193 }else{
1194 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001195 }
drhfdaac672013-10-04 15:30:21 +00001196 }
1197 }
danielk1977b3dff962005-02-01 01:21:55 +00001198 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001199}
1200
1201/*
drh382c0242001-10-06 16:33:02 +00001202** This routine is called by the parser while in the middle of
1203** parsing a CREATE TABLE statement. The pFirst token is the first
1204** token in the sequence of tokens that describe the type of the
1205** column currently under construction. pLast is the last token
1206** in the sequence. Use this information to construct a string
1207** that contains the typename of the column and store that string
1208** in zType.
1209*/
drh487e2622005-06-25 18:42:14 +00001210void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001211 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001212 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001213
drhc4a64fa2009-05-11 20:53:28 +00001214 p = pParse->pNewTable;
1215 if( p==0 || NEVER(p->nCol<1) ) return;
1216 pCol = &p->aCol[p->nCol-1];
1217 assert( pCol->zType==0 );
1218 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001219 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001220}
1221
1222/*
danielk19777977a172004-11-09 12:44:37 +00001223** The expression is the default value for the most recently added column
1224** of the table currently under construction.
1225**
1226** Default value expressions must be constant. Raise an exception if this
1227** is not the case.
drhd9b02572001-04-15 00:37:09 +00001228**
1229** This routine is called by the parser while in the middle of
1230** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001231*/
drhb7916a72009-05-27 10:31:29 +00001232void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001233 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001234 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001235 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001236 p = pParse->pNewTable;
1237 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001238 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001239 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001240 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1241 pCol->zName);
1242 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001243 /* A copy of pExpr is used instead of the original, as pExpr contains
1244 ** tokens that point to volatile memory. The 'span' of the expression
1245 ** is required by pragma table_info.
1246 */
drh633e6d52008-07-28 19:34:53 +00001247 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001248 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1249 sqlite3DbFree(db, pCol->zDflt);
1250 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001251 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001252 }
danielk19777977a172004-11-09 12:44:37 +00001253 }
drhb7916a72009-05-27 10:31:29 +00001254 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001255}
1256
1257/*
drh4a324312001-12-21 14:30:42 +00001258** Designate the PRIMARY KEY for the table. pList is a list of names
1259** of columns that form the primary key. If pList is NULL, then the
1260** most recently added column of the table is the primary key.
1261**
1262** A table can have at most one primary key. If the table already has
1263** a primary key (and this is the second primary key) then create an
1264** error.
1265**
1266** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001267** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001268** field of the table under construction to be the index of the
1269** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1270** no INTEGER PRIMARY KEY.
1271**
1272** If the key is not an INTEGER PRIMARY KEY, then create a unique
1273** index for the key. No index is created for INTEGER PRIMARY KEYs.
1274*/
drh205f48e2004-11-05 00:43:11 +00001275void sqlite3AddPrimaryKey(
1276 Parse *pParse, /* Parsing context */
1277 ExprList *pList, /* List of field names to be indexed */
1278 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001279 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1280 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001281){
drh4a324312001-12-21 14:30:42 +00001282 Table *pTab = pParse->pNewTable;
1283 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001284 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001285 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001286 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001287 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001288 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001289 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001290 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001291 }
drh7d10d5a2008-08-20 16:35:10 +00001292 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001293 if( pList==0 ){
1294 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001295 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001296 zType = pTab->aCol[iCol].zType;
1297 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001298 }else{
drh8ea30bf2013-10-22 01:18:17 +00001299 nTerm = pList->nExpr;
1300 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001301 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001302 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001303 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1304 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001305 break;
1306 }
drh78100cc2003-08-23 22:40:53 +00001307 }
drh4a324312001-12-21 14:30:42 +00001308 }
1309 }
drh8ea30bf2013-10-22 01:18:17 +00001310 if( nTerm==1
1311 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1312 && sortOrder==SQLITE_SO_ASC
1313 ){
drh4a324312001-12-21 14:30:42 +00001314 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001315 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001316 assert( autoInc==0 || autoInc==1 );
1317 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001318 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001319 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001320#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001321 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1322 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001323#endif
drh4a324312001-12-21 14:30:42 +00001324 }else{
drhc6bd4e42013-11-02 14:37:18 +00001325 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001326 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001327 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001328 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001329 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001330 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001331 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001332 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001333 }
drhe0194f22003-02-26 13:52:51 +00001334 pList = 0;
drh4a324312001-12-21 14:30:42 +00001335 }
drhe0194f22003-02-26 13:52:51 +00001336
1337primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001338 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001339 return;
drh4a324312001-12-21 14:30:42 +00001340}
1341
1342/*
drhffe07b22005-11-03 00:41:17 +00001343** Add a new CHECK constraint to the table currently under construction.
1344*/
1345void sqlite3AddCheckConstraint(
1346 Parse *pParse, /* Parsing context */
1347 Expr *pCheckExpr /* The check expression */
1348){
1349#ifndef SQLITE_OMIT_CHECK
1350 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001351 sqlite3 *db = pParse->db;
1352 if( pTab && !IN_DECLARE_VTAB
1353 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1354 ){
drh2938f922012-03-07 19:13:29 +00001355 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1356 if( pParse->constraintName.n ){
1357 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1358 }
drh33e619f2009-05-28 01:00:55 +00001359 }else
drhffe07b22005-11-03 00:41:17 +00001360#endif
drh33e619f2009-05-28 01:00:55 +00001361 {
drh2938f922012-03-07 19:13:29 +00001362 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001363 }
drhffe07b22005-11-03 00:41:17 +00001364}
1365
1366/*
drhd3d39e92004-05-20 22:16:29 +00001367** Set the collation function of the most recently parsed table column
1368** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001369*/
danielk197739002502007-11-12 09:50:26 +00001370void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001371 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001372 int i;
danielk197739002502007-11-12 09:50:26 +00001373 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001374 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001375
danielk1977b8cbb872006-06-19 05:33:45 +00001376 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001377 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001378 db = pParse->db;
1379 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001380 if( !zColl ) return;
1381
drhc4a64fa2009-05-11 20:53:28 +00001382 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001383 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001384 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001385 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001386
1387 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1388 ** then an index may have been created on this column before the
1389 ** collation type was added. Correct this if it is the case.
1390 */
1391 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001392 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001393 if( pIdx->aiColumn[0]==i ){
1394 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001395 }
1396 }
danielk197739002502007-11-12 09:50:26 +00001397 }else{
drh633e6d52008-07-28 19:34:53 +00001398 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001399 }
danielk19777cedc8d2004-06-10 10:50:08 +00001400}
1401
danielk1977466be562004-06-10 02:16:01 +00001402/*
1403** This function returns the collation sequence for database native text
1404** encoding identified by the string zName, length nName.
1405**
1406** If the requested collation sequence is not available, or not available
1407** in the database native encoding, the collation factory is invoked to
1408** request it. If the collation factory does not supply such a sequence,
1409** and the sequence is available in another text encoding, then that is
1410** returned instead.
1411**
1412** If no versions of the requested collations sequence are available, or
1413** another error occurs, NULL is returned and an error message written into
1414** pParse.
drha34001c2007-02-02 12:44:37 +00001415**
1416** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1417** invokes the collation factory if the named collation cannot be found
1418** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001419**
1420** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001421*/
drhc4a64fa2009-05-11 20:53:28 +00001422CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001423 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001424 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001425 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001426 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001427
drhc4a64fa2009-05-11 20:53:28 +00001428 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001429 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001430 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001431 }
1432
danielk19770202b292004-06-09 09:55:16 +00001433 return pColl;
1434}
1435
1436
drh8e2ca022002-06-17 17:07:19 +00001437/*
drh3f7d4e42004-07-24 14:35:58 +00001438** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001439**
1440** The schema cookie is used to determine when the schema for the
1441** database changes. After each schema change, the cookie value
1442** changes. When a process first reads the schema it records the
1443** cookie. Thereafter, whenever it goes to access the database,
1444** it checks the cookie to make sure the schema has not changed
1445** since it was last read.
1446**
1447** This plan is not completely bullet-proof. It is possible for
1448** the schema to change multiple times and for the cookie to be
1449** set back to prior value. But schema changes are infrequent
1450** and the probability of hitting the same cookie value is only
1451** 1 chance in 2^32. So we're safe enough.
1452*/
drh9cbf3422008-01-17 16:22:13 +00001453void sqlite3ChangeCookie(Parse *pParse, int iDb){
1454 int r1 = sqlite3GetTempReg(pParse);
1455 sqlite3 *db = pParse->db;
1456 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001457 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001458 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001459 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001460 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001461}
1462
1463/*
drh969fa7c2002-02-18 18:30:32 +00001464** Measure the number of characters needed to output the given
1465** identifier. The number returned includes any quotes used
1466** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001467**
1468** The estimate is conservative. It might be larger that what is
1469** really needed.
drh969fa7c2002-02-18 18:30:32 +00001470*/
1471static int identLength(const char *z){
1472 int n;
drh17f71932002-02-21 12:01:27 +00001473 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001474 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001475 }
drh234c39d2004-07-24 03:30:47 +00001476 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001477}
1478
1479/*
danielk19771b870de2009-03-14 08:37:23 +00001480** The first parameter is a pointer to an output buffer. The second
1481** parameter is a pointer to an integer that contains the offset at
1482** which to write into the output buffer. This function copies the
1483** nul-terminated string pointed to by the third parameter, zSignedIdent,
1484** to the specified offset in the buffer and updates *pIdx to refer
1485** to the first byte after the last byte written before returning.
1486**
1487** If the string zSignedIdent consists entirely of alpha-numeric
1488** characters, does not begin with a digit and is not an SQL keyword,
1489** then it is copied to the output buffer exactly as it is. Otherwise,
1490** it is quoted using double-quotes.
1491*/
drhc4a64fa2009-05-11 20:53:28 +00001492static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001493 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001494 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001495 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001496
drh17f71932002-02-21 12:01:27 +00001497 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001498 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001499 }
drhc7407522014-01-10 20:38:12 +00001500 needQuote = sqlite3Isdigit(zIdent[0])
1501 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1502 || zIdent[j]!=0
1503 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001504
drh234c39d2004-07-24 03:30:47 +00001505 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001506 for(j=0; zIdent[j]; j++){
1507 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001508 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001509 }
drh234c39d2004-07-24 03:30:47 +00001510 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001511 z[i] = 0;
1512 *pIdx = i;
1513}
1514
1515/*
1516** Generate a CREATE TABLE statement appropriate for the given
1517** table. Memory to hold the text of the statement is obtained
1518** from sqliteMalloc() and must be freed by the calling function.
1519*/
drh1d34fde2009-02-03 15:50:33 +00001520static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001521 int i, k, n;
1522 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001523 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001524 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001525 n = 0;
drh234c39d2004-07-24 03:30:47 +00001526 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001527 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001528 }
1529 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001530 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001531 zSep = "";
1532 zSep2 = ",";
1533 zEnd = ")";
1534 }else{
1535 zSep = "\n ";
1536 zSep2 = ",\n ";
1537 zEnd = "\n)";
1538 }
drhe0bc4042002-06-25 01:09:11 +00001539 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001540 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001541 if( zStmt==0 ){
1542 db->mallocFailed = 1;
1543 return 0;
1544 }
drhbdb339f2009-02-02 18:03:21 +00001545 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001546 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001547 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001548 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001549 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001550 static const char * const azType[] = {
drhc4a64fa2009-05-11 20:53:28 +00001551 /* SQLITE_AFF_NONE */ "",
drh7ea31cc2014-09-18 14:36:00 +00001552 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001553 /* SQLITE_AFF_NUMERIC */ " NUM",
1554 /* SQLITE_AFF_INTEGER */ " INT",
1555 /* SQLITE_AFF_REAL */ " REAL"
1556 };
1557 int len;
1558 const char *zType;
1559
drh5bb3eb92007-05-04 13:15:55 +00001560 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001561 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001562 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001563 identPut(zStmt, &k, pCol->zName);
drh7ea31cc2014-09-18 14:36:00 +00001564 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1565 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001566 testcase( pCol->affinity==SQLITE_AFF_NONE );
drh7ea31cc2014-09-18 14:36:00 +00001567 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001568 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1569 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1570 testcase( pCol->affinity==SQLITE_AFF_REAL );
1571
drh7ea31cc2014-09-18 14:36:00 +00001572 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
drhc4a64fa2009-05-11 20:53:28 +00001573 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001574 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001575 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001576 memcpy(&zStmt[k], zType, len);
1577 k += len;
1578 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001579 }
drh5bb3eb92007-05-04 13:15:55 +00001580 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001581 return zStmt;
1582}
1583
1584/*
drh7f9c5db2013-10-23 00:32:58 +00001585** Resize an Index object to hold N columns total. Return SQLITE_OK
1586** on success and SQLITE_NOMEM on an OOM error.
1587*/
1588static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1589 char *zExtra;
1590 int nByte;
1591 if( pIdx->nColumn>=N ) return SQLITE_OK;
1592 assert( pIdx->isResized==0 );
1593 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1594 zExtra = sqlite3DbMallocZero(db, nByte);
1595 if( zExtra==0 ) return SQLITE_NOMEM;
1596 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1597 pIdx->azColl = (char**)zExtra;
1598 zExtra += sizeof(char*)*N;
1599 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1600 pIdx->aiColumn = (i16*)zExtra;
1601 zExtra += sizeof(i16)*N;
1602 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1603 pIdx->aSortOrder = (u8*)zExtra;
1604 pIdx->nColumn = N;
1605 pIdx->isResized = 1;
1606 return SQLITE_OK;
1607}
1608
1609/*
drhfdaac672013-10-04 15:30:21 +00001610** Estimate the total row width for a table.
1611*/
drhe13e9f52013-10-05 19:18:00 +00001612static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001613 unsigned wTable = 0;
1614 const Column *pTabCol;
1615 int i;
1616 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1617 wTable += pTabCol->szEst;
1618 }
1619 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001620 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001621}
1622
1623/*
drhe13e9f52013-10-05 19:18:00 +00001624** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001625*/
drhe13e9f52013-10-05 19:18:00 +00001626static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001627 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001628 int i;
1629 const Column *aCol = pIdx->pTable->aCol;
1630 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001631 i16 x = pIdx->aiColumn[i];
1632 assert( x<pIdx->pTable->nCol );
1633 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001634 }
drhe13e9f52013-10-05 19:18:00 +00001635 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001636}
1637
drh7f9c5db2013-10-23 00:32:58 +00001638/* Return true if value x is found any of the first nCol entries of aiCol[]
1639*/
1640static int hasColumn(const i16 *aiCol, int nCol, int x){
1641 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1642 return 0;
1643}
1644
1645/*
drhc6bd4e42013-11-02 14:37:18 +00001646** This routine runs at the end of parsing a CREATE TABLE statement that
1647** has a WITHOUT ROWID clause. The job of this routine is to convert both
1648** internal schema data structures and the generated VDBE code so that they
1649** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1650** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001651**
drhc6bd4e42013-11-02 14:37:18 +00001652** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1653** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1654** data storage is a covering index btree.
1655** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001656** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001657** identified by the sqlite_master table entry of the table itself.
1658** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1659** schema to the rootpage from the main table.
1660** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1661** (5) Add all table columns to the PRIMARY KEY Index object
1662** so that the PRIMARY KEY is a covering index. The surplus
1663** columns are part of KeyInfo.nXField and are not used for
1664** sorting or lookup or uniqueness checks.
1665** (6) Replace the rowid tail on all automatically generated UNIQUE
1666** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001667*/
1668static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1669 Index *pIdx;
1670 Index *pPk;
1671 int nPk;
1672 int i, j;
1673 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001674 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001675
1676 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001677 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001678 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001679 */
1680 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001681 assert( v );
1682 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1683 }
1684
1685 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1686 ** table entry.
1687 */
1688 if( pParse->addrSkipPK ){
1689 assert( v );
1690 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001691 }
1692
1693 /* Locate the PRIMARY KEY index. Or, if this table was originally
1694 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1695 */
1696 if( pTab->iPKey>=0 ){
1697 ExprList *pList;
1698 pList = sqlite3ExprListAppend(pParse, 0, 0);
1699 if( pList==0 ) return;
1700 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1701 pTab->aCol[pTab->iPKey].zName);
1702 pList->a[0].sortOrder = pParse->iPkSortOrder;
1703 assert( pParse->pNewTable==pTab );
1704 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1705 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001706 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001707 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001708 }else{
1709 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001710 }
drh12826092013-11-05 22:39:17 +00001711 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001712 assert( pPk!=0 );
1713 nPk = pPk->nKeyCol;
1714
drhec95c442013-10-23 01:57:32 +00001715 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1716 for(i=0; i<nPk; i++){
1717 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1718 }
drh9eade082013-10-24 14:16:10 +00001719 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001720
drhc6bd4e42013-11-02 14:37:18 +00001721 /* The root page of the PRIMARY KEY is the table root page */
1722 pPk->tnum = pTab->tnum;
1723
drh7f9c5db2013-10-23 00:32:58 +00001724 /* Update the in-memory representation of all UNIQUE indices by converting
1725 ** the final rowid column into one or more columns of the PRIMARY KEY.
1726 */
1727 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1728 int n;
drh48dd1d82014-05-27 18:18:58 +00001729 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001730 for(i=n=0; i<nPk; i++){
1731 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1732 }
drh5a9a37b2013-11-05 17:30:04 +00001733 if( n==0 ){
1734 /* This index is a superset of the primary key */
1735 pIdx->nColumn = pIdx->nKeyCol;
1736 continue;
1737 }
drh7f9c5db2013-10-23 00:32:58 +00001738 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1739 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001740 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001741 pIdx->aiColumn[j] = pPk->aiColumn[i];
1742 pIdx->azColl[j] = pPk->azColl[i];
1743 j++;
1744 }
1745 }
drh00012df2013-11-05 01:59:07 +00001746 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1747 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001748 }
1749
1750 /* Add all table columns to the PRIMARY KEY index
1751 */
1752 if( nPk<pTab->nCol ){
1753 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1754 for(i=0, j=nPk; i<pTab->nCol; i++){
1755 if( !hasColumn(pPk->aiColumn, j, i) ){
1756 assert( j<pPk->nColumn );
1757 pPk->aiColumn[j] = i;
1758 pPk->azColl[j] = "BINARY";
1759 j++;
1760 }
1761 }
1762 assert( pPk->nColumn==j );
1763 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001764 }else{
1765 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001766 }
1767}
1768
drhfdaac672013-10-04 15:30:21 +00001769/*
drh75897232000-05-29 14:26:00 +00001770** This routine is called to report the final ")" that terminates
1771** a CREATE TABLE statement.
1772**
drhf57b3392001-10-08 13:22:32 +00001773** The table structure that other action routines have been building
1774** is added to the internal hash tables, assuming no errors have
1775** occurred.
drh75897232000-05-29 14:26:00 +00001776**
drh1d85d932004-02-14 23:05:52 +00001777** An entry for the table is made in the master table on disk, unless
1778** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001779** it means we are reading the sqlite_master table because we just
1780** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001781** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001782** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001783**
1784** If the pSelect argument is not NULL, it means that this routine
1785** was called to create a table generated from a
1786** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1787** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001788*/
danielk197719a8e7e2005-03-17 05:03:38 +00001789void sqlite3EndTable(
1790 Parse *pParse, /* Parse context */
1791 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001792 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1793 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001794 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1795){
drhfdaac672013-10-04 15:30:21 +00001796 Table *p; /* The new table */
1797 sqlite3 *db = pParse->db; /* The database connection */
1798 int iDb; /* Database in which the table lives */
1799 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001800
drh5969da42013-10-21 02:14:45 +00001801 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1802 return;
danielk1977261919c2005-12-06 12:52:59 +00001803 }
drh28037572000-08-02 13:47:41 +00001804 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001805 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001806
danielk1977517eb642004-06-07 10:00:31 +00001807 assert( !db->init.busy || !pSelect );
1808
drhc6bd4e42013-11-02 14:37:18 +00001809 /* If the db->init.busy is 1 it means we are reading the SQL off the
1810 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1811 ** So do not write to the disk again. Extract the root page number
1812 ** for the table from the db->init.newTnum field. (The page number
1813 ** should have been put there by the sqliteOpenCb routine.)
1814 */
1815 if( db->init.busy ){
1816 p->tnum = db->init.newTnum;
1817 }
1818
1819 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001820 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001821 if( (p->tabFlags & TF_Autoincrement) ){
1822 sqlite3ErrorMsg(pParse,
1823 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1824 return;
1825 }
drh5969da42013-10-21 02:14:45 +00001826 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001827 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001828 }else{
1829 p->tabFlags |= TF_WithoutRowid;
1830 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001831 }
1832 }
1833
drhb9bb7c12006-06-11 23:41:55 +00001834 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001835
drhffe07b22005-11-03 00:41:17 +00001836#ifndef SQLITE_OMIT_CHECK
1837 /* Resolve names in all CHECK constraint expressions.
1838 */
1839 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001840 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001841 }
1842#endif /* !defined(SQLITE_OMIT_CHECK) */
1843
drhe13e9f52013-10-05 19:18:00 +00001844 /* Estimate the average row size for the table and for all implied indices */
1845 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001846 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001847 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001848 }
1849
drhe3c41372001-09-17 20:25:58 +00001850 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001851 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001852 **
drhe0bc4042002-06-25 01:09:11 +00001853 ** If this is a TEMPORARY table, write the entry into the auxiliary
1854 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001855 */
drh1d85d932004-02-14 23:05:52 +00001856 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001857 int n;
drhd8bc7082000-06-07 23:51:50 +00001858 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001859 char *zType; /* "view" or "table" */
1860 char *zType2; /* "VIEW" or "TABLE" */
1861 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001862
danielk19774adee202004-05-08 08:23:19 +00001863 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001864 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001865
drh66a51672008-01-03 00:01:23 +00001866 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001867
drh0fa991b2009-03-21 16:19:26 +00001868 /*
1869 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001870 */
drh4ff6dfa2002-03-03 23:06:00 +00001871 if( p->pSelect==0 ){
1872 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001873 zType = "table";
1874 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001875#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001876 }else{
1877 /* A view */
drh4794f732004-11-05 17:17:50 +00001878 zType = "view";
1879 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001880#endif
drh4ff6dfa2002-03-03 23:06:00 +00001881 }
danielk1977517eb642004-06-07 10:00:31 +00001882
danielk1977517eb642004-06-07 10:00:31 +00001883 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1884 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001885 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001886 **
1887 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1888 ** suitable state to query for the column names and types to be used
1889 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001890 **
1891 ** A shared-cache write-lock is not required to write to the new table,
1892 ** as a schema-lock must have already been obtained to create it. Since
1893 ** a schema-lock excludes all other database users, the write-lock would
1894 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001895 */
1896 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001897 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001898 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001899
danielk19776ab3a2e2009-02-19 14:39:25 +00001900 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001901 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001902 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001903 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001904 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001905 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001906 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001907 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001908 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001909 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001910 assert( p->aCol==0 );
1911 p->nCol = pSelTab->nCol;
1912 p->aCol = pSelTab->aCol;
1913 pSelTab->nCol = 0;
1914 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001915 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001916 }
1917 }
drh4794f732004-11-05 17:17:50 +00001918
drh4794f732004-11-05 17:17:50 +00001919 /* Compute the complete text of the CREATE statement */
1920 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001921 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001922 }else{
drh8ea30bf2013-10-22 01:18:17 +00001923 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1924 n = (int)(pEnd2->z - pParse->sNameToken.z);
1925 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001926 zStmt = sqlite3MPrintf(db,
1927 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1928 );
drh4794f732004-11-05 17:17:50 +00001929 }
1930
1931 /* A slot for the record has already been allocated in the
1932 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001933 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001934 */
1935 sqlite3NestedParse(pParse,
1936 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001937 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1938 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001939 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001940 zType,
1941 p->zName,
1942 p->zName,
drhb7654112008-01-12 12:48:07 +00001943 pParse->regRoot,
1944 zStmt,
1945 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001946 );
drh633e6d52008-07-28 19:34:53 +00001947 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001948 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001949
1950#ifndef SQLITE_OMIT_AUTOINCREMENT
1951 /* Check to see if we need to create an sqlite_sequence table for
1952 ** keeping track of autoincrement keys.
1953 */
drh7d10d5a2008-08-20 16:35:10 +00001954 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001955 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001956 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001957 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001958 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001959 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1960 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001961 );
1962 }
1963 }
1964#endif
drh4794f732004-11-05 17:17:50 +00001965
1966 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001967 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001968 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001969 }
drh17e9e292003-02-01 13:53:28 +00001970
drh2958a4e2004-11-12 03:56:15 +00001971
drh17e9e292003-02-01 13:53:28 +00001972 /* Add the table to the in-memory representation of the database.
1973 */
drh8af73d42009-05-13 22:58:28 +00001974 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001975 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001976 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001977 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00001978 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00001979 if( pOld ){
1980 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001981 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001982 return;
drh17e9e292003-02-01 13:53:28 +00001983 }
drh17e9e292003-02-01 13:53:28 +00001984 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001985 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001986
1987#ifndef SQLITE_OMIT_ALTERTABLE
1988 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001989 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001990 int nName;
drh5969da42013-10-21 02:14:45 +00001991 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001992 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001993 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001994 }
drh1bd10f82008-12-10 21:19:56 +00001995 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001996 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001997 }
1998#endif
drh17e9e292003-02-01 13:53:28 +00001999 }
drh75897232000-05-29 14:26:00 +00002000}
2001
drhb7f91642004-10-31 02:22:47 +00002002#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002003/*
drha76b5df2002-02-23 02:32:10 +00002004** The parser calls this routine in order to create a new VIEW
2005*/
danielk19774adee202004-05-08 08:23:19 +00002006void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002007 Parse *pParse, /* The parsing context */
2008 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002009 Token *pName1, /* The token that holds the name of the view */
2010 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002011 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002012 int isTemp, /* TRUE for a TEMPORARY view */
2013 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002014){
drha76b5df2002-02-23 02:32:10 +00002015 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002016 int n;
drhb7916a72009-05-27 10:31:29 +00002017 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002018 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002019 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002020 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002021 int iDb;
drh17435752007-08-16 04:30:38 +00002022 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002023
drh7c3d64f2005-06-06 15:32:08 +00002024 if( pParse->nVar>0 ){
2025 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002026 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002027 return;
2028 }
drhfdd48a72006-09-11 23:45:48 +00002029 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002030 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002031 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002032 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002033 return;
2034 }
danielk1977ef2cb632004-05-29 02:37:19 +00002035 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002036 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002037 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2038 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002039 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002040 return;
2041 }
drh174b6192002-12-03 02:22:52 +00002042
drh4b59ab52002-08-24 18:24:51 +00002043 /* Make a copy of the entire SELECT statement that defines the view.
2044 ** This will force all the Expr.token.z values to be dynamically
2045 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002046 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002047 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002048 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002049 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002050 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002051 return;
2052 }
drh17435752007-08-16 04:30:38 +00002053 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002054 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002055 }
drh4b59ab52002-08-24 18:24:51 +00002056
2057 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2058 ** the end.
2059 */
drha76b5df2002-02-23 02:32:10 +00002060 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002061 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002062 sEnd.z += sEnd.n;
2063 }
2064 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002065 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002066 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002067 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002068 sEnd.z = &z[n-1];
2069 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002070
danielk19774adee202004-05-08 08:23:19 +00002071 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002072 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002073 return;
drh417be792002-03-03 18:59:40 +00002074}
drhb7f91642004-10-31 02:22:47 +00002075#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002076
danielk1977fe3fcbe22006-06-12 12:08:45 +00002077#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002078/*
2079** The Table structure pTable is really a VIEW. Fill in the names of
2080** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002081** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002082*/
danielk19774adee202004-05-08 08:23:19 +00002083int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002084 Table *pSelTab; /* A fake table from which we get the result set */
2085 Select *pSel; /* Copy of the SELECT that implements the view */
2086 int nErr = 0; /* Number of errors encountered */
2087 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002088 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002089 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002090
2091 assert( pTable );
2092
danielk1977fe3fcbe22006-06-12 12:08:45 +00002093#ifndef SQLITE_OMIT_VIRTUALTABLE
2094 if( sqlite3VtabCallConnect(pParse, pTable) ){
2095 return SQLITE_ERROR;
2096 }
drh4cbdda92006-06-14 19:00:20 +00002097 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002098#endif
2099
2100#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002101 /* A positive nCol means the columns names for this view are
2102 ** already known.
2103 */
2104 if( pTable->nCol>0 ) return 0;
2105
2106 /* A negative nCol is a special marker meaning that we are currently
2107 ** trying to compute the column names. If we enter this routine with
2108 ** a negative nCol, it means two or more views form a loop, like this:
2109 **
2110 ** CREATE VIEW one AS SELECT * FROM two;
2111 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002112 **
drh768578e2009-05-12 00:40:12 +00002113 ** Actually, the error above is now caught prior to reaching this point.
2114 ** But the following test is still important as it does come up
2115 ** in the following:
2116 **
2117 ** CREATE TABLE main.ex1(a);
2118 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2119 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002120 */
2121 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002122 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002123 return 1;
2124 }
drh85c23c62005-08-20 03:03:04 +00002125 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002126
2127 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002128 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2129 ** "*" elements in the results set of the view and will assign cursors
2130 ** to the elements of the FROM clause. But we do not want these changes
2131 ** to be permanent. So the computation is done on a copy of the SELECT
2132 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002133 */
drh9b3187e2005-01-18 14:45:47 +00002134 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002135 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002136 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002137 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002138 n = pParse->nTab;
2139 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2140 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002141 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002142#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002143 xAuth = db->xAuth;
2144 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002145 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002146 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002147#else
drh7d10d5a2008-08-20 16:35:10 +00002148 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002149#endif
drhd9da78a2009-03-24 15:08:09 +00002150 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002151 pParse->nTab = n;
2152 if( pSelTab ){
2153 assert( pTable->aCol==0 );
2154 pTable->nCol = pSelTab->nCol;
2155 pTable->aCol = pSelTab->aCol;
2156 pSelTab->nCol = 0;
2157 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002158 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002159 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002160 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002161 }else{
2162 pTable->nCol = 0;
2163 nErr++;
2164 }
drh633e6d52008-07-28 19:34:53 +00002165 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002166 } else {
drh417be792002-03-03 18:59:40 +00002167 nErr++;
2168 }
drhb7f91642004-10-31 02:22:47 +00002169#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002170 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002171}
2172#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002173
drhb7f91642004-10-31 02:22:47 +00002174#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002175/*
drh8bf8dc92003-05-17 17:35:10 +00002176** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002177*/
drh9bb575f2004-09-06 17:24:11 +00002178static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002179 HashElem *i;
drh21206082011-04-04 18:22:02 +00002180 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002181 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002182 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002183 Table *pTab = sqliteHashData(i);
2184 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002185 sqliteDeleteColumnNames(db, pTab);
2186 pTab->aCol = 0;
2187 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002188 }
2189 }
drh8bf8dc92003-05-17 17:35:10 +00002190 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002191}
drhb7f91642004-10-31 02:22:47 +00002192#else
2193# define sqliteViewResetAll(A,B)
2194#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002195
drh75897232000-05-29 14:26:00 +00002196/*
danielk1977a0bf2652004-11-04 14:30:04 +00002197** This function is called by the VDBE to adjust the internal schema
2198** used by SQLite when the btree layer moves a table root page. The
2199** root-page of a table or index in database iDb has changed from iFrom
2200** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002201**
2202** Ticket #1728: The symbol table might still contain information
2203** on tables and/or indices that are the process of being deleted.
2204** If you are unlucky, one of those deleted indices or tables might
2205** have the same rootpage number as the real table or index that is
2206** being moved. So we cannot stop searching after the first match
2207** because the first match might be for one of the deleted indices
2208** or tables and not the table/index that is actually being moved.
2209** We must continue looping until all tables and indices with
2210** rootpage==iFrom have been converted to have a rootpage of iTo
2211** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002212*/
2213#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002214void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002215 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002216 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002217 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002218
drhcdf011d2011-04-04 21:25:28 +00002219 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2220 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002221 pHash = &pDb->pSchema->tblHash;
2222 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002223 Table *pTab = sqliteHashData(pElem);
2224 if( pTab->tnum==iFrom ){
2225 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002226 }
2227 }
danielk1977da184232006-01-05 11:34:32 +00002228 pHash = &pDb->pSchema->idxHash;
2229 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002230 Index *pIdx = sqliteHashData(pElem);
2231 if( pIdx->tnum==iFrom ){
2232 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002233 }
2234 }
danielk1977a0bf2652004-11-04 14:30:04 +00002235}
2236#endif
2237
2238/*
2239** Write code to erase the table with root-page iTable from database iDb.
2240** Also write code to modify the sqlite_master table and internal schema
2241** if a root-page of another table is moved by the btree-layer whilst
2242** erasing iTable (this can happen with an auto-vacuum database).
2243*/
drh4e0cff62004-11-05 05:10:28 +00002244static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2245 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002246 int r1 = sqlite3GetTempReg(pParse);
2247 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002248 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002249#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002250 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002251 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002252 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002253 ** reflect this.
2254 **
drh0fa991b2009-03-21 16:19:26 +00002255 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002256 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2257 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002258 */
danielk197763e3e9f2004-11-05 09:19:27 +00002259 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002260 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2261 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002262#endif
drhb7654112008-01-12 12:48:07 +00002263 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002264}
2265
2266/*
2267** Write VDBE code to erase table pTab and all associated indices on disk.
2268** Code to update the sqlite_master tables and internal schema definitions
2269** in case a root-page belonging to another table is moved by the btree layer
2270** is also added (this can happen with an auto-vacuum database).
2271*/
drh4e0cff62004-11-05 05:10:28 +00002272static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002273#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002274 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002275 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2276 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002277 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002278 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002279 }
2280#else
2281 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2282 ** is not defined), then it is important to call OP_Destroy on the
2283 ** table and index root-pages in order, starting with the numerically
2284 ** largest root-page number. This guarantees that none of the root-pages
2285 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2286 ** following were coded:
2287 **
2288 ** OP_Destroy 4 0
2289 ** ...
2290 ** OP_Destroy 5 0
2291 **
2292 ** and root page 5 happened to be the largest root-page number in the
2293 ** database, then root page 5 would be moved to page 4 by the
2294 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2295 ** a free-list page.
2296 */
2297 int iTab = pTab->tnum;
2298 int iDestroyed = 0;
2299
2300 while( 1 ){
2301 Index *pIdx;
2302 int iLargest = 0;
2303
2304 if( iDestroyed==0 || iTab<iDestroyed ){
2305 iLargest = iTab;
2306 }
2307 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2308 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002309 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002310 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2311 iLargest = iIdx;
2312 }
2313 }
danielk1977da184232006-01-05 11:34:32 +00002314 if( iLargest==0 ){
2315 return;
2316 }else{
2317 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002318 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002319 destroyRootPage(pParse, iLargest, iDb);
2320 iDestroyed = iLargest;
2321 }
danielk1977a0bf2652004-11-04 14:30:04 +00002322 }
2323#endif
2324}
2325
2326/*
drh74e7c8f2011-10-21 19:06:32 +00002327** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002328** after a DROP INDEX or DROP TABLE command.
2329*/
2330static void sqlite3ClearStatTables(
2331 Parse *pParse, /* The parsing context */
2332 int iDb, /* The database number */
2333 const char *zType, /* "idx" or "tbl" */
2334 const char *zName /* Name of index or table */
2335){
drha5ae4c32011-08-07 01:31:52 +00002336 int i;
2337 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002338 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002339 char zTab[24];
2340 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2341 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002342 sqlite3NestedParse(pParse,
2343 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002344 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002345 );
2346 }
2347 }
2348}
2349
2350/*
drhfaacf172011-08-12 01:51:45 +00002351** Generate code to drop a table.
2352*/
2353void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2354 Vdbe *v;
2355 sqlite3 *db = pParse->db;
2356 Trigger *pTrigger;
2357 Db *pDb = &db->aDb[iDb];
2358
2359 v = sqlite3GetVdbe(pParse);
2360 assert( v!=0 );
2361 sqlite3BeginWriteOperation(pParse, 1, iDb);
2362
2363#ifndef SQLITE_OMIT_VIRTUALTABLE
2364 if( IsVirtual(pTab) ){
2365 sqlite3VdbeAddOp0(v, OP_VBegin);
2366 }
2367#endif
2368
2369 /* Drop all triggers associated with the table being dropped. Code
2370 ** is generated to remove entries from sqlite_master and/or
2371 ** sqlite_temp_master if required.
2372 */
2373 pTrigger = sqlite3TriggerList(pParse, pTab);
2374 while( pTrigger ){
2375 assert( pTrigger->pSchema==pTab->pSchema ||
2376 pTrigger->pSchema==db->aDb[1].pSchema );
2377 sqlite3DropTriggerPtr(pParse, pTrigger);
2378 pTrigger = pTrigger->pNext;
2379 }
2380
2381#ifndef SQLITE_OMIT_AUTOINCREMENT
2382 /* Remove any entries of the sqlite_sequence table associated with
2383 ** the table being dropped. This is done before the table is dropped
2384 ** at the btree level, in case the sqlite_sequence table needs to
2385 ** move as a result of the drop (can happen in auto-vacuum mode).
2386 */
2387 if( pTab->tabFlags & TF_Autoincrement ){
2388 sqlite3NestedParse(pParse,
2389 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2390 pDb->zName, pTab->zName
2391 );
2392 }
2393#endif
2394
2395 /* Drop all SQLITE_MASTER table and index entries that refer to the
2396 ** table. The program name loops through the master table and deletes
2397 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002398 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002399 ** created in the temp database that refers to a table in another
2400 ** database.
2401 */
2402 sqlite3NestedParse(pParse,
2403 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2404 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002405 if( !isView && !IsVirtual(pTab) ){
2406 destroyTable(pParse, pTab);
2407 }
2408
2409 /* Remove the table entry from SQLite's internal schema and modify
2410 ** the schema cookie.
2411 */
2412 if( IsVirtual(pTab) ){
2413 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2414 }
2415 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2416 sqlite3ChangeCookie(pParse, iDb);
2417 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002418}
2419
2420/*
drh75897232000-05-29 14:26:00 +00002421** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002422** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002423*/
drha0733842005-12-29 01:11:36 +00002424void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002425 Table *pTab;
drh75897232000-05-29 14:26:00 +00002426 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002427 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002428 int iDb;
drh75897232000-05-29 14:26:00 +00002429
drh8af73d42009-05-13 22:58:28 +00002430 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002431 goto exit_drop_table;
2432 }
drh8af73d42009-05-13 22:58:28 +00002433 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002434 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002435 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002436 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002437 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002438
drha0733842005-12-29 01:11:36 +00002439 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002440 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002441 goto exit_drop_table;
2442 }
danielk1977da184232006-01-05 11:34:32 +00002443 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002444 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002445
2446 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2447 ** it is initialized.
2448 */
2449 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2450 goto exit_drop_table;
2451 }
drhe5f9c642003-01-13 23:27:31 +00002452#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002453 {
2454 int code;
danielk1977da184232006-01-05 11:34:32 +00002455 const char *zTab = SCHEMA_TABLE(iDb);
2456 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002457 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002458 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002459 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002460 }
drhe5f9c642003-01-13 23:27:31 +00002461 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002462 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002463 code = SQLITE_DROP_TEMP_VIEW;
2464 }else{
2465 code = SQLITE_DROP_VIEW;
2466 }
danielk19774b2688a2006-06-20 11:01:07 +00002467#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002468 }else if( IsVirtual(pTab) ){
2469 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002470 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002471#endif
drhe5f9c642003-01-13 23:27:31 +00002472 }else{
danielk197753c0f742005-03-29 03:10:59 +00002473 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002474 code = SQLITE_DROP_TEMP_TABLE;
2475 }else{
2476 code = SQLITE_DROP_TABLE;
2477 }
2478 }
danielk1977f1a381e2006-06-16 08:01:02 +00002479 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002480 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002481 }
danielk1977a8858102004-05-28 12:11:21 +00002482 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2483 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002484 }
drhe5f9c642003-01-13 23:27:31 +00002485 }
2486#endif
drh08ccfaa2011-10-07 23:52:25 +00002487 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2488 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002489 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002490 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002491 }
danielk1977576ec6b2005-01-21 11:55:25 +00002492
2493#ifndef SQLITE_OMIT_VIEW
2494 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2495 ** on a table.
2496 */
danielk1977a8858102004-05-28 12:11:21 +00002497 if( isView && pTab->pSelect==0 ){
2498 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2499 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002500 }
danielk1977a8858102004-05-28 12:11:21 +00002501 if( !isView && pTab->pSelect ){
2502 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2503 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002504 }
danielk1977576ec6b2005-01-21 11:55:25 +00002505#endif
drh75897232000-05-29 14:26:00 +00002506
drh1ccde152000-06-17 13:12:39 +00002507 /* Generate code to remove the table from the master table
2508 ** on disk.
2509 */
danielk19774adee202004-05-08 08:23:19 +00002510 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002511 if( v ){
drh77658e22007-12-04 16:54:52 +00002512 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002513 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002514 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002515 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002516 }
danielk1977a8858102004-05-28 12:11:21 +00002517
2518exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002519 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002520}
2521
2522/*
drhc2eef3b2002-08-31 18:53:06 +00002523** This routine is called to create a new foreign key on the table
2524** currently under construction. pFromCol determines which columns
2525** in the current table point to the foreign key. If pFromCol==0 then
2526** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002527** the table referred to (a.k.a the "parent" table). pToCol is a list
2528** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002529** information about the conflict resolution algorithms specified
2530** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2531**
2532** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002533** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002534**
2535** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002536** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002537*/
danielk19774adee202004-05-08 08:23:19 +00002538void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002539 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002540 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002541 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002542 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002543 int flags /* Conflict resolution algorithms. */
2544){
danielk197718576932008-08-06 13:47:40 +00002545 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002546#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002547 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002548 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002549 Table *p = pParse->pNewTable;
2550 int nByte;
2551 int i;
2552 int nCol;
2553 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002554
2555 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002556 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002557 if( pFromCol==0 ){
2558 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002559 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002560 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002561 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002562 " should reference only one column of table %T",
2563 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002564 goto fk_end;
2565 }
2566 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002567 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002568 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002569 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002570 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002571 goto fk_end;
2572 }else{
danielk19770202b292004-06-09 09:55:16 +00002573 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002574 }
drhe61922a2009-05-02 13:29:37 +00002575 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002576 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002577 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002578 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002579 }
2580 }
drh633e6d52008-07-28 19:34:53 +00002581 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002582 if( pFKey==0 ){
2583 goto fk_end;
2584 }
drhc2eef3b2002-08-31 18:53:06 +00002585 pFKey->pFrom = p;
2586 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002587 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002588 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002589 memcpy(z, pTo->z, pTo->n);
2590 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002591 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002592 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002593 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002594 if( pFromCol==0 ){
2595 pFKey->aCol[0].iFrom = p->nCol-1;
2596 }else{
2597 for(i=0; i<nCol; i++){
2598 int j;
2599 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002600 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002601 pFKey->aCol[i].iFrom = j;
2602 break;
2603 }
2604 }
2605 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002606 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002607 "unknown column \"%s\" in foreign key definition",
2608 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002609 goto fk_end;
2610 }
2611 }
2612 }
2613 if( pToCol ){
2614 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002615 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002616 pFKey->aCol[i].zCol = z;
2617 memcpy(z, pToCol->a[i].zName, n);
2618 z[n] = 0;
2619 z += n+1;
2620 }
2621 }
2622 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002623 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2624 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002625
drh21206082011-04-04 18:22:02 +00002626 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002627 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002628 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002629 );
danf59c5ca2009-09-22 16:55:38 +00002630 if( pNextTo==pFKey ){
2631 db->mallocFailed = 1;
2632 goto fk_end;
2633 }
dan1da40a32009-09-19 17:00:31 +00002634 if( pNextTo ){
2635 assert( pNextTo->pPrevTo==0 );
2636 pFKey->pNextTo = pNextTo;
2637 pNextTo->pPrevTo = pFKey;
2638 }
2639
drhc2eef3b2002-08-31 18:53:06 +00002640 /* Link the foreign key to the table as the last step.
2641 */
2642 p->pFKey = pFKey;
2643 pFKey = 0;
2644
2645fk_end:
drh633e6d52008-07-28 19:34:53 +00002646 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002647#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002648 sqlite3ExprListDelete(db, pFromCol);
2649 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002650}
2651
2652/*
2653** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2654** clause is seen as part of a foreign key definition. The isDeferred
2655** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2656** The behavior of the most recently created foreign key is adjusted
2657** accordingly.
2658*/
danielk19774adee202004-05-08 08:23:19 +00002659void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002660#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002661 Table *pTab;
2662 FKey *pFKey;
2663 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002664 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002665 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002666#endif
drhc2eef3b2002-08-31 18:53:06 +00002667}
2668
2669/*
drh063336a2004-11-05 20:58:39 +00002670** Generate code that will erase and refill index *pIdx. This is
2671** used to initialize a newly created index or to recompute the
2672** content of an index in response to a REINDEX command.
2673**
2674** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002675** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002676** root page number of the index. If memRootPage is negative, then
2677** the index already exists and must be cleared before being refilled and
2678** the root page number of the index is taken from pIndex->tnum.
2679*/
2680static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2681 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002682 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2683 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002684 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002685 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002686 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002687 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002688 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002689 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002690 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002691 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002692 sqlite3 *db = pParse->db; /* The database connection */
2693 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002694
danielk19771d54df82004-11-23 15:41:16 +00002695#ifndef SQLITE_OMIT_AUTHORIZATION
2696 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002697 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002698 return;
2699 }
2700#endif
2701
danielk1977c00da102006-01-07 13:21:04 +00002702 /* Require a write-lock on the table to perform this operation */
2703 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2704
drh063336a2004-11-05 20:58:39 +00002705 v = sqlite3GetVdbe(pParse);
2706 if( v==0 ) return;
2707 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002708 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002709 }else{
2710 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002711 }
drh2ec2fb22013-11-06 19:59:23 +00002712 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002713
dan689ab892011-08-12 15:02:00 +00002714 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002715 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002716 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002717 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002718
2719 /* Open the table. Loop through all rows of the table, inserting index
2720 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002721 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002722 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002723 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002724
drh1c2c0b72014-01-04 19:27:05 +00002725 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002726 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002727 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002728 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002729 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002730 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2731 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002732 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002733 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2734
drh688852a2014-02-17 22:40:43 +00002735 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002736 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002737 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002738 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2739 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2740 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002741 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002742 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002743 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002744 }else{
2745 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002746 }
drhca892a72011-09-03 00:17:51 +00002747 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2748 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2749 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002750 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002751 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002752 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002753
drh66a51672008-01-03 00:01:23 +00002754 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2755 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002756 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002757}
2758
2759/*
drh77e57df2013-10-22 14:28:02 +00002760** Allocate heap space to hold an Index object with nCol columns.
2761**
2762** Increase the allocation size to provide an extra nExtra bytes
2763** of 8-byte aligned space after the Index object and return a
2764** pointer to this extra space in *ppExtra.
2765*/
2766Index *sqlite3AllocateIndexObject(
2767 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002768 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002769 int nExtra, /* Number of bytes of extra space to alloc */
2770 char **ppExtra /* Pointer to the "extra" space */
2771){
2772 Index *p; /* Allocated index object */
2773 int nByte; /* Bytes of space for Index object + arrays */
2774
2775 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2776 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002777 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002778 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002779 sizeof(u8)*nCol); /* Index.aSortOrder */
2780 p = sqlite3DbMallocZero(db, nByte + nExtra);
2781 if( p ){
2782 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002783 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2784 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2785 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002786 p->aSortOrder = (u8*)pExtra;
2787 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002788 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002789 *ppExtra = ((char*)p) + nByte;
2790 }
2791 return p;
2792}
2793
2794/*
drh23bf66d2004-12-14 03:34:34 +00002795** Create a new index for an SQL table. pName1.pName2 is the name of the index
2796** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002797** be NULL for a primary key or an index that is created to satisfy a
2798** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002799** as the table to be indexed. pParse->pNewTable is a table that is
2800** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002801**
drh382c0242001-10-06 16:33:02 +00002802** pList is a list of columns to be indexed. pList will be NULL if this
2803** is a primary key or unique-constraint on the most recent column added
2804** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002805**
2806** If the index is created successfully, return a pointer to the new Index
2807** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002808** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002809*/
dan1da40a32009-09-19 17:00:31 +00002810Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002811 Parse *pParse, /* All information about this parse */
2812 Token *pName1, /* First part of index name. May be NULL */
2813 Token *pName2, /* Second part of index name. May be NULL */
2814 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002815 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002816 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002817 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002818 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002819 int sortOrder, /* Sort order of primary key when pList==NULL */
2820 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002821){
dan1da40a32009-09-19 17:00:31 +00002822 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002823 Table *pTab = 0; /* Table to be indexed */
2824 Index *pIndex = 0; /* The index to be created */
2825 char *zName = 0; /* Name of the index */
2826 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002827 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002828 DbFixer sFix; /* For assigning database names to pTable */
2829 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002830 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002831 Db *pDb; /* The specific table containing the indexed database */
2832 int iDb; /* Index of the database that is being written */
2833 Token *pName = 0; /* Unqualified name of the index to create */
2834 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002835 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002836 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002837 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002838 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002839 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002840
drh8af73d42009-05-13 22:58:28 +00002841 assert( pParse->nErr==0 ); /* Never called with prior errors */
2842 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002843 goto exit_create_index;
2844 }
2845 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002846 goto exit_create_index;
2847 }
drhdaffd0e2001-04-11 14:28:42 +00002848
drh75897232000-05-29 14:26:00 +00002849 /*
2850 ** Find the table that is to be indexed. Return early if not found.
2851 */
danielk1977cbb18d22004-05-28 11:37:27 +00002852 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002853
2854 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002855 ** to search for the table. 'Fix' the table name to this db
2856 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002857 */
2858 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002859 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002860 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002861 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002862
danielk197753c0f742005-03-29 03:10:59 +00002863#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002864 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002865 ** is a temp table. If so, set the database to 1. Do not do this
2866 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002867 */
danielk1977fe910332007-12-02 11:46:34 +00002868 if( !db->init.busy ){
2869 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002870 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002871 iDb = 1;
2872 }
danielk1977ef2cb632004-05-29 02:37:19 +00002873 }
danielk197753c0f742005-03-29 03:10:59 +00002874#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002875
drhd100f692013-10-03 15:39:44 +00002876 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2877 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002878 /* Because the parser constructs pTblName from a single identifier,
2879 ** sqlite3FixSrcList can never fail. */
2880 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002881 }
dan41fb5cd2012-10-04 19:33:00 +00002882 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002883 assert( db->mallocFailed==0 || pTab==0 );
2884 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002885 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2886 sqlite3ErrorMsg(pParse,
2887 "cannot create a TEMP index on non-TEMP table \"%s\"",
2888 pTab->zName);
2889 goto exit_create_index;
2890 }
drh44156282013-10-23 22:23:03 +00002891 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002892 }else{
drhe3c41372001-09-17 20:25:58 +00002893 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002894 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002895 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002896 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002897 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002898 }
drhfdd6e852005-12-16 01:06:16 +00002899 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002900
drhd3001712009-05-12 17:46:53 +00002901 assert( pTab!=0 );
2902 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002903 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002904 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002905#if SQLITE_USER_AUTHENTICATION
2906 && sqlite3UserAuthTable(pTab->zName)==0
2907#endif
drh503a6862013-03-01 01:07:17 +00002908 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002909 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002910 goto exit_create_index;
2911 }
danielk1977576ec6b2005-01-21 11:55:25 +00002912#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002913 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002914 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002915 goto exit_create_index;
2916 }
danielk1977576ec6b2005-01-21 11:55:25 +00002917#endif
danielk19775ee9d692006-06-21 12:36:25 +00002918#ifndef SQLITE_OMIT_VIRTUALTABLE
2919 if( IsVirtual(pTab) ){
2920 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2921 goto exit_create_index;
2922 }
2923#endif
drh75897232000-05-29 14:26:00 +00002924
2925 /*
2926 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002927 ** index or table with the same name.
2928 **
2929 ** Exception: If we are reading the names of permanent indices from the
2930 ** sqlite_master table (because some other process changed the schema) and
2931 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002932 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002933 **
2934 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002935 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2936 ** own name.
drh75897232000-05-29 14:26:00 +00002937 */
danielk1977d8123362004-06-12 09:25:12 +00002938 if( pName ){
drh17435752007-08-16 04:30:38 +00002939 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002940 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002941 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002942 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002943 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002944 }
danielk1977d8123362004-06-12 09:25:12 +00002945 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002946 if( sqlite3FindTable(db, zName, 0)!=0 ){
2947 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2948 goto exit_create_index;
2949 }
2950 }
danielk197759a33f92007-03-17 10:26:59 +00002951 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2952 if( !ifNotExist ){
2953 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002954 }else{
2955 assert( !db->init.busy );
2956 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002957 }
danielk197759a33f92007-03-17 10:26:59 +00002958 goto exit_create_index;
2959 }
danielk1977a21c6b62005-01-24 10:25:59 +00002960 }else{
drhadbca9c2001-09-27 15:11:53 +00002961 int n;
2962 Index *pLoop;
2963 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002964 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002965 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002966 goto exit_create_index;
2967 }
drh75897232000-05-29 14:26:00 +00002968 }
2969
drhe5f9c642003-01-13 23:27:31 +00002970 /* Check for authorization to create an index.
2971 */
2972#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002973 {
drhfdd6e852005-12-16 01:06:16 +00002974 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002975 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002976 goto exit_create_index;
2977 }
2978 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002979 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002980 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002981 goto exit_create_index;
2982 }
drhe5f9c642003-01-13 23:27:31 +00002983 }
2984#endif
2985
drh75897232000-05-29 14:26:00 +00002986 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002987 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002988 ** So create a fake list to simulate this.
2989 */
2990 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002991 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002992 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002993 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2994 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002995 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002996 }
2997
danielk1977b3bf5562006-01-10 17:58:23 +00002998 /* Figure out how many bytes of space are required to store explicitly
2999 ** specified collation sequence names.
3000 */
3001 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003002 Expr *pExpr = pList->a[i].pExpr;
3003 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00003004 assert( pExpr->op==TK_COLLATE );
3005 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003006 }
3007 }
3008
drh75897232000-05-29 14:26:00 +00003009 /*
3010 ** Allocate the index structure.
3011 */
drhea678832008-12-10 19:26:22 +00003012 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003013 nExtraCol = pPk ? pPk->nKeyCol : 1;
3014 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003015 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003016 if( db->mallocFailed ){
3017 goto exit_create_index;
3018 }
dancfc9df72014-04-25 15:01:01 +00003019 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003020 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003021 pIndex->zName = zExtra;
3022 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003023 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003024 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003025 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003026 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003027 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003028 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003029 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003030 if( pPIWhere ){
3031 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3032 pIndex->pPartIdxWhere = pPIWhere;
3033 pPIWhere = 0;
3034 }
drh21206082011-04-04 18:22:02 +00003035 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003036
drhfdd6e852005-12-16 01:06:16 +00003037 /* Check to see if we should honor DESC requests on index columns
3038 */
danielk1977da184232006-01-05 11:34:32 +00003039 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003040 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003041 }else{
3042 sortOrderMask = 0; /* Ignore DESC */
3043 }
3044
drh1ccde152000-06-17 13:12:39 +00003045 /* Scan the names of the columns of the table to be indexed and
3046 ** load the column indices into the Index structure. Report an error
3047 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003048 **
3049 ** TODO: Add a test to make sure that the same column is not named
3050 ** more than once within the same index. Only the first instance of
3051 ** the column will ever be used by the optimizer. Note that using the
3052 ** same column more than once cannot be an error because that would
3053 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003054 */
drhfdd6e852005-12-16 01:06:16 +00003055 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3056 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003057 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003058 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003059
drhfdd6e852005-12-16 01:06:16 +00003060 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3061 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003062 }
3063 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003064 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003065 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003066 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003067 goto exit_create_index;
3068 }
drhbf20a352014-04-04 22:44:59 +00003069 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003070 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003071 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003072 int nColl;
dan911ce412013-05-15 15:16:50 +00003073 assert( pListItem->pExpr->op==TK_COLLATE );
3074 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003075 nColl = sqlite3Strlen30(zColl) + 1;
3076 assert( nExtra>=nColl );
3077 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003078 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003079 zExtra += nColl;
3080 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003081 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003082 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003083 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003084 }
drhb7f24de2009-05-13 17:35:23 +00003085 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003086 goto exit_create_index;
3087 }
danielk1977b3bf5562006-01-10 17:58:23 +00003088 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003089 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003090 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003091 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003092 }
drh44156282013-10-23 22:23:03 +00003093 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003094 for(j=0; j<pPk->nKeyCol; j++){
3095 int x = pPk->aiColumn[j];
3096 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3097 pIndex->nColumn--;
3098 }else{
3099 pIndex->aiColumn[i] = x;
3100 pIndex->azColl[i] = pPk->azColl[j];
3101 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3102 i++;
3103 }
drh44156282013-10-23 22:23:03 +00003104 }
drh7913e412013-11-01 20:30:36 +00003105 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003106 }else{
3107 pIndex->aiColumn[i] = -1;
3108 pIndex->azColl[i] = "BINARY";
3109 }
drh51147ba2005-07-23 22:59:55 +00003110 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003111 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003112
danielk1977d8123362004-06-12 09:25:12 +00003113 if( pTab==pParse->pNewTable ){
3114 /* This routine has been called to create an automatic index as a
3115 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3116 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3117 ** i.e. one of:
3118 **
3119 ** CREATE TABLE t(x PRIMARY KEY, y);
3120 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3121 **
3122 ** Either way, check to see if the table already has such an index. If
3123 ** so, don't bother creating this one. This only applies to
3124 ** automatically created indices. Users can do as they wish with
3125 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003126 **
3127 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3128 ** (and thus suppressing the second one) even if they have different
3129 ** sort orders.
3130 **
3131 ** If there are different collating sequences or if the columns of
3132 ** the constraint occur in different orders, then the constraints are
3133 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003134 */
3135 Index *pIdx;
3136 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3137 int k;
drh5f1d1d92014-07-31 22:59:04 +00003138 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003139 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003140 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003141
drhbbbdc832013-10-22 18:01:40 +00003142 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3143 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003144 const char *z1;
3145 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003146 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003147 z1 = pIdx->azColl[k];
3148 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003149 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003150 }
drhbbbdc832013-10-22 18:01:40 +00003151 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003152 if( pIdx->onError!=pIndex->onError ){
3153 /* This constraint creates the same index as a previous
3154 ** constraint specified somewhere in the CREATE TABLE statement.
3155 ** However the ON CONFLICT clauses are different. If both this
3156 ** constraint and the previous equivalent constraint have explicit
3157 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003158 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003159 */
3160 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3161 sqlite3ErrorMsg(pParse,
3162 "conflicting ON CONFLICT clauses specified", 0);
3163 }
3164 if( pIdx->onError==OE_Default ){
3165 pIdx->onError = pIndex->onError;
3166 }
3167 }
danielk1977d8123362004-06-12 09:25:12 +00003168 goto exit_create_index;
3169 }
3170 }
3171 }
3172
drh75897232000-05-29 14:26:00 +00003173 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003174 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003175 */
drh234c39d2004-07-24 03:30:47 +00003176 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003177 Index *p;
drh21206082011-04-04 18:22:02 +00003178 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003179 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003180 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003181 if( p ){
3182 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003183 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003184 goto exit_create_index;
3185 }
drh5e00f6c2001-09-13 13:46:56 +00003186 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003187 if( pTblName!=0 ){
3188 pIndex->tnum = db->init.newTnum;
3189 }
drhd78eeee2001-09-13 16:18:53 +00003190 }
3191
drh58383402013-11-04 17:00:50 +00003192 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3193 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3194 ** emit code to allocate the index rootpage on disk and make an entry for
3195 ** the index in the sqlite_master table and populate the index with
3196 ** content. But, do not do this if we are simply reading the sqlite_master
3197 ** table to parse the schema, or if this index is the PRIMARY KEY index
3198 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003199 **
drh58383402013-11-04 17:00:50 +00003200 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3201 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003202 ** has just been created, it contains no data and the index initialization
3203 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003204 */
drh58383402013-11-04 17:00:50 +00003205 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003206 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003207 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003208 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003209
danielk19774adee202004-05-08 08:23:19 +00003210 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003211 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003212
drhfdd6e852005-12-16 01:06:16 +00003213
drh063336a2004-11-05 20:58:39 +00003214 /* Create the rootpage for the index
3215 */
drhaee128d2005-02-14 20:48:18 +00003216 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003217 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003218
3219 /* Gather the complete text of the CREATE INDEX statement into
3220 ** the zStmt variable
3221 */
drhd3001712009-05-12 17:46:53 +00003222 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003223 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003224 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003225 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003226 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003227 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003228 }else{
3229 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003230 /* zStmt = sqlite3MPrintf(""); */
3231 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003232 }
drh063336a2004-11-05 20:58:39 +00003233
3234 /* Add an entry in sqlite_master for this index
3235 */
3236 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003237 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003238 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3239 pIndex->zName,
3240 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003241 iMem,
drh063336a2004-11-05 20:58:39 +00003242 zStmt
3243 );
drh633e6d52008-07-28 19:34:53 +00003244 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003245
danielk1977a21c6b62005-01-24 10:25:59 +00003246 /* Fill the index with data and reparse the schema. Code an OP_Expire
3247 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003248 */
danielk1977cbb18d22004-05-28 11:37:27 +00003249 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003250 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003251 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003252 sqlite3VdbeAddParseSchemaOp(v, iDb,
3253 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003254 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003255 }
drh75897232000-05-29 14:26:00 +00003256 }
3257
danielk1977d8123362004-06-12 09:25:12 +00003258 /* When adding an index to the list of indices for a table, make
3259 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003260 ** OE_Ignore. This is necessary for the correct constraint check
3261 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3262 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003263 */
drh234c39d2004-07-24 03:30:47 +00003264 if( db->init.busy || pTblName==0 ){
3265 if( onError!=OE_Replace || pTab->pIndex==0
3266 || pTab->pIndex->onError==OE_Replace){
3267 pIndex->pNext = pTab->pIndex;
3268 pTab->pIndex = pIndex;
3269 }else{
3270 Index *pOther = pTab->pIndex;
3271 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3272 pOther = pOther->pNext;
3273 }
3274 pIndex->pNext = pOther->pNext;
3275 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003276 }
dan1da40a32009-09-19 17:00:31 +00003277 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003278 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003279 }
danielk1977d8123362004-06-12 09:25:12 +00003280
drh75897232000-05-29 14:26:00 +00003281 /* Clean up before exiting */
3282exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003283 if( pIndex ) freeIndex(db, pIndex);
3284 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003285 sqlite3ExprListDelete(db, pList);
3286 sqlite3SrcListDelete(db, pTblName);
3287 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003288 return pRet;
drh75897232000-05-29 14:26:00 +00003289}
3290
3291/*
drh51147ba2005-07-23 22:59:55 +00003292** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003293** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003294**
peter.d.reid60ec9142014-09-06 16:39:46 +00003295** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003296** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3297** number of rows in the table that match any particular value of the
3298** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003299** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003300** of the index. And so forth. It must always be the case that
3301*
3302** aiRowEst[N]<=aiRowEst[N-1]
3303** aiRowEst[N]>=1
3304**
3305** Apart from that, we have little to go on besides intuition as to
3306** how aiRowEst[] should be initialized. The numbers generated here
3307** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003308*/
3309void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003310 /* 10, 9, 8, 7, 6 */
3311 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003312 LogEst *a = pIdx->aiRowLogEst;
3313 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003314 int i;
dancfc9df72014-04-25 15:01:01 +00003315
dan264d2b92014-04-29 19:01:57 +00003316 /* Set the first entry (number of rows in the index) to the estimated
3317 ** number of rows in the table. Or 10, if the estimated number of rows
3318 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003319 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003320 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3321
3322 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3323 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003324 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003325 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3326 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003327 }
dan264d2b92014-04-29 19:01:57 +00003328
3329 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003330 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003331}
3332
3333/*
drh74e24cd2002-01-09 03:19:59 +00003334** This routine will drop an existing named index. This routine
3335** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003336*/
drh4d91a702006-01-04 15:54:36 +00003337void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003338 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003339 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003340 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003341 int iDb;
drh75897232000-05-29 14:26:00 +00003342
drh8af73d42009-05-13 22:58:28 +00003343 assert( pParse->nErr==0 ); /* Never called with prior errors */
3344 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003345 goto exit_drop_index;
3346 }
drhd24cc422003-03-27 12:51:24 +00003347 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003348 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3349 goto exit_drop_index;
3350 }
danielk19774adee202004-05-08 08:23:19 +00003351 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003352 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003353 if( !ifExists ){
3354 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003355 }else{
3356 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003357 }
drha6ecd332004-06-10 00:29:09 +00003358 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003359 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003360 }
drh48dd1d82014-05-27 18:18:58 +00003361 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003362 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003363 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003364 goto exit_drop_index;
3365 }
danielk1977da184232006-01-05 11:34:32 +00003366 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003367#ifndef SQLITE_OMIT_AUTHORIZATION
3368 {
3369 int code = SQLITE_DROP_INDEX;
3370 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003371 const char *zDb = db->aDb[iDb].zName;
3372 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003373 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003374 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003375 }
danielk1977da184232006-01-05 11:34:32 +00003376 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003377 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003378 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003379 }
drhed6c8672003-01-12 18:02:16 +00003380 }
drhe5f9c642003-01-13 23:27:31 +00003381#endif
drh75897232000-05-29 14:26:00 +00003382
3383 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003384 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003385 if( v ){
drh77658e22007-12-04 16:54:52 +00003386 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003387 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003388 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003389 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003390 );
drha5ae4c32011-08-07 01:31:52 +00003391 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003392 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003393 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003394 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003395 }
3396
drhd24cc422003-03-27 12:51:24 +00003397exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003398 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003399}
3400
3401/*
dan9ace1122012-03-29 07:51:45 +00003402** pArray is a pointer to an array of objects. Each object in the
3403** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3404** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003405**
dan9ace1122012-03-29 07:51:45 +00003406** When this function is called, *pnEntry contains the current size of
3407** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3408** in total).
drh13449892005-09-07 21:22:45 +00003409**
dan9ace1122012-03-29 07:51:45 +00003410** If the realloc() is successful (i.e. if no OOM condition occurs), the
3411** space allocated for the new object is zeroed, *pnEntry updated to
3412** reflect the new size of the array and a pointer to the new allocation
3413** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003414**
dan9ace1122012-03-29 07:51:45 +00003415** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3416** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003417*/
drhcf643722007-03-27 13:36:37 +00003418void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003419 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003420 void *pArray, /* Array of objects. Might be reallocated */
3421 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003422 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003423 int *pIdx /* Write the index of a new slot here */
3424){
3425 char *z;
drh6c535152012-02-02 03:38:30 +00003426 int n = *pnEntry;
3427 if( (n & (n-1))==0 ){
3428 int sz = (n==0) ? 1 : 2*n;
3429 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003430 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003431 *pIdx = -1;
3432 return pArray;
drh13449892005-09-07 21:22:45 +00003433 }
drhcf643722007-03-27 13:36:37 +00003434 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003435 }
drhcf643722007-03-27 13:36:37 +00003436 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003437 memset(&z[n * szEntry], 0, szEntry);
3438 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003439 ++*pnEntry;
3440 return pArray;
drh13449892005-09-07 21:22:45 +00003441}
3442
3443/*
drh75897232000-05-29 14:26:00 +00003444** Append a new element to the given IdList. Create a new IdList if
3445** need be.
drhdaffd0e2001-04-11 14:28:42 +00003446**
3447** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003448*/
drh17435752007-08-16 04:30:38 +00003449IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003450 int i;
drh75897232000-05-29 14:26:00 +00003451 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003452 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003453 if( pList==0 ) return 0;
3454 }
drhcf643722007-03-27 13:36:37 +00003455 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003456 db,
drhcf643722007-03-27 13:36:37 +00003457 pList->a,
3458 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003459 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003460 &i
3461 );
drh13449892005-09-07 21:22:45 +00003462 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003463 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003464 return 0;
drh75897232000-05-29 14:26:00 +00003465 }
drh17435752007-08-16 04:30:38 +00003466 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003467 return pList;
3468}
3469
3470/*
drhfe05af82005-07-21 03:14:59 +00003471** Delete an IdList.
3472*/
drh633e6d52008-07-28 19:34:53 +00003473void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003474 int i;
3475 if( pList==0 ) return;
3476 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003477 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003478 }
drh633e6d52008-07-28 19:34:53 +00003479 sqlite3DbFree(db, pList->a);
3480 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003481}
3482
3483/*
3484** Return the index in pList of the identifier named zId. Return -1
3485** if not found.
3486*/
3487int sqlite3IdListIndex(IdList *pList, const char *zName){
3488 int i;
3489 if( pList==0 ) return -1;
3490 for(i=0; i<pList->nId; i++){
3491 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3492 }
3493 return -1;
3494}
3495
3496/*
drha78c22c2008-11-11 18:28:58 +00003497** Expand the space allocated for the given SrcList object by
3498** creating nExtra new slots beginning at iStart. iStart is zero based.
3499** New slots are zeroed.
3500**
3501** For example, suppose a SrcList initially contains two entries: A,B.
3502** To append 3 new entries onto the end, do this:
3503**
3504** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3505**
3506** After the call above it would contain: A, B, nil, nil, nil.
3507** If the iStart argument had been 1 instead of 2, then the result
3508** would have been: A, nil, nil, nil, B. To prepend the new slots,
3509** the iStart value would be 0. The result then would
3510** be: nil, nil, nil, A, B.
3511**
3512** If a memory allocation fails the SrcList is unchanged. The
3513** db->mallocFailed flag will be set to true.
3514*/
3515SrcList *sqlite3SrcListEnlarge(
3516 sqlite3 *db, /* Database connection to notify of OOM errors */
3517 SrcList *pSrc, /* The SrcList to be enlarged */
3518 int nExtra, /* Number of new slots to add to pSrc->a[] */
3519 int iStart /* Index in pSrc->a[] of first new slot */
3520){
3521 int i;
3522
3523 /* Sanity checking on calling parameters */
3524 assert( iStart>=0 );
3525 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003526 assert( pSrc!=0 );
3527 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003528
3529 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003530 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003531 SrcList *pNew;
3532 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003533 int nGot;
drha78c22c2008-11-11 18:28:58 +00003534 pNew = sqlite3DbRealloc(db, pSrc,
3535 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3536 if( pNew==0 ){
3537 assert( db->mallocFailed );
3538 return pSrc;
3539 }
3540 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003541 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003542 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003543 }
3544
3545 /* Move existing slots that come after the newly inserted slots
3546 ** out of the way */
3547 for(i=pSrc->nSrc-1; i>=iStart; i--){
3548 pSrc->a[i+nExtra] = pSrc->a[i];
3549 }
drh6d1626e2014-03-05 15:52:43 +00003550 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003551
3552 /* Zero the newly allocated slots */
3553 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3554 for(i=iStart; i<iStart+nExtra; i++){
3555 pSrc->a[i].iCursor = -1;
3556 }
3557
3558 /* Return a pointer to the enlarged SrcList */
3559 return pSrc;
3560}
3561
3562
3563/*
drhad3cab52002-05-24 02:04:32 +00003564** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003565** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003566**
drha78c22c2008-11-11 18:28:58 +00003567** A SrcList is returned, or NULL if there is an OOM error. The returned
3568** SrcList might be the same as the SrcList that was input or it might be
3569** a new one. If an OOM error does occurs, then the prior value of pList
3570** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003571**
3572** If pDatabase is not null, it means that the table has an optional
3573** database name prefix. Like this: "database.table". The pDatabase
3574** points to the table name and the pTable points to the database name.
3575** The SrcList.a[].zName field is filled with the table name which might
3576** come from pTable (if pDatabase is NULL) or from pDatabase.
3577** SrcList.a[].zDatabase is filled with the database name from pTable,
3578** or with NULL if no database is specified.
3579**
3580** In other words, if call like this:
3581**
drh17435752007-08-16 04:30:38 +00003582** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003583**
3584** Then B is a table name and the database name is unspecified. If called
3585** like this:
3586**
drh17435752007-08-16 04:30:38 +00003587** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003588**
drhd3001712009-05-12 17:46:53 +00003589** Then C is the table name and B is the database name. If C is defined
3590** then so is B. In other words, we never have a case where:
3591**
3592** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003593**
3594** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3595** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003596*/
drh17435752007-08-16 04:30:38 +00003597SrcList *sqlite3SrcListAppend(
3598 sqlite3 *db, /* Connection to notify of malloc failures */
3599 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3600 Token *pTable, /* Table to append */
3601 Token *pDatabase /* Database of the table */
3602){
drha99db3b2004-06-19 14:49:12 +00003603 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003604 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003605 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003606 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003607 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003608 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003609 }
drha78c22c2008-11-11 18:28:58 +00003610 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3611 if( db->mallocFailed ){
3612 sqlite3SrcListDelete(db, pList);
3613 return 0;
drhad3cab52002-05-24 02:04:32 +00003614 }
drha78c22c2008-11-11 18:28:58 +00003615 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003616 if( pDatabase && pDatabase->z==0 ){
3617 pDatabase = 0;
3618 }
drhd3001712009-05-12 17:46:53 +00003619 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003620 Token *pTemp = pDatabase;
3621 pDatabase = pTable;
3622 pTable = pTemp;
3623 }
drh17435752007-08-16 04:30:38 +00003624 pItem->zName = sqlite3NameFromToken(db, pTable);
3625 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003626 return pList;
3627}
3628
3629/*
drhdfe88ec2008-11-03 20:55:06 +00003630** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003631*/
danielk19774adee202004-05-08 08:23:19 +00003632void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003633 int i;
drh9b3187e2005-01-18 14:45:47 +00003634 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003635 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003636 if( pList ){
3637 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3638 if( pItem->iCursor>=0 ) break;
3639 pItem->iCursor = pParse->nTab++;
3640 if( pItem->pSelect ){
3641 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3642 }
drh63eb5f22003-04-29 16:20:44 +00003643 }
3644 }
3645}
3646
3647/*
drhad3cab52002-05-24 02:04:32 +00003648** Delete an entire SrcList including all its substructure.
3649*/
drh633e6d52008-07-28 19:34:53 +00003650void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003651 int i;
drhbe5c89a2004-07-26 00:31:09 +00003652 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003653 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003654 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003655 sqlite3DbFree(db, pItem->zDatabase);
3656 sqlite3DbFree(db, pItem->zName);
3657 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003658 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003659 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003660 sqlite3SelectDelete(db, pItem->pSelect);
3661 sqlite3ExprDelete(db, pItem->pOn);
3662 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003663 }
drh633e6d52008-07-28 19:34:53 +00003664 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003665}
3666
drh982cef72000-05-30 16:27:03 +00003667/*
drh61dfc312006-12-16 16:25:15 +00003668** This routine is called by the parser to add a new term to the
3669** end of a growing FROM clause. The "p" parameter is the part of
3670** the FROM clause that has already been constructed. "p" is NULL
3671** if this is the first term of the FROM clause. pTable and pDatabase
3672** are the name of the table and database named in the FROM clause term.
3673** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003674** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003675** alias token. If the term is a subquery, then pSubquery is the
3676** SELECT statement that the subquery encodes. The pTable and
3677** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3678** parameters are the content of the ON and USING clauses.
3679**
3680** Return a new SrcList which encodes is the FROM with the new
3681** term added.
3682*/
3683SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003684 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003685 SrcList *p, /* The left part of the FROM clause already seen */
3686 Token *pTable, /* Name of the table to add to the FROM clause */
3687 Token *pDatabase, /* Name of the database containing pTable */
3688 Token *pAlias, /* The right-hand side of the AS subexpression */
3689 Select *pSubquery, /* A subquery used in place of a table name */
3690 Expr *pOn, /* The ON clause of a join */
3691 IdList *pUsing /* The USING clause of a join */
3692){
3693 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003694 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003695 if( !p && (pOn || pUsing) ){
3696 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3697 (pOn ? "ON" : "USING")
3698 );
3699 goto append_from_error;
3700 }
drh17435752007-08-16 04:30:38 +00003701 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003702 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003703 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003704 }
3705 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003706 assert( pAlias!=0 );
3707 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003708 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003709 }
3710 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003711 pItem->pOn = pOn;
3712 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003713 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003714
3715 append_from_error:
3716 assert( p==0 );
3717 sqlite3ExprDelete(db, pOn);
3718 sqlite3IdListDelete(db, pUsing);
3719 sqlite3SelectDelete(db, pSubquery);
3720 return 0;
drh61dfc312006-12-16 16:25:15 +00003721}
3722
3723/*
danielk1977b1c685b2008-10-06 16:18:39 +00003724** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3725** element of the source-list passed as the second argument.
3726*/
3727void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003728 assert( pIndexedBy!=0 );
3729 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003730 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3731 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3732 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3733 /* A "NOT INDEXED" clause was supplied. See parse.y
3734 ** construct "indexed_opt" for details. */
3735 pItem->notIndexed = 1;
3736 }else{
3737 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3738 }
3739 }
3740}
3741
3742/*
drh61dfc312006-12-16 16:25:15 +00003743** When building up a FROM clause in the parser, the join operator
3744** is initially attached to the left operand. But the code generator
3745** expects the join operator to be on the right operand. This routine
3746** Shifts all join operators from left to right for an entire FROM
3747** clause.
3748**
3749** Example: Suppose the join is like this:
3750**
3751** A natural cross join B
3752**
3753** The operator is "natural cross join". The A and B operands are stored
3754** in p->a[0] and p->a[1], respectively. The parser initially stores the
3755** operator with A. This routine shifts that operator over to B.
3756*/
3757void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003758 if( p ){
drh61dfc312006-12-16 16:25:15 +00003759 int i;
drhd017ab92011-08-23 00:01:58 +00003760 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003761 for(i=p->nSrc-1; i>0; i--){
3762 p->a[i].jointype = p->a[i-1].jointype;
3763 }
3764 p->a[0].jointype = 0;
3765 }
3766}
3767
3768/*
drhc4a3c772001-04-04 11:48:57 +00003769** Begin a transaction
3770*/
drh684917c2004-10-05 02:41:42 +00003771void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003772 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003773 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003774 int i;
drh5e00f6c2001-09-13 13:46:56 +00003775
drhd3001712009-05-12 17:46:53 +00003776 assert( pParse!=0 );
3777 db = pParse->db;
3778 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003779/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003780 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3781 return;
3782 }
danielk19771d850a72004-05-31 08:26:49 +00003783 v = sqlite3GetVdbe(pParse);
3784 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003785 if( type!=TK_DEFERRED ){
3786 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003787 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003788 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003789 }
3790 }
drh66a51672008-01-03 00:01:23 +00003791 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003792}
3793
3794/*
3795** Commit a transaction
3796*/
danielk19774adee202004-05-08 08:23:19 +00003797void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003798 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003799
drhd3001712009-05-12 17:46:53 +00003800 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003801 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003802 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3803 return;
3804 }
danielk19771d850a72004-05-31 08:26:49 +00003805 v = sqlite3GetVdbe(pParse);
3806 if( v ){
drh66a51672008-01-03 00:01:23 +00003807 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003808 }
drhc4a3c772001-04-04 11:48:57 +00003809}
3810
3811/*
3812** Rollback a transaction
3813*/
danielk19774adee202004-05-08 08:23:19 +00003814void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003815 Vdbe *v;
3816
drhd3001712009-05-12 17:46:53 +00003817 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003818 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003819 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3820 return;
3821 }
danielk19774adee202004-05-08 08:23:19 +00003822 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003823 if( v ){
drh66a51672008-01-03 00:01:23 +00003824 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003825 }
drhc4a3c772001-04-04 11:48:57 +00003826}
drhf57b14a2001-09-14 18:54:08 +00003827
3828/*
danielk1977fd7f0452008-12-17 17:30:26 +00003829** This function is called by the parser when it parses a command to create,
3830** release or rollback an SQL savepoint.
3831*/
3832void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003833 char *zName = sqlite3NameFromToken(pParse->db, pName);
3834 if( zName ){
3835 Vdbe *v = sqlite3GetVdbe(pParse);
3836#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003837 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003838 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3839#endif
3840 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3841 sqlite3DbFree(pParse->db, zName);
3842 return;
3843 }
3844 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003845 }
3846}
3847
3848/*
drhdc3ff9c2004-08-18 02:10:15 +00003849** Make sure the TEMP database is open and available for use. Return
3850** the number of errors. Leave any error messages in the pParse structure.
3851*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003852int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003853 sqlite3 *db = pParse->db;
3854 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003855 int rc;
drh10a76c92010-01-26 01:25:26 +00003856 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003857 static const int flags =
3858 SQLITE_OPEN_READWRITE |
3859 SQLITE_OPEN_CREATE |
3860 SQLITE_OPEN_EXCLUSIVE |
3861 SQLITE_OPEN_DELETEONCLOSE |
3862 SQLITE_OPEN_TEMP_DB;
3863
dan3a6d8ae2011-04-23 15:54:54 +00003864 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003865 if( rc!=SQLITE_OK ){
3866 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3867 "file for storing temporary tables");
3868 pParse->rc = rc;
3869 return 1;
3870 }
drh10a76c92010-01-26 01:25:26 +00003871 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003872 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003873 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3874 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003875 return 1;
drh10a76c92010-01-26 01:25:26 +00003876 }
drhdc3ff9c2004-08-18 02:10:15 +00003877 }
3878 return 0;
3879}
3880
3881/*
drhaceb31b2014-02-08 01:40:27 +00003882** Record the fact that the schema cookie will need to be verified
3883** for database iDb. The code to actually verify the schema cookie
3884** will occur at the end of the top-level VDBE and will be generated
3885** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003886*/
danielk19774adee202004-05-08 08:23:19 +00003887void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003888 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003889 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003890
drhaceb31b2014-02-08 01:40:27 +00003891 assert( iDb>=0 && iDb<db->nDb );
3892 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3893 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3894 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003895 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3896 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003897 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3898 if( !OMIT_TEMPDB && iDb==1 ){
3899 sqlite3OpenTempDatabase(pToplevel);
3900 }
drh001bbcb2003-03-19 03:14:00 +00003901 }
drh001bbcb2003-03-19 03:14:00 +00003902}
3903
3904/*
dan57966752011-04-09 17:32:58 +00003905** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3906** attached database. Otherwise, invoke it for the database named zDb only.
3907*/
3908void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3909 sqlite3 *db = pParse->db;
3910 int i;
3911 for(i=0; i<db->nDb; i++){
3912 Db *pDb = &db->aDb[i];
3913 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3914 sqlite3CodeVerifySchema(pParse, i);
3915 }
3916 }
3917}
3918
3919/*
drh1c928532002-01-31 15:54:21 +00003920** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003921** might change the database.
3922**
3923** This routine starts a new transaction if we are not already within
3924** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003925** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003926** be set for operations that might fail (due to a constraint) part of
3927** the way through and which will need to undo some writes without having to
3928** rollback the whole transaction. For operations where all constraints
3929** can be checked before any changes are made to the database, it is never
3930** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003931*/
drh7f0f12e2004-05-21 13:39:50 +00003932void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003933 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003934 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003935 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003936 pToplevel->isMultiWrite |= setStatement;
3937}
3938
drhff738bc2009-09-24 00:09:58 +00003939/*
3940** Indicate that the statement currently under construction might write
3941** more than one entry (example: deleting one row then inserting another,
3942** inserting multiple rows in a table, or inserting a row and index entries.)
3943** If an abort occurs after some of these writes have completed, then it will
3944** be necessary to undo the completed writes.
3945*/
3946void sqlite3MultiWrite(Parse *pParse){
3947 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3948 pToplevel->isMultiWrite = 1;
3949}
3950
dane0af83a2009-09-08 19:15:01 +00003951/*
drhff738bc2009-09-24 00:09:58 +00003952** The code generator calls this routine if is discovers that it is
3953** possible to abort a statement prior to completion. In order to
3954** perform this abort without corrupting the database, we need to make
3955** sure that the statement is protected by a statement transaction.
3956**
3957** Technically, we only need to set the mayAbort flag if the
3958** isMultiWrite flag was previously set. There is a time dependency
3959** such that the abort must occur after the multiwrite. This makes
3960** some statements involving the REPLACE conflict resolution algorithm
3961** go a little faster. But taking advantage of this time dependency
3962** makes it more difficult to prove that the code is correct (in
3963** particular, it prevents us from writing an effective
3964** implementation of sqlite3AssertMayAbort()) and so we have chosen
3965** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003966*/
3967void sqlite3MayAbort(Parse *pParse){
3968 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3969 pToplevel->mayAbort = 1;
3970}
3971
3972/*
3973** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3974** error. The onError parameter determines which (if any) of the statement
3975** and/or current transaction is rolled back.
3976*/
drhd91c1a12013-02-09 13:58:25 +00003977void sqlite3HaltConstraint(
3978 Parse *pParse, /* Parsing context */
3979 int errCode, /* extended error code */
3980 int onError, /* Constraint type */
3981 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003982 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3983 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003984){
dane0af83a2009-09-08 19:15:01 +00003985 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003986 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003987 if( onError==OE_Abort ){
3988 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003989 }
drhd91c1a12013-02-09 13:58:25 +00003990 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003991 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3992}
3993
3994/*
3995** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3996*/
3997void sqlite3UniqueConstraint(
3998 Parse *pParse, /* Parsing context */
3999 int onError, /* Constraint type */
4000 Index *pIdx /* The index that triggers the constraint */
4001){
4002 char *zErr;
4003 int j;
4004 StrAccum errMsg;
4005 Table *pTab = pIdx->pTable;
4006
4007 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4008 errMsg.db = pParse->db;
4009 for(j=0; j<pIdx->nKeyCol; j++){
4010 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4011 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004012 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004013 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004014 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004015 }
4016 zErr = sqlite3StrAccumFinish(&errMsg);
4017 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004018 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4019 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004020 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004021}
4022
4023
4024/*
4025** Code an OP_Halt due to non-unique rowid.
4026*/
4027void sqlite3RowidConstraint(
4028 Parse *pParse, /* Parsing context */
4029 int onError, /* Conflict resolution algorithm */
4030 Table *pTab /* The table with the non-unique rowid */
4031){
4032 char *zMsg;
4033 int rc;
4034 if( pTab->iPKey>=0 ){
4035 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4036 pTab->aCol[pTab->iPKey].zName);
4037 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4038 }else{
4039 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4040 rc = SQLITE_CONSTRAINT_ROWID;
4041 }
4042 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4043 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004044}
4045
drh4343fea2004-11-05 23:46:15 +00004046/*
4047** Check to see if pIndex uses the collating sequence pColl. Return
4048** true if it does and false if it does not.
4049*/
4050#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004051static int collationMatch(const char *zColl, Index *pIndex){
4052 int i;
drh04491712009-05-13 17:21:13 +00004053 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004054 for(i=0; i<pIndex->nColumn; i++){
4055 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004056 assert( z!=0 || pIndex->aiColumn[i]<0 );
4057 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004058 return 1;
4059 }
drh4343fea2004-11-05 23:46:15 +00004060 }
4061 return 0;
4062}
4063#endif
4064
4065/*
4066** Recompute all indices of pTab that use the collating sequence pColl.
4067** If pColl==0 then recompute all indices of pTab.
4068*/
4069#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004070static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004071 Index *pIndex; /* An index associated with pTab */
4072
4073 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004074 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004075 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4076 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004077 sqlite3RefillIndex(pParse, pIndex, -1);
4078 }
4079 }
4080}
4081#endif
4082
4083/*
4084** Recompute all indices of all tables in all databases where the
4085** indices use the collating sequence pColl. If pColl==0 then recompute
4086** all indices everywhere.
4087*/
4088#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004089static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004090 Db *pDb; /* A single database */
4091 int iDb; /* The database index number */
4092 sqlite3 *db = pParse->db; /* The database connection */
4093 HashElem *k; /* For looping over tables in pDb */
4094 Table *pTab; /* A table in the database */
4095
drh21206082011-04-04 18:22:02 +00004096 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004097 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004098 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004099 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004100 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004101 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004102 }
4103 }
4104}
4105#endif
4106
4107/*
drheee46cf2004-11-06 00:02:48 +00004108** Generate code for the REINDEX command.
4109**
4110** REINDEX -- 1
4111** REINDEX <collation> -- 2
4112** REINDEX ?<database>.?<tablename> -- 3
4113** REINDEX ?<database>.?<indexname> -- 4
4114**
4115** Form 1 causes all indices in all attached databases to be rebuilt.
4116** Form 2 rebuilds all indices in all databases that use the named
4117** collating function. Forms 3 and 4 rebuild the named index or all
4118** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004119*/
4120#ifndef SQLITE_OMIT_REINDEX
4121void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4122 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4123 char *z; /* Name of a table or index */
4124 const char *zDb; /* Name of the database */
4125 Table *pTab; /* A table in the database */
4126 Index *pIndex; /* An index associated with pTab */
4127 int iDb; /* The database index number */
4128 sqlite3 *db = pParse->db; /* The database connection */
4129 Token *pObjName; /* Name of the table or index to be reindexed */
4130
danielk197733a5edc2005-01-27 00:22:02 +00004131 /* Read the database schema. If an error occurs, leave an error message
4132 ** and code in pParse and return NULL. */
4133 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004134 return;
danielk197733a5edc2005-01-27 00:22:02 +00004135 }
4136
drh8af73d42009-05-13 22:58:28 +00004137 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004138 reindexDatabases(pParse, 0);
4139 return;
drhd3001712009-05-12 17:46:53 +00004140 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004141 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004142 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004143 zColl = sqlite3NameFromToken(pParse->db, pName1);
4144 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004145 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004146 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004147 reindexDatabases(pParse, zColl);
4148 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004149 return;
4150 }
drh633e6d52008-07-28 19:34:53 +00004151 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004152 }
4153 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4154 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004155 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004156 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004157 zDb = db->aDb[iDb].zName;
4158 pTab = sqlite3FindTable(db, z, zDb);
4159 if( pTab ){
4160 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004161 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004162 return;
4163 }
4164 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004165 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004166 if( pIndex ){
4167 sqlite3BeginWriteOperation(pParse, 0, iDb);
4168 sqlite3RefillIndex(pParse, pIndex, -1);
4169 return;
4170 }
4171 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4172}
4173#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004174
4175/*
drh2ec2fb22013-11-06 19:59:23 +00004176** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004177**
drh2ec2fb22013-11-06 19:59:23 +00004178** The KeyInfo structure for an index is cached in the Index object.
4179** So there might be multiple references to the returned pointer. The
4180** caller should not try to modify the KeyInfo object.
4181**
4182** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4183** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004184*/
drh2ec2fb22013-11-06 19:59:23 +00004185KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004186 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004187#ifndef SQLITE_OMIT_SHARED_CACHE
4188 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4189 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4190 pIdx->pKeyInfo = 0;
4191 }
4192#endif
drh2ec2fb22013-11-06 19:59:23 +00004193 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004194 int i;
4195 int nCol = pIdx->nColumn;
4196 int nKey = pIdx->nKeyCol;
4197 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004198 if( pIdx->uniqNotNull ){
4199 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4200 }else{
4201 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4202 }
4203 if( pKey ){
4204 assert( sqlite3KeyInfoIsWriteable(pKey) );
4205 for(i=0; i<nCol; i++){
4206 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004207 assert( zColl!=0 );
4208 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4209 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004210 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4211 }
4212 if( pParse->nErr ){
4213 sqlite3KeyInfoUnref(pKey);
4214 }else{
4215 pIdx->pKeyInfo = pKey;
4216 }
danielk1977b3bf5562006-01-10 17:58:23 +00004217 }
danielk1977b3bf5562006-01-10 17:58:23 +00004218 }
drh2ec2fb22013-11-06 19:59:23 +00004219 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004220}
drh8b471862014-01-11 13:22:17 +00004221
4222#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004223/*
4224** This routine is invoked once per CTE by the parser while parsing a
4225** WITH clause.
drh8b471862014-01-11 13:22:17 +00004226*/
dan7d562db2014-01-11 19:19:36 +00004227With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004228 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004229 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004230 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004231 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004232 Select *pQuery /* Query used to initialize the table */
4233){
dan4e9119d2014-01-13 15:12:23 +00004234 sqlite3 *db = pParse->db;
4235 With *pNew;
4236 char *zName;
4237
4238 /* Check that the CTE name is unique within this WITH clause. If
4239 ** not, store an error in the Parse structure. */
4240 zName = sqlite3NameFromToken(pParse->db, pName);
4241 if( zName && pWith ){
4242 int i;
4243 for(i=0; i<pWith->nCte; i++){
4244 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004245 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004246 }
4247 }
4248 }
4249
4250 if( pWith ){
4251 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4252 pNew = sqlite3DbRealloc(db, pWith, nByte);
4253 }else{
4254 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4255 }
4256 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004257 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004258
4259 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004260 sqlite3ExprListDelete(db, pArglist);
4261 sqlite3SelectDelete(db, pQuery);
4262 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004263 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004264 }else{
4265 pNew->a[pNew->nCte].pSelect = pQuery;
4266 pNew->a[pNew->nCte].pCols = pArglist;
4267 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004268 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004269 pNew->nCte++;
4270 }
4271
4272 return pNew;
drh8b471862014-01-11 13:22:17 +00004273}
4274
dan7d562db2014-01-11 19:19:36 +00004275/*
4276** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004277*/
dan7d562db2014-01-11 19:19:36 +00004278void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004279 if( pWith ){
4280 int i;
4281 for(i=0; i<pWith->nCte; i++){
4282 struct Cte *pCte = &pWith->a[i];
4283 sqlite3ExprListDelete(db, pCte->pCols);
4284 sqlite3SelectDelete(db, pCte->pSelect);
4285 sqlite3DbFree(db, pCte->zName);
4286 }
4287 sqlite3DbFree(db, pWith);
4288 }
drh8b471862014-01-11 13:22:17 +00004289}
4290#endif /* !defined(SQLITE_OMIT_CTE) */