blob: b897494db3c2e478402917cfbe724de567177ac7 [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);
drh75b170b2014-10-04 00:07:44 +0000438#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
439 sqlite3_free(p->aiRowEst);
440#endif
drh633e6d52008-07-28 19:34:53 +0000441 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000442}
443
444/*
drhc96d8532005-05-03 12:30:33 +0000445** For the index called zIdxName which is found in the database iDb,
446** unlike that index from its Table then remove the index from
447** the index hash table and free all memory structures associated
448** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000449*/
drh9bb575f2004-09-06 17:24:11 +0000450void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000451 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000452 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000453
drh21206082011-04-04 18:22:02 +0000454 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
455 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000456 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000457 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000458 if( pIndex->pTable->pIndex==pIndex ){
459 pIndex->pTable->pIndex = pIndex->pNext;
460 }else{
461 Index *p;
drh04491712009-05-13 17:21:13 +0000462 /* Justification of ALWAYS(); The index must be on the list of
463 ** indices. */
464 p = pIndex->pTable->pIndex;
465 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
466 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000467 p->pNext = pIndex->pNext;
468 }
drh5e00f6c2001-09-13 13:46:56 +0000469 }
dan1feeaed2010-07-23 15:41:47 +0000470 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000471 }
drh956bc922004-07-24 17:38:29 +0000472 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000473}
474
475/*
drh81028a42012-05-15 18:28:27 +0000476** Look through the list of open database files in db->aDb[] and if
477** any have been closed, remove them from the list. Reallocate the
478** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000479**
drh81028a42012-05-15 18:28:27 +0000480** Entry 0 (the "main" database) and entry 1 (the "temp" database)
481** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000482*/
drh81028a42012-05-15 18:28:27 +0000483void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000484 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000485 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000486 struct Db *pDb = &db->aDb[i];
487 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000488 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000489 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000490 continue;
491 }
492 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000493 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000494 }
drh8bf8dc92003-05-17 17:35:10 +0000495 j++;
drh1c2d8412003-03-31 00:30:47 +0000496 }
497 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
498 db->nDb = j;
499 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
500 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000501 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000502 db->aDb = db->aDbStatic;
503 }
drhe0bc4042002-06-25 01:09:11 +0000504}
505
506/*
drh81028a42012-05-15 18:28:27 +0000507** Reset the schema for the database at index iDb. Also reset the
508** TEMP schema.
509*/
510void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000511 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000512 assert( iDb<db->nDb );
513
514 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000515 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000516 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
517 assert( pDb->pSchema!=0 );
518 sqlite3SchemaClear(pDb->pSchema);
519
520 /* If any database other than TEMP is reset, then also reset TEMP
521 ** since TEMP might be holding triggers that reference tables in the
522 ** other database.
523 */
524 if( iDb!=1 ){
525 pDb = &db->aDb[1];
526 assert( pDb->pSchema!=0 );
527 sqlite3SchemaClear(pDb->pSchema);
528 }
529 return;
530}
531
532/*
533** Erase all schema information from all attached databases (including
534** "main" and "temp") for a single database connection.
535*/
536void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
537 int i;
538 sqlite3BtreeEnterAll(db);
539 for(i=0; i<db->nDb; i++){
540 Db *pDb = &db->aDb[i];
541 if( pDb->pSchema ){
542 sqlite3SchemaClear(pDb->pSchema);
543 }
544 }
545 db->flags &= ~SQLITE_InternChanges;
546 sqlite3VtabUnlockList(db);
547 sqlite3BtreeLeaveAll(db);
548 sqlite3CollapseDatabaseArray(db);
549}
550
551/*
drhe0bc4042002-06-25 01:09:11 +0000552** This routine is called when a commit occurs.
553*/
drh9bb575f2004-09-06 17:24:11 +0000554void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000555 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000556}
557
558/*
dand46def72010-07-24 11:28:28 +0000559** Delete memory allocated for the column names of a table or view (the
560** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000561*/
dand46def72010-07-24 11:28:28 +0000562static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000563 int i;
564 Column *pCol;
565 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000566 if( (pCol = pTable->aCol)!=0 ){
567 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000568 sqlite3DbFree(db, pCol->zName);
569 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000570 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000571 sqlite3DbFree(db, pCol->zType);
572 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000573 }
drh633e6d52008-07-28 19:34:53 +0000574 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000575 }
drh956bc922004-07-24 17:38:29 +0000576}
577
578/*
drh75897232000-05-29 14:26:00 +0000579** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000580** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000581**
582** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000583** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000584** memory structures of the indices and foreign keys associated with
585** the table.
drh29ddd3a2012-05-15 12:49:32 +0000586**
587** The db parameter is optional. It is needed if the Table object
588** contains lookaside memory. (Table objects in the schema do not use
589** lookaside memory, but some ephemeral Table objects do.) Or the
590** db parameter can be used with db->pnBytesFreed to measure the memory
591** used by the Table object.
drh75897232000-05-29 14:26:00 +0000592*/
dan1feeaed2010-07-23 15:41:47 +0000593void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000594 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000595 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000596
dand46def72010-07-24 11:28:28 +0000597 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000598
drhed8a3bb2005-06-06 21:19:56 +0000599 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000600 if( !pTable ) return;
601 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000602
drh29ddd3a2012-05-15 12:49:32 +0000603 /* Record the number of outstanding lookaside allocations in schema Tables
604 ** prior to doing any free() operations. Since schema Tables do not use
605 ** lookaside, this number should not change. */
606 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
607 db->lookaside.nOut : 0 );
608
dand46def72010-07-24 11:28:28 +0000609 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000610 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
611 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000612 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000613 if( !db || db->pnBytesFreed==0 ){
614 char *zName = pIndex->zName;
615 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000616 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000617 );
drh21206082011-04-04 18:22:02 +0000618 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000619 assert( pOld==pIndex || pOld==0 );
620 }
621 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000622 }
623
dan1da40a32009-09-19 17:00:31 +0000624 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000625 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000626
627 /* Delete the Table structure itself.
628 */
dand46def72010-07-24 11:28:28 +0000629 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000630 sqlite3DbFree(db, pTable->zName);
631 sqlite3DbFree(db, pTable->zColAff);
632 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000633#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000634 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000635#endif
drh078e4082010-07-28 19:17:51 +0000636#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000637 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000638#endif
drh633e6d52008-07-28 19:34:53 +0000639 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000640
641 /* Verify that no lookaside memory was used by schema tables */
642 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000643}
644
645/*
drh5edc3122001-09-13 21:53:09 +0000646** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000647** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000648*/
drh9bb575f2004-09-06 17:24:11 +0000649void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000650 Table *p;
drh956bc922004-07-24 17:38:29 +0000651 Db *pDb;
652
drhd229ca92002-01-09 13:30:41 +0000653 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000654 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000655 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000656 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000657 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000658 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000659 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000660 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000661 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000662}
663
664/*
drha99db3b2004-06-19 14:49:12 +0000665** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000666** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000667** is obtained from sqliteMalloc() and must be freed by the calling
668** function.
drh75897232000-05-29 14:26:00 +0000669**
drh24fb6272009-05-01 21:13:36 +0000670** Any quotation marks (ex: "name", 'name', [name], or `name`) that
671** surround the body of the token are removed.
672**
drhc96d8532005-05-03 12:30:33 +0000673** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000674** are not \000 terminated and are not persistent. The returned string
675** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000676*/
drh17435752007-08-16 04:30:38 +0000677char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000678 char *zName;
679 if( pName ){
drh17435752007-08-16 04:30:38 +0000680 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000681 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000682 }else{
683 zName = 0;
684 }
drh75897232000-05-29 14:26:00 +0000685 return zName;
686}
687
688/*
danielk1977cbb18d22004-05-28 11:37:27 +0000689** Open the sqlite_master table stored in database number iDb for
690** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000691*/
danielk1977c00da102006-01-07 13:21:04 +0000692void sqlite3OpenMasterTable(Parse *p, int iDb){
693 Vdbe *v = sqlite3GetVdbe(p);
694 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000695 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000696 if( p->nTab==0 ){
697 p->nTab = 1;
698 }
drhe0bc4042002-06-25 01:09:11 +0000699}
700
701/*
danielk197704103022009-02-03 16:51:24 +0000702** Parameter zName points to a nul-terminated buffer containing the name
703** of a database ("main", "temp" or the name of an attached db). This
704** function returns the index of the named database in db->aDb[], or
705** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000706*/
danielk197704103022009-02-03 16:51:24 +0000707int sqlite3FindDbName(sqlite3 *db, const char *zName){
708 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000709 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000710 Db *pDb;
711 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000712 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000713 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000714 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000715 break;
drh73c42a12004-11-20 18:13:10 +0000716 }
danielk1977cbb18d22004-05-28 11:37:27 +0000717 }
718 }
danielk1977576ec6b2005-01-21 11:55:25 +0000719 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000720}
721
danielk197704103022009-02-03 16:51:24 +0000722/*
723** The token *pName contains the name of a database (either "main" or
724** "temp" or the name of an attached db). This routine returns the
725** index of the named database in db->aDb[], or -1 if the named db
726** does not exist.
727*/
728int sqlite3FindDb(sqlite3 *db, Token *pName){
729 int i; /* Database number */
730 char *zName; /* Name we are searching for */
731 zName = sqlite3NameFromToken(db, pName);
732 i = sqlite3FindDbName(db, zName);
733 sqlite3DbFree(db, zName);
734 return i;
735}
736
drh0e3d7472004-06-19 17:33:07 +0000737/* The table or view or trigger name is passed to this routine via tokens
738** pName1 and pName2. If the table name was fully qualified, for example:
739**
740** CREATE TABLE xxx.yyy (...);
741**
742** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
743** the table name is not fully qualified, i.e.:
744**
745** CREATE TABLE yyy(...);
746**
747** Then pName1 is set to "yyy" and pName2 is "".
748**
749** This routine sets the *ppUnqual pointer to point at the token (pName1 or
750** pName2) that stores the unqualified table name. The index of the
751** database "xxx" is returned.
752*/
danielk1977ef2cb632004-05-29 02:37:19 +0000753int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000754 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000755 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000756 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
757 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000758){
drh0e3d7472004-06-19 17:33:07 +0000759 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000760 sqlite3 *db = pParse->db;
761
drhc4a64fa2009-05-11 20:53:28 +0000762 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000763 if( db->init.busy ) {
764 sqlite3ErrorMsg(pParse, "corrupt database");
765 pParse->nErr++;
766 return -1;
767 }
danielk1977cbb18d22004-05-28 11:37:27 +0000768 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000769 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000770 if( iDb<0 ){
771 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
772 pParse->nErr++;
773 return -1;
774 }
775 }else{
776 assert( db->init.iDb==0 || db->init.busy );
777 iDb = db->init.iDb;
778 *pUnqual = pName1;
779 }
780 return iDb;
781}
782
783/*
danielk1977d8123362004-06-12 09:25:12 +0000784** This routine is used to check if the UTF-8 string zName is a legal
785** unqualified name for a new schema object (table, index, view or
786** trigger). All names are legal except those that begin with the string
787** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
788** is reserved for internal use.
789*/
790int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000791 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000792 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000793 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000794 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
795 return SQLITE_ERROR;
796 }
797 return SQLITE_OK;
798}
799
800/*
drh44156282013-10-23 22:23:03 +0000801** Return the PRIMARY KEY index of a table
802*/
803Index *sqlite3PrimaryKeyIndex(Table *pTab){
804 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000805 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000806 return p;
807}
808
809/*
810** Return the column of index pIdx that corresponds to table
811** column iCol. Return -1 if not found.
812*/
813i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
814 int i;
815 for(i=0; i<pIdx->nColumn; i++){
816 if( iCol==pIdx->aiColumn[i] ) return i;
817 }
818 return -1;
819}
820
821/*
drh75897232000-05-29 14:26:00 +0000822** Begin constructing a new table representation in memory. This is
823** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000824** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000825** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000826** flag is true if the table should be stored in the auxiliary database
827** file instead of in the main database file. This is normally the case
828** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000829** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000830**
drhf57b3392001-10-08 13:22:32 +0000831** The new table record is initialized and put in pParse->pNewTable.
832** As more of the CREATE TABLE statement is parsed, additional action
833** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000834** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000835** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000836*/
danielk19774adee202004-05-08 08:23:19 +0000837void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000838 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000839 Token *pName1, /* First part of the name of the table or view */
840 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000841 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000842 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000843 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000844 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000845){
drh75897232000-05-29 14:26:00 +0000846 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000847 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000848 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000849 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000850 int iDb; /* Database number to create the table in */
851 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000852
danielk1977cbb18d22004-05-28 11:37:27 +0000853 /* The table or view name to create is passed to this routine via tokens
854 ** pName1 and pName2. If the table name was fully qualified, for example:
855 **
856 ** CREATE TABLE xxx.yyy (...);
857 **
858 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
859 ** the table name is not fully qualified, i.e.:
860 **
861 ** CREATE TABLE yyy(...);
862 **
863 ** Then pName1 is set to "yyy" and pName2 is "".
864 **
865 ** The call below sets the pName pointer to point at the token (pName1 or
866 ** pName2) that stores the unqualified table name. The variable iDb is
867 ** set to the index of the database that the table or view is to be
868 ** created in.
869 */
danielk1977ef2cb632004-05-29 02:37:19 +0000870 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000871 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000872 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
873 /* If creating a temp table, the name may not be qualified. Unless
874 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000875 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000876 return;
877 }
danielk197753c0f742005-03-29 03:10:59 +0000878 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000879
880 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000881 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000882 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000883 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000884 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000885 }
drh1d85d932004-02-14 23:05:52 +0000886 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000887#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000888 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000889 {
890 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000891 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000892 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000893 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000894 }
drhe5f9c642003-01-13 23:27:31 +0000895 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000896 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000897 code = SQLITE_CREATE_TEMP_VIEW;
898 }else{
899 code = SQLITE_CREATE_VIEW;
900 }
901 }else{
danielk197753c0f742005-03-29 03:10:59 +0000902 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000903 code = SQLITE_CREATE_TEMP_TABLE;
904 }else{
905 code = SQLITE_CREATE_TABLE;
906 }
907 }
danielk1977f1a381e2006-06-16 08:01:02 +0000908 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000909 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000910 }
911 }
912#endif
drhf57b3392001-10-08 13:22:32 +0000913
drhf57b3392001-10-08 13:22:32 +0000914 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000915 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000916 ** it does. The exception is if the statement being parsed was passed
917 ** to an sqlite3_declare_vtab() call. In that case only the column names
918 ** and types will be used, so there is no need to test for namespace
919 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000920 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000921 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000922 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000923 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
924 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000925 }
dana16d1062010-09-28 17:37:28 +0000926 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000927 if( pTable ){
928 if( !noErr ){
929 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000930 }else{
931 assert( !db->init.busy );
932 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000933 }
934 goto begin_table_error;
935 }
drh8a8a0d12010-09-28 20:26:44 +0000936 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000937 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
938 goto begin_table_error;
939 }
drh75897232000-05-29 14:26:00 +0000940 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000941
danielk197726783a52007-08-29 14:06:22 +0000942 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000943 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000944 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000945 pParse->rc = SQLITE_NOMEM;
946 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000947 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000948 }
drh75897232000-05-29 14:26:00 +0000949 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000950 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000951 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000952 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000953 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000954 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000955 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000956
drh4794f732004-11-05 17:17:50 +0000957 /* If this is the magic sqlite_sequence table used by autoincrement,
958 ** then record a pointer to this table in the main database structure
959 ** so that INSERT can find the table easily.
960 */
961#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000962 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000963 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000964 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000965 }
966#endif
967
drh17f71932002-02-21 12:01:27 +0000968 /* Begin generating the code that will insert the table record into
969 ** the SQLITE_MASTER table. Note in particular that we must go ahead
970 ** and allocate the record number for the table entry now. Before any
971 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
972 ** indices to be created and the table record must come before the
973 ** indices. Hence, the record number for the table must be allocated
974 ** now.
975 */
danielk19774adee202004-05-08 08:23:19 +0000976 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000977 int j1;
drhe321c292006-01-12 01:56:43 +0000978 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000979 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000980 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000981
danielk197720b1eaf2006-07-26 16:22:14 +0000982#ifndef SQLITE_OMIT_VIRTUALTABLE
983 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000984 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000985 }
986#endif
987
danielk197736963fd2005-02-19 08:18:05 +0000988 /* If the file format and encoding in the database have not been set,
989 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000990 */
drhb7654112008-01-12 12:48:07 +0000991 reg1 = pParse->regRowid = ++pParse->nMem;
992 reg2 = pParse->regRoot = ++pParse->nMem;
993 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000994 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000995 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000996 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000997 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000998 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000999 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001000 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001001 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001002 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001003 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001004
drh4794f732004-11-05 17:17:50 +00001005 /* This just creates a place-holder record in the sqlite_master table.
1006 ** The record created does not contain anything yet. It will be replaced
1007 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001008 **
drh0fa991b2009-03-21 16:19:26 +00001009 ** The rowid for the new entry is left in register pParse->regRowid.
1010 ** The root page number of the new table is left in reg pParse->regRoot.
1011 ** The rowid and root page number values are needed by the code that
1012 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001013 */
danielk1977f1a381e2006-06-16 08:01:02 +00001014#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1015 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001016 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001017 }else
1018#endif
1019 {
drh8a120f82013-11-01 17:59:53 +00001020 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001021 }
danielk1977c00da102006-01-07 13:21:04 +00001022 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001023 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1024 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1025 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1026 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001027 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001028 }
drh23bf66d2004-12-14 03:34:34 +00001029
1030 /* Normal (non-error) return. */
1031 return;
1032
1033 /* If an error occurs, we jump here */
1034begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001035 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001036 return;
drh75897232000-05-29 14:26:00 +00001037}
1038
1039/*
danielk1977c60e9b82005-01-31 12:42:29 +00001040** This macro is used to compare two strings in a case-insensitive manner.
1041** It is slightly faster than calling sqlite3StrICmp() directly, but
1042** produces larger code.
1043**
1044** WARNING: This macro is not compatible with the strcmp() family. It
1045** returns true if the two strings are equal, otherwise false.
1046*/
1047#define STRICMP(x, y) (\
1048sqlite3UpperToLower[*(unsigned char *)(x)]== \
1049sqlite3UpperToLower[*(unsigned char *)(y)] \
1050&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1051
1052/*
drh75897232000-05-29 14:26:00 +00001053** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001054**
1055** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001056** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001057** first to get things going. Then this routine is called for each
1058** column.
drh75897232000-05-29 14:26:00 +00001059*/
danielk19774adee202004-05-08 08:23:19 +00001060void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001061 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001062 int i;
drha99db3b2004-06-19 14:49:12 +00001063 char *z;
drhc9b84a12002-06-20 11:36:48 +00001064 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001065 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001066 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001067#if SQLITE_MAX_COLUMN
1068 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001069 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1070 return;
1071 }
drhbb4957f2008-03-20 14:03:29 +00001072#endif
danielk1977ae74e032008-12-23 11:11:51 +00001073 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001074 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001075 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001076 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001077 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001078 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001079 return;
1080 }
1081 }
drh75897232000-05-29 14:26:00 +00001082 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001083 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001084 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001085 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001086 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001087 return;
1088 }
drh6d4abfb2001-10-22 02:58:08 +00001089 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001090 }
drhc9b84a12002-06-20 11:36:48 +00001091 pCol = &p->aCol[p->nCol];
1092 memset(pCol, 0, sizeof(p->aCol[0]));
1093 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001094
1095 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001096 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1097 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001098 */
danielk19774f057f92004-06-08 00:02:33 +00001099 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001100 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001101 p->nCol++;
drh75897232000-05-29 14:26:00 +00001102}
1103
1104/*
drh382c0242001-10-06 16:33:02 +00001105** This routine is called by the parser while in the middle of
1106** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1107** been seen on a column. This routine sets the notNull flag on
1108** the column currently under construction.
1109*/
danielk19774adee202004-05-08 08:23:19 +00001110void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001111 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001112 p = pParse->pNewTable;
1113 if( p==0 || NEVER(p->nCol<1) ) return;
1114 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001115}
1116
1117/*
danielk197752a83fb2005-01-31 12:56:44 +00001118** Scan the column type name zType (length nType) and return the
1119** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001120**
1121** This routine does a case-independent search of zType for the
1122** substrings in the following table. If one of the substrings is
1123** found, the corresponding affinity is returned. If zType contains
1124** more than one of the substrings, entries toward the top of
1125** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001126** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001127**
1128** Substring | Affinity
1129** --------------------------------
1130** 'INT' | SQLITE_AFF_INTEGER
1131** 'CHAR' | SQLITE_AFF_TEXT
1132** 'CLOB' | SQLITE_AFF_TEXT
1133** 'TEXT' | SQLITE_AFF_TEXT
1134** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001135** 'REAL' | SQLITE_AFF_REAL
1136** 'FLOA' | SQLITE_AFF_REAL
1137** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001138**
1139** If none of the substrings in the above table are found,
1140** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001141*/
drhfdaac672013-10-04 15:30:21 +00001142char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001143 u32 h = 0;
1144 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001145 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001146
drhfdaac672013-10-04 15:30:21 +00001147 if( zIn==0 ) return aff;
1148 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001149 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001150 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001151 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001152 aff = SQLITE_AFF_TEXT;
1153 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001154 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1155 aff = SQLITE_AFF_TEXT;
1156 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1157 aff = SQLITE_AFF_TEXT;
1158 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001159 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001160 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001161 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001162#ifndef SQLITE_OMIT_FLOATING_POINT
1163 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1164 && aff==SQLITE_AFF_NUMERIC ){
1165 aff = SQLITE_AFF_REAL;
1166 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1167 && aff==SQLITE_AFF_NUMERIC ){
1168 aff = SQLITE_AFF_REAL;
1169 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1170 && aff==SQLITE_AFF_NUMERIC ){
1171 aff = SQLITE_AFF_REAL;
1172#endif
danielk1977201f7162005-02-01 02:13:29 +00001173 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001174 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001175 break;
danielk197752a83fb2005-01-31 12:56:44 +00001176 }
1177 }
drhd3037a42013-10-04 18:29:25 +00001178
1179 /* If pszEst is not NULL, store an estimate of the field size. The
1180 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001181 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001182 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001183 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001184 if( zChar ){
1185 while( zChar[0] ){
1186 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001187 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001188 sqlite3GetInt32(zChar, &v);
1189 v = v/4 + 1;
1190 if( v>255 ) v = 255;
1191 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1192 break;
1193 }
1194 zChar++;
drhfdaac672013-10-04 15:30:21 +00001195 }
drhd3037a42013-10-04 18:29:25 +00001196 }else{
1197 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001198 }
drhfdaac672013-10-04 15:30:21 +00001199 }
1200 }
danielk1977b3dff962005-02-01 01:21:55 +00001201 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001202}
1203
1204/*
drh382c0242001-10-06 16:33:02 +00001205** This routine is called by the parser while in the middle of
1206** parsing a CREATE TABLE statement. The pFirst token is the first
1207** token in the sequence of tokens that describe the type of the
1208** column currently under construction. pLast is the last token
1209** in the sequence. Use this information to construct a string
1210** that contains the typename of the column and store that string
1211** in zType.
1212*/
drh487e2622005-06-25 18:42:14 +00001213void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001214 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001215 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001216
drhc4a64fa2009-05-11 20:53:28 +00001217 p = pParse->pNewTable;
1218 if( p==0 || NEVER(p->nCol<1) ) return;
1219 pCol = &p->aCol[p->nCol-1];
1220 assert( pCol->zType==0 );
1221 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001222 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001223}
1224
1225/*
danielk19777977a172004-11-09 12:44:37 +00001226** The expression is the default value for the most recently added column
1227** of the table currently under construction.
1228**
1229** Default value expressions must be constant. Raise an exception if this
1230** is not the case.
drhd9b02572001-04-15 00:37:09 +00001231**
1232** This routine is called by the parser while in the middle of
1233** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001234*/
drhb7916a72009-05-27 10:31:29 +00001235void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001236 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001237 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001238 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001239 p = pParse->pNewTable;
1240 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001241 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001242 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001243 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1244 pCol->zName);
1245 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001246 /* A copy of pExpr is used instead of the original, as pExpr contains
1247 ** tokens that point to volatile memory. The 'span' of the expression
1248 ** is required by pragma table_info.
1249 */
drh633e6d52008-07-28 19:34:53 +00001250 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001251 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1252 sqlite3DbFree(db, pCol->zDflt);
1253 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001254 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001255 }
danielk19777977a172004-11-09 12:44:37 +00001256 }
drhb7916a72009-05-27 10:31:29 +00001257 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001258}
1259
1260/*
drh4a324312001-12-21 14:30:42 +00001261** Designate the PRIMARY KEY for the table. pList is a list of names
1262** of columns that form the primary key. If pList is NULL, then the
1263** most recently added column of the table is the primary key.
1264**
1265** A table can have at most one primary key. If the table already has
1266** a primary key (and this is the second primary key) then create an
1267** error.
1268**
1269** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001270** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001271** field of the table under construction to be the index of the
1272** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1273** no INTEGER PRIMARY KEY.
1274**
1275** If the key is not an INTEGER PRIMARY KEY, then create a unique
1276** index for the key. No index is created for INTEGER PRIMARY KEYs.
1277*/
drh205f48e2004-11-05 00:43:11 +00001278void sqlite3AddPrimaryKey(
1279 Parse *pParse, /* Parsing context */
1280 ExprList *pList, /* List of field names to be indexed */
1281 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001282 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1283 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001284){
drh4a324312001-12-21 14:30:42 +00001285 Table *pTab = pParse->pNewTable;
1286 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001287 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001288 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001289 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001290 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001291 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001292 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001293 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001294 }
drh7d10d5a2008-08-20 16:35:10 +00001295 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001296 if( pList==0 ){
1297 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001298 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001299 zType = pTab->aCol[iCol].zType;
1300 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001301 }else{
drh8ea30bf2013-10-22 01:18:17 +00001302 nTerm = pList->nExpr;
1303 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001304 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001305 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001306 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1307 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001308 break;
1309 }
drh78100cc2003-08-23 22:40:53 +00001310 }
drh4a324312001-12-21 14:30:42 +00001311 }
1312 }
drh8ea30bf2013-10-22 01:18:17 +00001313 if( nTerm==1
1314 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1315 && sortOrder==SQLITE_SO_ASC
1316 ){
drh4a324312001-12-21 14:30:42 +00001317 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001318 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001319 assert( autoInc==0 || autoInc==1 );
1320 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001321 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001322 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001323#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001324 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1325 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001326#endif
drh4a324312001-12-21 14:30:42 +00001327 }else{
drhc6bd4e42013-11-02 14:37:18 +00001328 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001329 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001330 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001331 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001332 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001333 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001334 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001335 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001336 }
drhe0194f22003-02-26 13:52:51 +00001337 pList = 0;
drh4a324312001-12-21 14:30:42 +00001338 }
drhe0194f22003-02-26 13:52:51 +00001339
1340primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001341 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001342 return;
drh4a324312001-12-21 14:30:42 +00001343}
1344
1345/*
drhffe07b22005-11-03 00:41:17 +00001346** Add a new CHECK constraint to the table currently under construction.
1347*/
1348void sqlite3AddCheckConstraint(
1349 Parse *pParse, /* Parsing context */
1350 Expr *pCheckExpr /* The check expression */
1351){
1352#ifndef SQLITE_OMIT_CHECK
1353 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001354 sqlite3 *db = pParse->db;
1355 if( pTab && !IN_DECLARE_VTAB
1356 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1357 ){
drh2938f922012-03-07 19:13:29 +00001358 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1359 if( pParse->constraintName.n ){
1360 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1361 }
drh33e619f2009-05-28 01:00:55 +00001362 }else
drhffe07b22005-11-03 00:41:17 +00001363#endif
drh33e619f2009-05-28 01:00:55 +00001364 {
drh2938f922012-03-07 19:13:29 +00001365 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001366 }
drhffe07b22005-11-03 00:41:17 +00001367}
1368
1369/*
drhd3d39e92004-05-20 22:16:29 +00001370** Set the collation function of the most recently parsed table column
1371** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001372*/
danielk197739002502007-11-12 09:50:26 +00001373void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001374 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001375 int i;
danielk197739002502007-11-12 09:50:26 +00001376 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001377 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001378
danielk1977b8cbb872006-06-19 05:33:45 +00001379 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001380 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001381 db = pParse->db;
1382 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001383 if( !zColl ) return;
1384
drhc4a64fa2009-05-11 20:53:28 +00001385 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001386 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001387 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001388 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001389
1390 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1391 ** then an index may have been created on this column before the
1392 ** collation type was added. Correct this if it is the case.
1393 */
1394 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001395 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001396 if( pIdx->aiColumn[0]==i ){
1397 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001398 }
1399 }
danielk197739002502007-11-12 09:50:26 +00001400 }else{
drh633e6d52008-07-28 19:34:53 +00001401 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001402 }
danielk19777cedc8d2004-06-10 10:50:08 +00001403}
1404
danielk1977466be562004-06-10 02:16:01 +00001405/*
1406** This function returns the collation sequence for database native text
1407** encoding identified by the string zName, length nName.
1408**
1409** If the requested collation sequence is not available, or not available
1410** in the database native encoding, the collation factory is invoked to
1411** request it. If the collation factory does not supply such a sequence,
1412** and the sequence is available in another text encoding, then that is
1413** returned instead.
1414**
1415** If no versions of the requested collations sequence are available, or
1416** another error occurs, NULL is returned and an error message written into
1417** pParse.
drha34001c2007-02-02 12:44:37 +00001418**
1419** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1420** invokes the collation factory if the named collation cannot be found
1421** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001422**
1423** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001424*/
drhc4a64fa2009-05-11 20:53:28 +00001425CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001426 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001427 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001428 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001429 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001430
drhc4a64fa2009-05-11 20:53:28 +00001431 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001432 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001433 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001434 }
1435
danielk19770202b292004-06-09 09:55:16 +00001436 return pColl;
1437}
1438
1439
drh8e2ca022002-06-17 17:07:19 +00001440/*
drh3f7d4e42004-07-24 14:35:58 +00001441** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001442**
1443** The schema cookie is used to determine when the schema for the
1444** database changes. After each schema change, the cookie value
1445** changes. When a process first reads the schema it records the
1446** cookie. Thereafter, whenever it goes to access the database,
1447** it checks the cookie to make sure the schema has not changed
1448** since it was last read.
1449**
1450** This plan is not completely bullet-proof. It is possible for
1451** the schema to change multiple times and for the cookie to be
1452** set back to prior value. But schema changes are infrequent
1453** and the probability of hitting the same cookie value is only
1454** 1 chance in 2^32. So we're safe enough.
1455*/
drh9cbf3422008-01-17 16:22:13 +00001456void sqlite3ChangeCookie(Parse *pParse, int iDb){
1457 int r1 = sqlite3GetTempReg(pParse);
1458 sqlite3 *db = pParse->db;
1459 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001460 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001461 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001462 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001463 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001464}
1465
1466/*
drh969fa7c2002-02-18 18:30:32 +00001467** Measure the number of characters needed to output the given
1468** identifier. The number returned includes any quotes used
1469** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001470**
1471** The estimate is conservative. It might be larger that what is
1472** really needed.
drh969fa7c2002-02-18 18:30:32 +00001473*/
1474static int identLength(const char *z){
1475 int n;
drh17f71932002-02-21 12:01:27 +00001476 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001477 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001478 }
drh234c39d2004-07-24 03:30:47 +00001479 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001480}
1481
1482/*
danielk19771b870de2009-03-14 08:37:23 +00001483** The first parameter is a pointer to an output buffer. The second
1484** parameter is a pointer to an integer that contains the offset at
1485** which to write into the output buffer. This function copies the
1486** nul-terminated string pointed to by the third parameter, zSignedIdent,
1487** to the specified offset in the buffer and updates *pIdx to refer
1488** to the first byte after the last byte written before returning.
1489**
1490** If the string zSignedIdent consists entirely of alpha-numeric
1491** characters, does not begin with a digit and is not an SQL keyword,
1492** then it is copied to the output buffer exactly as it is. Otherwise,
1493** it is quoted using double-quotes.
1494*/
drhc4a64fa2009-05-11 20:53:28 +00001495static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001496 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001497 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001498 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001499
drh17f71932002-02-21 12:01:27 +00001500 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001501 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001502 }
drhc7407522014-01-10 20:38:12 +00001503 needQuote = sqlite3Isdigit(zIdent[0])
1504 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1505 || zIdent[j]!=0
1506 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001507
drh234c39d2004-07-24 03:30:47 +00001508 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001509 for(j=0; zIdent[j]; j++){
1510 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001511 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001512 }
drh234c39d2004-07-24 03:30:47 +00001513 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001514 z[i] = 0;
1515 *pIdx = i;
1516}
1517
1518/*
1519** Generate a CREATE TABLE statement appropriate for the given
1520** table. Memory to hold the text of the statement is obtained
1521** from sqliteMalloc() and must be freed by the calling function.
1522*/
drh1d34fde2009-02-03 15:50:33 +00001523static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001524 int i, k, n;
1525 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001526 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001527 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001528 n = 0;
drh234c39d2004-07-24 03:30:47 +00001529 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001530 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001531 }
1532 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001533 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001534 zSep = "";
1535 zSep2 = ",";
1536 zEnd = ")";
1537 }else{
1538 zSep = "\n ";
1539 zSep2 = ",\n ";
1540 zEnd = "\n)";
1541 }
drhe0bc4042002-06-25 01:09:11 +00001542 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001543 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001544 if( zStmt==0 ){
1545 db->mallocFailed = 1;
1546 return 0;
1547 }
drhbdb339f2009-02-02 18:03:21 +00001548 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001549 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001550 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001551 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001552 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001553 static const char * const azType[] = {
drhc4a64fa2009-05-11 20:53:28 +00001554 /* SQLITE_AFF_NONE */ "",
drh7ea31cc2014-09-18 14:36:00 +00001555 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001556 /* SQLITE_AFF_NUMERIC */ " NUM",
1557 /* SQLITE_AFF_INTEGER */ " INT",
1558 /* SQLITE_AFF_REAL */ " REAL"
1559 };
1560 int len;
1561 const char *zType;
1562
drh5bb3eb92007-05-04 13:15:55 +00001563 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001564 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001565 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001566 identPut(zStmt, &k, pCol->zName);
drh7ea31cc2014-09-18 14:36:00 +00001567 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1568 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001569 testcase( pCol->affinity==SQLITE_AFF_NONE );
drh7ea31cc2014-09-18 14:36:00 +00001570 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001571 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1572 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1573 testcase( pCol->affinity==SQLITE_AFF_REAL );
1574
drh7ea31cc2014-09-18 14:36:00 +00001575 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
drhc4a64fa2009-05-11 20:53:28 +00001576 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001577 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001578 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001579 memcpy(&zStmt[k], zType, len);
1580 k += len;
1581 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001582 }
drh5bb3eb92007-05-04 13:15:55 +00001583 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001584 return zStmt;
1585}
1586
1587/*
drh7f9c5db2013-10-23 00:32:58 +00001588** Resize an Index object to hold N columns total. Return SQLITE_OK
1589** on success and SQLITE_NOMEM on an OOM error.
1590*/
1591static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1592 char *zExtra;
1593 int nByte;
1594 if( pIdx->nColumn>=N ) return SQLITE_OK;
1595 assert( pIdx->isResized==0 );
1596 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1597 zExtra = sqlite3DbMallocZero(db, nByte);
1598 if( zExtra==0 ) return SQLITE_NOMEM;
1599 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1600 pIdx->azColl = (char**)zExtra;
1601 zExtra += sizeof(char*)*N;
1602 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1603 pIdx->aiColumn = (i16*)zExtra;
1604 zExtra += sizeof(i16)*N;
1605 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1606 pIdx->aSortOrder = (u8*)zExtra;
1607 pIdx->nColumn = N;
1608 pIdx->isResized = 1;
1609 return SQLITE_OK;
1610}
1611
1612/*
drhfdaac672013-10-04 15:30:21 +00001613** Estimate the total row width for a table.
1614*/
drhe13e9f52013-10-05 19:18:00 +00001615static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001616 unsigned wTable = 0;
1617 const Column *pTabCol;
1618 int i;
1619 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1620 wTable += pTabCol->szEst;
1621 }
1622 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001623 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001624}
1625
1626/*
drhe13e9f52013-10-05 19:18:00 +00001627** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001628*/
drhe13e9f52013-10-05 19:18:00 +00001629static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001630 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001631 int i;
1632 const Column *aCol = pIdx->pTable->aCol;
1633 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001634 i16 x = pIdx->aiColumn[i];
1635 assert( x<pIdx->pTable->nCol );
1636 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001637 }
drhe13e9f52013-10-05 19:18:00 +00001638 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001639}
1640
drh7f9c5db2013-10-23 00:32:58 +00001641/* Return true if value x is found any of the first nCol entries of aiCol[]
1642*/
1643static int hasColumn(const i16 *aiCol, int nCol, int x){
1644 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1645 return 0;
1646}
1647
1648/*
drhc6bd4e42013-11-02 14:37:18 +00001649** This routine runs at the end of parsing a CREATE TABLE statement that
1650** has a WITHOUT ROWID clause. The job of this routine is to convert both
1651** internal schema data structures and the generated VDBE code so that they
1652** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1653** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001654**
drhc6bd4e42013-11-02 14:37:18 +00001655** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1656** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1657** data storage is a covering index btree.
1658** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001659** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001660** identified by the sqlite_master table entry of the table itself.
1661** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1662** schema to the rootpage from the main table.
1663** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1664** (5) Add all table columns to the PRIMARY KEY Index object
1665** so that the PRIMARY KEY is a covering index. The surplus
1666** columns are part of KeyInfo.nXField and are not used for
1667** sorting or lookup or uniqueness checks.
1668** (6) Replace the rowid tail on all automatically generated UNIQUE
1669** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001670*/
1671static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1672 Index *pIdx;
1673 Index *pPk;
1674 int nPk;
1675 int i, j;
1676 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001677 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001678
1679 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001680 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001681 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001682 */
1683 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001684 assert( v );
1685 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1686 }
1687
1688 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1689 ** table entry.
1690 */
1691 if( pParse->addrSkipPK ){
1692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001694 }
1695
1696 /* Locate the PRIMARY KEY index. Or, if this table was originally
1697 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1698 */
1699 if( pTab->iPKey>=0 ){
1700 ExprList *pList;
1701 pList = sqlite3ExprListAppend(pParse, 0, 0);
1702 if( pList==0 ) return;
1703 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1704 pTab->aCol[pTab->iPKey].zName);
1705 pList->a[0].sortOrder = pParse->iPkSortOrder;
1706 assert( pParse->pNewTable==pTab );
1707 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1708 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001709 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001710 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001711 }else{
1712 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001713 }
drh12826092013-11-05 22:39:17 +00001714 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001715 assert( pPk!=0 );
1716 nPk = pPk->nKeyCol;
1717
drhec95c442013-10-23 01:57:32 +00001718 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1719 for(i=0; i<nPk; i++){
1720 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1721 }
drh9eade082013-10-24 14:16:10 +00001722 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001723
drhc6bd4e42013-11-02 14:37:18 +00001724 /* The root page of the PRIMARY KEY is the table root page */
1725 pPk->tnum = pTab->tnum;
1726
drh7f9c5db2013-10-23 00:32:58 +00001727 /* Update the in-memory representation of all UNIQUE indices by converting
1728 ** the final rowid column into one or more columns of the PRIMARY KEY.
1729 */
1730 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1731 int n;
drh48dd1d82014-05-27 18:18:58 +00001732 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001733 for(i=n=0; i<nPk; i++){
1734 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1735 }
drh5a9a37b2013-11-05 17:30:04 +00001736 if( n==0 ){
1737 /* This index is a superset of the primary key */
1738 pIdx->nColumn = pIdx->nKeyCol;
1739 continue;
1740 }
drh7f9c5db2013-10-23 00:32:58 +00001741 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1742 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001743 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001744 pIdx->aiColumn[j] = pPk->aiColumn[i];
1745 pIdx->azColl[j] = pPk->azColl[i];
1746 j++;
1747 }
1748 }
drh00012df2013-11-05 01:59:07 +00001749 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1750 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001751 }
1752
1753 /* Add all table columns to the PRIMARY KEY index
1754 */
1755 if( nPk<pTab->nCol ){
1756 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1757 for(i=0, j=nPk; i<pTab->nCol; i++){
1758 if( !hasColumn(pPk->aiColumn, j, i) ){
1759 assert( j<pPk->nColumn );
1760 pPk->aiColumn[j] = i;
1761 pPk->azColl[j] = "BINARY";
1762 j++;
1763 }
1764 }
1765 assert( pPk->nColumn==j );
1766 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001767 }else{
1768 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001769 }
1770}
1771
drhfdaac672013-10-04 15:30:21 +00001772/*
drh75897232000-05-29 14:26:00 +00001773** This routine is called to report the final ")" that terminates
1774** a CREATE TABLE statement.
1775**
drhf57b3392001-10-08 13:22:32 +00001776** The table structure that other action routines have been building
1777** is added to the internal hash tables, assuming no errors have
1778** occurred.
drh75897232000-05-29 14:26:00 +00001779**
drh1d85d932004-02-14 23:05:52 +00001780** An entry for the table is made in the master table on disk, unless
1781** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001782** it means we are reading the sqlite_master table because we just
1783** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001784** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001785** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001786**
1787** If the pSelect argument is not NULL, it means that this routine
1788** was called to create a table generated from a
1789** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1790** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001791*/
danielk197719a8e7e2005-03-17 05:03:38 +00001792void sqlite3EndTable(
1793 Parse *pParse, /* Parse context */
1794 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001795 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1796 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001797 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1798){
drhfdaac672013-10-04 15:30:21 +00001799 Table *p; /* The new table */
1800 sqlite3 *db = pParse->db; /* The database connection */
1801 int iDb; /* Database in which the table lives */
1802 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001803
drh5969da42013-10-21 02:14:45 +00001804 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1805 return;
danielk1977261919c2005-12-06 12:52:59 +00001806 }
drh28037572000-08-02 13:47:41 +00001807 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001808 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001809
danielk1977517eb642004-06-07 10:00:31 +00001810 assert( !db->init.busy || !pSelect );
1811
drhc6bd4e42013-11-02 14:37:18 +00001812 /* If the db->init.busy is 1 it means we are reading the SQL off the
1813 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1814 ** So do not write to the disk again. Extract the root page number
1815 ** for the table from the db->init.newTnum field. (The page number
1816 ** should have been put there by the sqliteOpenCb routine.)
1817 */
1818 if( db->init.busy ){
1819 p->tnum = db->init.newTnum;
1820 }
1821
1822 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001823 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001824 if( (p->tabFlags & TF_Autoincrement) ){
1825 sqlite3ErrorMsg(pParse,
1826 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1827 return;
1828 }
drh5969da42013-10-21 02:14:45 +00001829 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001830 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001831 }else{
1832 p->tabFlags |= TF_WithoutRowid;
1833 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001834 }
1835 }
1836
drhb9bb7c12006-06-11 23:41:55 +00001837 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001838
drhffe07b22005-11-03 00:41:17 +00001839#ifndef SQLITE_OMIT_CHECK
1840 /* Resolve names in all CHECK constraint expressions.
1841 */
1842 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001843 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001844 }
1845#endif /* !defined(SQLITE_OMIT_CHECK) */
1846
drhe13e9f52013-10-05 19:18:00 +00001847 /* Estimate the average row size for the table and for all implied indices */
1848 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001849 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001850 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001851 }
1852
drhe3c41372001-09-17 20:25:58 +00001853 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001854 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001855 **
drhe0bc4042002-06-25 01:09:11 +00001856 ** If this is a TEMPORARY table, write the entry into the auxiliary
1857 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001858 */
drh1d85d932004-02-14 23:05:52 +00001859 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001860 int n;
drhd8bc7082000-06-07 23:51:50 +00001861 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001862 char *zType; /* "view" or "table" */
1863 char *zType2; /* "VIEW" or "TABLE" */
1864 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001865
danielk19774adee202004-05-08 08:23:19 +00001866 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001867 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001868
drh66a51672008-01-03 00:01:23 +00001869 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001870
drh0fa991b2009-03-21 16:19:26 +00001871 /*
1872 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001873 */
drh4ff6dfa2002-03-03 23:06:00 +00001874 if( p->pSelect==0 ){
1875 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001876 zType = "table";
1877 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001878#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001879 }else{
1880 /* A view */
drh4794f732004-11-05 17:17:50 +00001881 zType = "view";
1882 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001883#endif
drh4ff6dfa2002-03-03 23:06:00 +00001884 }
danielk1977517eb642004-06-07 10:00:31 +00001885
danielk1977517eb642004-06-07 10:00:31 +00001886 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1887 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001888 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001889 **
1890 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1891 ** suitable state to query for the column names and types to be used
1892 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001893 **
1894 ** A shared-cache write-lock is not required to write to the new table,
1895 ** as a schema-lock must have already been obtained to create it. Since
1896 ** a schema-lock excludes all other database users, the write-lock would
1897 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001898 */
1899 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001900 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001901 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001902
danielk19776ab3a2e2009-02-19 14:39:25 +00001903 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001904 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001905 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001906 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001907 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001908 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001909 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001910 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001911 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001912 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001913 assert( p->aCol==0 );
1914 p->nCol = pSelTab->nCol;
1915 p->aCol = pSelTab->aCol;
1916 pSelTab->nCol = 0;
1917 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001918 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001919 }
1920 }
drh4794f732004-11-05 17:17:50 +00001921
drh4794f732004-11-05 17:17:50 +00001922 /* Compute the complete text of the CREATE statement */
1923 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001924 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001925 }else{
drh8ea30bf2013-10-22 01:18:17 +00001926 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1927 n = (int)(pEnd2->z - pParse->sNameToken.z);
1928 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001929 zStmt = sqlite3MPrintf(db,
1930 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1931 );
drh4794f732004-11-05 17:17:50 +00001932 }
1933
1934 /* A slot for the record has already been allocated in the
1935 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001936 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001937 */
1938 sqlite3NestedParse(pParse,
1939 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001940 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1941 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001942 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001943 zType,
1944 p->zName,
1945 p->zName,
drhb7654112008-01-12 12:48:07 +00001946 pParse->regRoot,
1947 zStmt,
1948 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001949 );
drh633e6d52008-07-28 19:34:53 +00001950 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001951 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001952
1953#ifndef SQLITE_OMIT_AUTOINCREMENT
1954 /* Check to see if we need to create an sqlite_sequence table for
1955 ** keeping track of autoincrement keys.
1956 */
drh7d10d5a2008-08-20 16:35:10 +00001957 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001958 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001959 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001960 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001961 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001962 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1963 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001964 );
1965 }
1966 }
1967#endif
drh4794f732004-11-05 17:17:50 +00001968
1969 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001970 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001971 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001972 }
drh17e9e292003-02-01 13:53:28 +00001973
drh2958a4e2004-11-12 03:56:15 +00001974
drh17e9e292003-02-01 13:53:28 +00001975 /* Add the table to the in-memory representation of the database.
1976 */
drh8af73d42009-05-13 22:58:28 +00001977 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001978 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001979 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001980 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00001981 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00001982 if( pOld ){
1983 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001984 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001985 return;
drh17e9e292003-02-01 13:53:28 +00001986 }
drh17e9e292003-02-01 13:53:28 +00001987 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001988 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001989
1990#ifndef SQLITE_OMIT_ALTERTABLE
1991 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001992 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001993 int nName;
drh5969da42013-10-21 02:14:45 +00001994 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001995 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00001996 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00001997 }
drh1bd10f82008-12-10 21:19:56 +00001998 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001999 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002000 }
2001#endif
drh17e9e292003-02-01 13:53:28 +00002002 }
drh75897232000-05-29 14:26:00 +00002003}
2004
drhb7f91642004-10-31 02:22:47 +00002005#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002006/*
drha76b5df2002-02-23 02:32:10 +00002007** The parser calls this routine in order to create a new VIEW
2008*/
danielk19774adee202004-05-08 08:23:19 +00002009void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002010 Parse *pParse, /* The parsing context */
2011 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002012 Token *pName1, /* The token that holds the name of the view */
2013 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002014 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002015 int isTemp, /* TRUE for a TEMPORARY view */
2016 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002017){
drha76b5df2002-02-23 02:32:10 +00002018 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002019 int n;
drhb7916a72009-05-27 10:31:29 +00002020 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002021 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002022 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002023 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002024 int iDb;
drh17435752007-08-16 04:30:38 +00002025 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002026
drh7c3d64f2005-06-06 15:32:08 +00002027 if( pParse->nVar>0 ){
2028 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002029 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002030 return;
2031 }
drhfdd48a72006-09-11 23:45:48 +00002032 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002033 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002034 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002035 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002036 return;
2037 }
danielk1977ef2cb632004-05-29 02:37:19 +00002038 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002039 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002040 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2041 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002042 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002043 return;
2044 }
drh174b6192002-12-03 02:22:52 +00002045
drh4b59ab52002-08-24 18:24:51 +00002046 /* Make a copy of the entire SELECT statement that defines the view.
2047 ** This will force all the Expr.token.z values to be dynamically
2048 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002049 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002050 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002051 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002052 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002053 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002054 return;
2055 }
drh17435752007-08-16 04:30:38 +00002056 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002057 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002058 }
drh4b59ab52002-08-24 18:24:51 +00002059
2060 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2061 ** the end.
2062 */
drha76b5df2002-02-23 02:32:10 +00002063 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002064 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002065 sEnd.z += sEnd.n;
2066 }
2067 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002068 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002069 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002070 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002071 sEnd.z = &z[n-1];
2072 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002073
danielk19774adee202004-05-08 08:23:19 +00002074 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002075 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002076 return;
drh417be792002-03-03 18:59:40 +00002077}
drhb7f91642004-10-31 02:22:47 +00002078#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002079
danielk1977fe3fcbe22006-06-12 12:08:45 +00002080#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002081/*
2082** The Table structure pTable is really a VIEW. Fill in the names of
2083** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002084** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002085*/
danielk19774adee202004-05-08 08:23:19 +00002086int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002087 Table *pSelTab; /* A fake table from which we get the result set */
2088 Select *pSel; /* Copy of the SELECT that implements the view */
2089 int nErr = 0; /* Number of errors encountered */
2090 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002091 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002092 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002093
2094 assert( pTable );
2095
danielk1977fe3fcbe22006-06-12 12:08:45 +00002096#ifndef SQLITE_OMIT_VIRTUALTABLE
2097 if( sqlite3VtabCallConnect(pParse, pTable) ){
2098 return SQLITE_ERROR;
2099 }
drh4cbdda92006-06-14 19:00:20 +00002100 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002101#endif
2102
2103#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002104 /* A positive nCol means the columns names for this view are
2105 ** already known.
2106 */
2107 if( pTable->nCol>0 ) return 0;
2108
2109 /* A negative nCol is a special marker meaning that we are currently
2110 ** trying to compute the column names. If we enter this routine with
2111 ** a negative nCol, it means two or more views form a loop, like this:
2112 **
2113 ** CREATE VIEW one AS SELECT * FROM two;
2114 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002115 **
drh768578e2009-05-12 00:40:12 +00002116 ** Actually, the error above is now caught prior to reaching this point.
2117 ** But the following test is still important as it does come up
2118 ** in the following:
2119 **
2120 ** CREATE TABLE main.ex1(a);
2121 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2122 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002123 */
2124 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002125 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002126 return 1;
2127 }
drh85c23c62005-08-20 03:03:04 +00002128 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002129
2130 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002131 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2132 ** "*" elements in the results set of the view and will assign cursors
2133 ** to the elements of the FROM clause. But we do not want these changes
2134 ** to be permanent. So the computation is done on a copy of the SELECT
2135 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002136 */
drh9b3187e2005-01-18 14:45:47 +00002137 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002138 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002139 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002140 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002141 n = pParse->nTab;
2142 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2143 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002144 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002145#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002146 xAuth = db->xAuth;
2147 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002148 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002149 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002150#else
drh7d10d5a2008-08-20 16:35:10 +00002151 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002152#endif
drhd9da78a2009-03-24 15:08:09 +00002153 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002154 pParse->nTab = n;
2155 if( pSelTab ){
2156 assert( pTable->aCol==0 );
2157 pTable->nCol = pSelTab->nCol;
2158 pTable->aCol = pSelTab->aCol;
2159 pSelTab->nCol = 0;
2160 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002161 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002162 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002163 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002164 }else{
2165 pTable->nCol = 0;
2166 nErr++;
2167 }
drh633e6d52008-07-28 19:34:53 +00002168 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002169 } else {
drh417be792002-03-03 18:59:40 +00002170 nErr++;
2171 }
drhb7f91642004-10-31 02:22:47 +00002172#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002173 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002174}
2175#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002176
drhb7f91642004-10-31 02:22:47 +00002177#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002178/*
drh8bf8dc92003-05-17 17:35:10 +00002179** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002180*/
drh9bb575f2004-09-06 17:24:11 +00002181static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002182 HashElem *i;
drh21206082011-04-04 18:22:02 +00002183 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002184 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002185 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002186 Table *pTab = sqliteHashData(i);
2187 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002188 sqliteDeleteColumnNames(db, pTab);
2189 pTab->aCol = 0;
2190 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002191 }
2192 }
drh8bf8dc92003-05-17 17:35:10 +00002193 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002194}
drhb7f91642004-10-31 02:22:47 +00002195#else
2196# define sqliteViewResetAll(A,B)
2197#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002198
drh75897232000-05-29 14:26:00 +00002199/*
danielk1977a0bf2652004-11-04 14:30:04 +00002200** This function is called by the VDBE to adjust the internal schema
2201** used by SQLite when the btree layer moves a table root page. The
2202** root-page of a table or index in database iDb has changed from iFrom
2203** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002204**
2205** Ticket #1728: The symbol table might still contain information
2206** on tables and/or indices that are the process of being deleted.
2207** If you are unlucky, one of those deleted indices or tables might
2208** have the same rootpage number as the real table or index that is
2209** being moved. So we cannot stop searching after the first match
2210** because the first match might be for one of the deleted indices
2211** or tables and not the table/index that is actually being moved.
2212** We must continue looping until all tables and indices with
2213** rootpage==iFrom have been converted to have a rootpage of iTo
2214** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002215*/
2216#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002217void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002218 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002219 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002220 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002221
drhcdf011d2011-04-04 21:25:28 +00002222 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2223 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002224 pHash = &pDb->pSchema->tblHash;
2225 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002226 Table *pTab = sqliteHashData(pElem);
2227 if( pTab->tnum==iFrom ){
2228 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002229 }
2230 }
danielk1977da184232006-01-05 11:34:32 +00002231 pHash = &pDb->pSchema->idxHash;
2232 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002233 Index *pIdx = sqliteHashData(pElem);
2234 if( pIdx->tnum==iFrom ){
2235 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002236 }
2237 }
danielk1977a0bf2652004-11-04 14:30:04 +00002238}
2239#endif
2240
2241/*
2242** Write code to erase the table with root-page iTable from database iDb.
2243** Also write code to modify the sqlite_master table and internal schema
2244** if a root-page of another table is moved by the btree-layer whilst
2245** erasing iTable (this can happen with an auto-vacuum database).
2246*/
drh4e0cff62004-11-05 05:10:28 +00002247static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2248 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002249 int r1 = sqlite3GetTempReg(pParse);
2250 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002251 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002252#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002253 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002254 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002255 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002256 ** reflect this.
2257 **
drh0fa991b2009-03-21 16:19:26 +00002258 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002259 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2260 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002261 */
danielk197763e3e9f2004-11-05 09:19:27 +00002262 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002263 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2264 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002265#endif
drhb7654112008-01-12 12:48:07 +00002266 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002267}
2268
2269/*
2270** Write VDBE code to erase table pTab and all associated indices on disk.
2271** Code to update the sqlite_master tables and internal schema definitions
2272** in case a root-page belonging to another table is moved by the btree layer
2273** is also added (this can happen with an auto-vacuum database).
2274*/
drh4e0cff62004-11-05 05:10:28 +00002275static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002276#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002277 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002278 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2279 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002280 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002281 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002282 }
2283#else
2284 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2285 ** is not defined), then it is important to call OP_Destroy on the
2286 ** table and index root-pages in order, starting with the numerically
2287 ** largest root-page number. This guarantees that none of the root-pages
2288 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2289 ** following were coded:
2290 **
2291 ** OP_Destroy 4 0
2292 ** ...
2293 ** OP_Destroy 5 0
2294 **
2295 ** and root page 5 happened to be the largest root-page number in the
2296 ** database, then root page 5 would be moved to page 4 by the
2297 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2298 ** a free-list page.
2299 */
2300 int iTab = pTab->tnum;
2301 int iDestroyed = 0;
2302
2303 while( 1 ){
2304 Index *pIdx;
2305 int iLargest = 0;
2306
2307 if( iDestroyed==0 || iTab<iDestroyed ){
2308 iLargest = iTab;
2309 }
2310 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2311 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002312 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002313 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2314 iLargest = iIdx;
2315 }
2316 }
danielk1977da184232006-01-05 11:34:32 +00002317 if( iLargest==0 ){
2318 return;
2319 }else{
2320 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002321 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002322 destroyRootPage(pParse, iLargest, iDb);
2323 iDestroyed = iLargest;
2324 }
danielk1977a0bf2652004-11-04 14:30:04 +00002325 }
2326#endif
2327}
2328
2329/*
drh74e7c8f2011-10-21 19:06:32 +00002330** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002331** after a DROP INDEX or DROP TABLE command.
2332*/
2333static void sqlite3ClearStatTables(
2334 Parse *pParse, /* The parsing context */
2335 int iDb, /* The database number */
2336 const char *zType, /* "idx" or "tbl" */
2337 const char *zName /* Name of index or table */
2338){
drha5ae4c32011-08-07 01:31:52 +00002339 int i;
2340 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002341 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002342 char zTab[24];
2343 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2344 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002345 sqlite3NestedParse(pParse,
2346 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002347 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002348 );
2349 }
2350 }
2351}
2352
2353/*
drhfaacf172011-08-12 01:51:45 +00002354** Generate code to drop a table.
2355*/
2356void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2357 Vdbe *v;
2358 sqlite3 *db = pParse->db;
2359 Trigger *pTrigger;
2360 Db *pDb = &db->aDb[iDb];
2361
2362 v = sqlite3GetVdbe(pParse);
2363 assert( v!=0 );
2364 sqlite3BeginWriteOperation(pParse, 1, iDb);
2365
2366#ifndef SQLITE_OMIT_VIRTUALTABLE
2367 if( IsVirtual(pTab) ){
2368 sqlite3VdbeAddOp0(v, OP_VBegin);
2369 }
2370#endif
2371
2372 /* Drop all triggers associated with the table being dropped. Code
2373 ** is generated to remove entries from sqlite_master and/or
2374 ** sqlite_temp_master if required.
2375 */
2376 pTrigger = sqlite3TriggerList(pParse, pTab);
2377 while( pTrigger ){
2378 assert( pTrigger->pSchema==pTab->pSchema ||
2379 pTrigger->pSchema==db->aDb[1].pSchema );
2380 sqlite3DropTriggerPtr(pParse, pTrigger);
2381 pTrigger = pTrigger->pNext;
2382 }
2383
2384#ifndef SQLITE_OMIT_AUTOINCREMENT
2385 /* Remove any entries of the sqlite_sequence table associated with
2386 ** the table being dropped. This is done before the table is dropped
2387 ** at the btree level, in case the sqlite_sequence table needs to
2388 ** move as a result of the drop (can happen in auto-vacuum mode).
2389 */
2390 if( pTab->tabFlags & TF_Autoincrement ){
2391 sqlite3NestedParse(pParse,
2392 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2393 pDb->zName, pTab->zName
2394 );
2395 }
2396#endif
2397
2398 /* Drop all SQLITE_MASTER table and index entries that refer to the
2399 ** table. The program name loops through the master table and deletes
2400 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002401 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002402 ** created in the temp database that refers to a table in another
2403 ** database.
2404 */
2405 sqlite3NestedParse(pParse,
2406 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2407 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002408 if( !isView && !IsVirtual(pTab) ){
2409 destroyTable(pParse, pTab);
2410 }
2411
2412 /* Remove the table entry from SQLite's internal schema and modify
2413 ** the schema cookie.
2414 */
2415 if( IsVirtual(pTab) ){
2416 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2417 }
2418 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2419 sqlite3ChangeCookie(pParse, iDb);
2420 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002421}
2422
2423/*
drh75897232000-05-29 14:26:00 +00002424** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002425** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002426*/
drha0733842005-12-29 01:11:36 +00002427void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002428 Table *pTab;
drh75897232000-05-29 14:26:00 +00002429 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002430 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002431 int iDb;
drh75897232000-05-29 14:26:00 +00002432
drh8af73d42009-05-13 22:58:28 +00002433 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002434 goto exit_drop_table;
2435 }
drh8af73d42009-05-13 22:58:28 +00002436 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002437 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002438 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002439 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002440 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002441
drha0733842005-12-29 01:11:36 +00002442 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002443 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002444 goto exit_drop_table;
2445 }
danielk1977da184232006-01-05 11:34:32 +00002446 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002447 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002448
2449 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2450 ** it is initialized.
2451 */
2452 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2453 goto exit_drop_table;
2454 }
drhe5f9c642003-01-13 23:27:31 +00002455#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002456 {
2457 int code;
danielk1977da184232006-01-05 11:34:32 +00002458 const char *zTab = SCHEMA_TABLE(iDb);
2459 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002460 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002461 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002462 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002463 }
drhe5f9c642003-01-13 23:27:31 +00002464 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002465 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002466 code = SQLITE_DROP_TEMP_VIEW;
2467 }else{
2468 code = SQLITE_DROP_VIEW;
2469 }
danielk19774b2688a2006-06-20 11:01:07 +00002470#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002471 }else if( IsVirtual(pTab) ){
2472 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002473 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002474#endif
drhe5f9c642003-01-13 23:27:31 +00002475 }else{
danielk197753c0f742005-03-29 03:10:59 +00002476 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002477 code = SQLITE_DROP_TEMP_TABLE;
2478 }else{
2479 code = SQLITE_DROP_TABLE;
2480 }
2481 }
danielk1977f1a381e2006-06-16 08:01:02 +00002482 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002483 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002484 }
danielk1977a8858102004-05-28 12:11:21 +00002485 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2486 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002487 }
drhe5f9c642003-01-13 23:27:31 +00002488 }
2489#endif
drh08ccfaa2011-10-07 23:52:25 +00002490 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2491 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002492 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002493 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002494 }
danielk1977576ec6b2005-01-21 11:55:25 +00002495
2496#ifndef SQLITE_OMIT_VIEW
2497 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2498 ** on a table.
2499 */
danielk1977a8858102004-05-28 12:11:21 +00002500 if( isView && pTab->pSelect==0 ){
2501 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2502 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002503 }
danielk1977a8858102004-05-28 12:11:21 +00002504 if( !isView && pTab->pSelect ){
2505 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2506 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002507 }
danielk1977576ec6b2005-01-21 11:55:25 +00002508#endif
drh75897232000-05-29 14:26:00 +00002509
drh1ccde152000-06-17 13:12:39 +00002510 /* Generate code to remove the table from the master table
2511 ** on disk.
2512 */
danielk19774adee202004-05-08 08:23:19 +00002513 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002514 if( v ){
drh77658e22007-12-04 16:54:52 +00002515 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002516 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002517 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002518 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002519 }
danielk1977a8858102004-05-28 12:11:21 +00002520
2521exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002522 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002523}
2524
2525/*
drhc2eef3b2002-08-31 18:53:06 +00002526** This routine is called to create a new foreign key on the table
2527** currently under construction. pFromCol determines which columns
2528** in the current table point to the foreign key. If pFromCol==0 then
2529** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002530** the table referred to (a.k.a the "parent" table). pToCol is a list
2531** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002532** information about the conflict resolution algorithms specified
2533** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2534**
2535** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002536** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002537**
2538** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002539** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002540*/
danielk19774adee202004-05-08 08:23:19 +00002541void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002542 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002543 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002544 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002545 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002546 int flags /* Conflict resolution algorithms. */
2547){
danielk197718576932008-08-06 13:47:40 +00002548 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002549#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002550 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002551 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002552 Table *p = pParse->pNewTable;
2553 int nByte;
2554 int i;
2555 int nCol;
2556 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002557
2558 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002559 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002560 if( pFromCol==0 ){
2561 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002562 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002563 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002564 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002565 " should reference only one column of table %T",
2566 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002567 goto fk_end;
2568 }
2569 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002570 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002571 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002572 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002573 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002574 goto fk_end;
2575 }else{
danielk19770202b292004-06-09 09:55:16 +00002576 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002577 }
drhe61922a2009-05-02 13:29:37 +00002578 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002579 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002580 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002581 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002582 }
2583 }
drh633e6d52008-07-28 19:34:53 +00002584 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002585 if( pFKey==0 ){
2586 goto fk_end;
2587 }
drhc2eef3b2002-08-31 18:53:06 +00002588 pFKey->pFrom = p;
2589 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002590 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002591 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002592 memcpy(z, pTo->z, pTo->n);
2593 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002594 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002595 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002596 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002597 if( pFromCol==0 ){
2598 pFKey->aCol[0].iFrom = p->nCol-1;
2599 }else{
2600 for(i=0; i<nCol; i++){
2601 int j;
2602 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002603 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002604 pFKey->aCol[i].iFrom = j;
2605 break;
2606 }
2607 }
2608 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002609 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002610 "unknown column \"%s\" in foreign key definition",
2611 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002612 goto fk_end;
2613 }
2614 }
2615 }
2616 if( pToCol ){
2617 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002618 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002619 pFKey->aCol[i].zCol = z;
2620 memcpy(z, pToCol->a[i].zName, n);
2621 z[n] = 0;
2622 z += n+1;
2623 }
2624 }
2625 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002626 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2627 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002628
drh21206082011-04-04 18:22:02 +00002629 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002630 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002631 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002632 );
danf59c5ca2009-09-22 16:55:38 +00002633 if( pNextTo==pFKey ){
2634 db->mallocFailed = 1;
2635 goto fk_end;
2636 }
dan1da40a32009-09-19 17:00:31 +00002637 if( pNextTo ){
2638 assert( pNextTo->pPrevTo==0 );
2639 pFKey->pNextTo = pNextTo;
2640 pNextTo->pPrevTo = pFKey;
2641 }
2642
drhc2eef3b2002-08-31 18:53:06 +00002643 /* Link the foreign key to the table as the last step.
2644 */
2645 p->pFKey = pFKey;
2646 pFKey = 0;
2647
2648fk_end:
drh633e6d52008-07-28 19:34:53 +00002649 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002650#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002651 sqlite3ExprListDelete(db, pFromCol);
2652 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002653}
2654
2655/*
2656** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2657** clause is seen as part of a foreign key definition. The isDeferred
2658** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2659** The behavior of the most recently created foreign key is adjusted
2660** accordingly.
2661*/
danielk19774adee202004-05-08 08:23:19 +00002662void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002663#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002664 Table *pTab;
2665 FKey *pFKey;
2666 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002667 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002668 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002669#endif
drhc2eef3b2002-08-31 18:53:06 +00002670}
2671
2672/*
drh063336a2004-11-05 20:58:39 +00002673** Generate code that will erase and refill index *pIdx. This is
2674** used to initialize a newly created index or to recompute the
2675** content of an index in response to a REINDEX command.
2676**
2677** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002678** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002679** root page number of the index. If memRootPage is negative, then
2680** the index already exists and must be cleared before being refilled and
2681** the root page number of the index is taken from pIndex->tnum.
2682*/
2683static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2684 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002685 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2686 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002687 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002688 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002689 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002690 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002691 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002692 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002693 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002694 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002695 sqlite3 *db = pParse->db; /* The database connection */
2696 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002697
danielk19771d54df82004-11-23 15:41:16 +00002698#ifndef SQLITE_OMIT_AUTHORIZATION
2699 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002700 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002701 return;
2702 }
2703#endif
2704
danielk1977c00da102006-01-07 13:21:04 +00002705 /* Require a write-lock on the table to perform this operation */
2706 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2707
drh063336a2004-11-05 20:58:39 +00002708 v = sqlite3GetVdbe(pParse);
2709 if( v==0 ) return;
2710 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002711 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002712 }else{
2713 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002714 }
drh2ec2fb22013-11-06 19:59:23 +00002715 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002716
dan689ab892011-08-12 15:02:00 +00002717 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002718 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002719 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002720 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002721
2722 /* Open the table. Loop through all rows of the table, inserting index
2723 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002724 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002725 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002726 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002727
drh1c2c0b72014-01-04 19:27:05 +00002728 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002729 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002730 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002731 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002732 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002733 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2734 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002735 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002736 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2737
drh688852a2014-02-17 22:40:43 +00002738 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002739 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002740 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002741 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2742 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2743 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002744 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002745 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002746 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002747 }else{
2748 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002749 }
drh6cf4a7d2014-10-13 13:00:58 +00002750 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
drhca892a72011-09-03 00:17:51 +00002751 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2752 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002753 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002754 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002755 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002756
drh66a51672008-01-03 00:01:23 +00002757 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2758 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002759 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002760}
2761
2762/*
drh77e57df2013-10-22 14:28:02 +00002763** Allocate heap space to hold an Index object with nCol columns.
2764**
2765** Increase the allocation size to provide an extra nExtra bytes
2766** of 8-byte aligned space after the Index object and return a
2767** pointer to this extra space in *ppExtra.
2768*/
2769Index *sqlite3AllocateIndexObject(
2770 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002771 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002772 int nExtra, /* Number of bytes of extra space to alloc */
2773 char **ppExtra /* Pointer to the "extra" space */
2774){
2775 Index *p; /* Allocated index object */
2776 int nByte; /* Bytes of space for Index object + arrays */
2777
2778 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2779 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002780 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002781 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002782 sizeof(u8)*nCol); /* Index.aSortOrder */
2783 p = sqlite3DbMallocZero(db, nByte + nExtra);
2784 if( p ){
2785 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002786 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2787 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2788 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002789 p->aSortOrder = (u8*)pExtra;
2790 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002791 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002792 *ppExtra = ((char*)p) + nByte;
2793 }
2794 return p;
2795}
2796
2797/*
drh23bf66d2004-12-14 03:34:34 +00002798** Create a new index for an SQL table. pName1.pName2 is the name of the index
2799** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002800** be NULL for a primary key or an index that is created to satisfy a
2801** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002802** as the table to be indexed. pParse->pNewTable is a table that is
2803** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002804**
drh382c0242001-10-06 16:33:02 +00002805** pList is a list of columns to be indexed. pList will be NULL if this
2806** is a primary key or unique-constraint on the most recent column added
2807** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002808**
2809** If the index is created successfully, return a pointer to the new Index
2810** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002811** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002812*/
dan1da40a32009-09-19 17:00:31 +00002813Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002814 Parse *pParse, /* All information about this parse */
2815 Token *pName1, /* First part of index name. May be NULL */
2816 Token *pName2, /* Second part of index name. May be NULL */
2817 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002818 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002819 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002820 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002821 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002822 int sortOrder, /* Sort order of primary key when pList==NULL */
2823 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002824){
dan1da40a32009-09-19 17:00:31 +00002825 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002826 Table *pTab = 0; /* Table to be indexed */
2827 Index *pIndex = 0; /* The index to be created */
2828 char *zName = 0; /* Name of the index */
2829 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002830 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002831 DbFixer sFix; /* For assigning database names to pTable */
2832 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002833 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002834 Db *pDb; /* The specific table containing the indexed database */
2835 int iDb; /* Index of the database that is being written */
2836 Token *pName = 0; /* Unqualified name of the index to create */
2837 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002838 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002839 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002840 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002841 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002842 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002843
drh8af73d42009-05-13 22:58:28 +00002844 assert( pParse->nErr==0 ); /* Never called with prior errors */
2845 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002846 goto exit_create_index;
2847 }
2848 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002849 goto exit_create_index;
2850 }
drhdaffd0e2001-04-11 14:28:42 +00002851
drh75897232000-05-29 14:26:00 +00002852 /*
2853 ** Find the table that is to be indexed. Return early if not found.
2854 */
danielk1977cbb18d22004-05-28 11:37:27 +00002855 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002856
2857 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002858 ** to search for the table. 'Fix' the table name to this db
2859 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002860 */
2861 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002862 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002863 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002864 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002865
danielk197753c0f742005-03-29 03:10:59 +00002866#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002867 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002868 ** is a temp table. If so, set the database to 1. Do not do this
2869 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002870 */
danielk1977fe910332007-12-02 11:46:34 +00002871 if( !db->init.busy ){
2872 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002873 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002874 iDb = 1;
2875 }
danielk1977ef2cb632004-05-29 02:37:19 +00002876 }
danielk197753c0f742005-03-29 03:10:59 +00002877#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002878
drhd100f692013-10-03 15:39:44 +00002879 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2880 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002881 /* Because the parser constructs pTblName from a single identifier,
2882 ** sqlite3FixSrcList can never fail. */
2883 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002884 }
dan41fb5cd2012-10-04 19:33:00 +00002885 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002886 assert( db->mallocFailed==0 || pTab==0 );
2887 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002888 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2889 sqlite3ErrorMsg(pParse,
2890 "cannot create a TEMP index on non-TEMP table \"%s\"",
2891 pTab->zName);
2892 goto exit_create_index;
2893 }
drh44156282013-10-23 22:23:03 +00002894 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002895 }else{
drhe3c41372001-09-17 20:25:58 +00002896 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002897 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002898 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002899 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002900 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002901 }
drhfdd6e852005-12-16 01:06:16 +00002902 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002903
drhd3001712009-05-12 17:46:53 +00002904 assert( pTab!=0 );
2905 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002906 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002907 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002908#if SQLITE_USER_AUTHENTICATION
2909 && sqlite3UserAuthTable(pTab->zName)==0
2910#endif
drh503a6862013-03-01 01:07:17 +00002911 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002912 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002913 goto exit_create_index;
2914 }
danielk1977576ec6b2005-01-21 11:55:25 +00002915#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002916 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002917 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002918 goto exit_create_index;
2919 }
danielk1977576ec6b2005-01-21 11:55:25 +00002920#endif
danielk19775ee9d692006-06-21 12:36:25 +00002921#ifndef SQLITE_OMIT_VIRTUALTABLE
2922 if( IsVirtual(pTab) ){
2923 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2924 goto exit_create_index;
2925 }
2926#endif
drh75897232000-05-29 14:26:00 +00002927
2928 /*
2929 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002930 ** index or table with the same name.
2931 **
2932 ** Exception: If we are reading the names of permanent indices from the
2933 ** sqlite_master table (because some other process changed the schema) and
2934 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002935 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002936 **
2937 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002938 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2939 ** own name.
drh75897232000-05-29 14:26:00 +00002940 */
danielk1977d8123362004-06-12 09:25:12 +00002941 if( pName ){
drh17435752007-08-16 04:30:38 +00002942 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002943 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002944 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002945 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002946 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002947 }
danielk1977d8123362004-06-12 09:25:12 +00002948 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002949 if( sqlite3FindTable(db, zName, 0)!=0 ){
2950 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2951 goto exit_create_index;
2952 }
2953 }
danielk197759a33f92007-03-17 10:26:59 +00002954 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2955 if( !ifNotExist ){
2956 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002957 }else{
2958 assert( !db->init.busy );
2959 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002960 }
danielk197759a33f92007-03-17 10:26:59 +00002961 goto exit_create_index;
2962 }
danielk1977a21c6b62005-01-24 10:25:59 +00002963 }else{
drhadbca9c2001-09-27 15:11:53 +00002964 int n;
2965 Index *pLoop;
2966 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002967 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002968 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002969 goto exit_create_index;
2970 }
drh75897232000-05-29 14:26:00 +00002971 }
2972
drhe5f9c642003-01-13 23:27:31 +00002973 /* Check for authorization to create an index.
2974 */
2975#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002976 {
drhfdd6e852005-12-16 01:06:16 +00002977 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002978 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002979 goto exit_create_index;
2980 }
2981 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002982 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002983 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002984 goto exit_create_index;
2985 }
drhe5f9c642003-01-13 23:27:31 +00002986 }
2987#endif
2988
drh75897232000-05-29 14:26:00 +00002989 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002990 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002991 ** So create a fake list to simulate this.
2992 */
2993 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002994 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002995 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002996 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
2997 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00002998 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002999 }
3000
danielk1977b3bf5562006-01-10 17:58:23 +00003001 /* Figure out how many bytes of space are required to store explicitly
3002 ** specified collation sequence names.
3003 */
3004 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003005 Expr *pExpr = pList->a[i].pExpr;
3006 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00003007 assert( pExpr->op==TK_COLLATE );
3008 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003009 }
3010 }
3011
drh75897232000-05-29 14:26:00 +00003012 /*
3013 ** Allocate the index structure.
3014 */
drhea678832008-12-10 19:26:22 +00003015 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003016 nExtraCol = pPk ? pPk->nKeyCol : 1;
3017 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003018 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003019 if( db->mallocFailed ){
3020 goto exit_create_index;
3021 }
dancfc9df72014-04-25 15:01:01 +00003022 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003023 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003024 pIndex->zName = zExtra;
3025 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003026 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003027 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003028 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003029 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003030 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003031 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003032 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003033 if( pPIWhere ){
3034 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3035 pIndex->pPartIdxWhere = pPIWhere;
3036 pPIWhere = 0;
3037 }
drh21206082011-04-04 18:22:02 +00003038 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003039
drhfdd6e852005-12-16 01:06:16 +00003040 /* Check to see if we should honor DESC requests on index columns
3041 */
danielk1977da184232006-01-05 11:34:32 +00003042 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003043 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003044 }else{
3045 sortOrderMask = 0; /* Ignore DESC */
3046 }
3047
drh1ccde152000-06-17 13:12:39 +00003048 /* Scan the names of the columns of the table to be indexed and
3049 ** load the column indices into the Index structure. Report an error
3050 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003051 **
3052 ** TODO: Add a test to make sure that the same column is not named
3053 ** more than once within the same index. Only the first instance of
3054 ** the column will ever be used by the optimizer. Note that using the
3055 ** same column more than once cannot be an error because that would
3056 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003057 */
drhfdd6e852005-12-16 01:06:16 +00003058 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3059 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003060 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003061 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003062
drhfdd6e852005-12-16 01:06:16 +00003063 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3064 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003065 }
3066 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003067 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003068 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003069 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003070 goto exit_create_index;
3071 }
drhbf20a352014-04-04 22:44:59 +00003072 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003073 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003074 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003075 int nColl;
dan911ce412013-05-15 15:16:50 +00003076 assert( pListItem->pExpr->op==TK_COLLATE );
3077 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003078 nColl = sqlite3Strlen30(zColl) + 1;
3079 assert( nExtra>=nColl );
3080 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003081 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003082 zExtra += nColl;
3083 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003084 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003085 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003086 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003087 }
drhb7f24de2009-05-13 17:35:23 +00003088 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003089 goto exit_create_index;
3090 }
danielk1977b3bf5562006-01-10 17:58:23 +00003091 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003092 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003093 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003094 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003095 }
drh44156282013-10-23 22:23:03 +00003096 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003097 for(j=0; j<pPk->nKeyCol; j++){
3098 int x = pPk->aiColumn[j];
3099 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3100 pIndex->nColumn--;
3101 }else{
3102 pIndex->aiColumn[i] = x;
3103 pIndex->azColl[i] = pPk->azColl[j];
3104 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3105 i++;
3106 }
drh44156282013-10-23 22:23:03 +00003107 }
drh7913e412013-11-01 20:30:36 +00003108 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003109 }else{
3110 pIndex->aiColumn[i] = -1;
3111 pIndex->azColl[i] = "BINARY";
3112 }
drh51147ba2005-07-23 22:59:55 +00003113 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003114 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003115
danielk1977d8123362004-06-12 09:25:12 +00003116 if( pTab==pParse->pNewTable ){
3117 /* This routine has been called to create an automatic index as a
3118 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3119 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3120 ** i.e. one of:
3121 **
3122 ** CREATE TABLE t(x PRIMARY KEY, y);
3123 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3124 **
3125 ** Either way, check to see if the table already has such an index. If
3126 ** so, don't bother creating this one. This only applies to
3127 ** automatically created indices. Users can do as they wish with
3128 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003129 **
3130 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3131 ** (and thus suppressing the second one) even if they have different
3132 ** sort orders.
3133 **
3134 ** If there are different collating sequences or if the columns of
3135 ** the constraint occur in different orders, then the constraints are
3136 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003137 */
3138 Index *pIdx;
3139 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3140 int k;
drh5f1d1d92014-07-31 22:59:04 +00003141 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003142 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003143 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003144
drhbbbdc832013-10-22 18:01:40 +00003145 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3146 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003147 const char *z1;
3148 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003149 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003150 z1 = pIdx->azColl[k];
3151 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003152 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003153 }
drhbbbdc832013-10-22 18:01:40 +00003154 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003155 if( pIdx->onError!=pIndex->onError ){
3156 /* This constraint creates the same index as a previous
3157 ** constraint specified somewhere in the CREATE TABLE statement.
3158 ** However the ON CONFLICT clauses are different. If both this
3159 ** constraint and the previous equivalent constraint have explicit
3160 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003161 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003162 */
3163 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3164 sqlite3ErrorMsg(pParse,
3165 "conflicting ON CONFLICT clauses specified", 0);
3166 }
3167 if( pIdx->onError==OE_Default ){
3168 pIdx->onError = pIndex->onError;
3169 }
3170 }
danielk1977d8123362004-06-12 09:25:12 +00003171 goto exit_create_index;
3172 }
3173 }
3174 }
3175
drh75897232000-05-29 14:26:00 +00003176 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003177 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003178 */
drh234c39d2004-07-24 03:30:47 +00003179 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003180 Index *p;
drh21206082011-04-04 18:22:02 +00003181 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003182 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003183 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003184 if( p ){
3185 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003186 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003187 goto exit_create_index;
3188 }
drh5e00f6c2001-09-13 13:46:56 +00003189 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003190 if( pTblName!=0 ){
3191 pIndex->tnum = db->init.newTnum;
3192 }
drhd78eeee2001-09-13 16:18:53 +00003193 }
3194
drh58383402013-11-04 17:00:50 +00003195 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3196 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3197 ** emit code to allocate the index rootpage on disk and make an entry for
3198 ** the index in the sqlite_master table and populate the index with
3199 ** content. But, do not do this if we are simply reading the sqlite_master
3200 ** table to parse the schema, or if this index is the PRIMARY KEY index
3201 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003202 **
drh58383402013-11-04 17:00:50 +00003203 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3204 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003205 ** has just been created, it contains no data and the index initialization
3206 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003207 */
drh58383402013-11-04 17:00:50 +00003208 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003209 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003210 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003211 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003212
danielk19774adee202004-05-08 08:23:19 +00003213 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003214 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003215
drhfdd6e852005-12-16 01:06:16 +00003216
drh063336a2004-11-05 20:58:39 +00003217 /* Create the rootpage for the index
3218 */
drhaee128d2005-02-14 20:48:18 +00003219 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003220 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003221
3222 /* Gather the complete text of the CREATE INDEX statement into
3223 ** the zStmt variable
3224 */
drhd3001712009-05-12 17:46:53 +00003225 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003226 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003227 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003228 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003229 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003230 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003231 }else{
3232 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003233 /* zStmt = sqlite3MPrintf(""); */
3234 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003235 }
drh063336a2004-11-05 20:58:39 +00003236
3237 /* Add an entry in sqlite_master for this index
3238 */
3239 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003240 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003241 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3242 pIndex->zName,
3243 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003244 iMem,
drh063336a2004-11-05 20:58:39 +00003245 zStmt
3246 );
drh633e6d52008-07-28 19:34:53 +00003247 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003248
danielk1977a21c6b62005-01-24 10:25:59 +00003249 /* Fill the index with data and reparse the schema. Code an OP_Expire
3250 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003251 */
danielk1977cbb18d22004-05-28 11:37:27 +00003252 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003253 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003254 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003255 sqlite3VdbeAddParseSchemaOp(v, iDb,
3256 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003257 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003258 }
drh75897232000-05-29 14:26:00 +00003259 }
3260
danielk1977d8123362004-06-12 09:25:12 +00003261 /* When adding an index to the list of indices for a table, make
3262 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003263 ** OE_Ignore. This is necessary for the correct constraint check
3264 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3265 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003266 */
drh234c39d2004-07-24 03:30:47 +00003267 if( db->init.busy || pTblName==0 ){
3268 if( onError!=OE_Replace || pTab->pIndex==0
3269 || pTab->pIndex->onError==OE_Replace){
3270 pIndex->pNext = pTab->pIndex;
3271 pTab->pIndex = pIndex;
3272 }else{
3273 Index *pOther = pTab->pIndex;
3274 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3275 pOther = pOther->pNext;
3276 }
3277 pIndex->pNext = pOther->pNext;
3278 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003279 }
dan1da40a32009-09-19 17:00:31 +00003280 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003281 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003282 }
danielk1977d8123362004-06-12 09:25:12 +00003283
drh75897232000-05-29 14:26:00 +00003284 /* Clean up before exiting */
3285exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003286 if( pIndex ) freeIndex(db, pIndex);
3287 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003288 sqlite3ExprListDelete(db, pList);
3289 sqlite3SrcListDelete(db, pTblName);
3290 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003291 return pRet;
drh75897232000-05-29 14:26:00 +00003292}
3293
3294/*
drh51147ba2005-07-23 22:59:55 +00003295** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003296** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003297**
peter.d.reid60ec9142014-09-06 16:39:46 +00003298** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003299** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3300** number of rows in the table that match any particular value of the
3301** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003302** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003303** of the index. And so forth. It must always be the case that
3304*
3305** aiRowEst[N]<=aiRowEst[N-1]
3306** aiRowEst[N]>=1
3307**
3308** Apart from that, we have little to go on besides intuition as to
3309** how aiRowEst[] should be initialized. The numbers generated here
3310** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003311*/
3312void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003313 /* 10, 9, 8, 7, 6 */
3314 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003315 LogEst *a = pIdx->aiRowLogEst;
3316 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003317 int i;
dancfc9df72014-04-25 15:01:01 +00003318
dan264d2b92014-04-29 19:01:57 +00003319 /* Set the first entry (number of rows in the index) to the estimated
3320 ** number of rows in the table. Or 10, if the estimated number of rows
3321 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003322 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003323 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3324
3325 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3326 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003327 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003328 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3329 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003330 }
dan264d2b92014-04-29 19:01:57 +00003331
3332 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003333 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003334}
3335
3336/*
drh74e24cd2002-01-09 03:19:59 +00003337** This routine will drop an existing named index. This routine
3338** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003339*/
drh4d91a702006-01-04 15:54:36 +00003340void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003341 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003342 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003343 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003344 int iDb;
drh75897232000-05-29 14:26:00 +00003345
drh8af73d42009-05-13 22:58:28 +00003346 assert( pParse->nErr==0 ); /* Never called with prior errors */
3347 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003348 goto exit_drop_index;
3349 }
drhd24cc422003-03-27 12:51:24 +00003350 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003351 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3352 goto exit_drop_index;
3353 }
danielk19774adee202004-05-08 08:23:19 +00003354 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003355 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003356 if( !ifExists ){
3357 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003358 }else{
3359 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003360 }
drha6ecd332004-06-10 00:29:09 +00003361 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003362 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003363 }
drh48dd1d82014-05-27 18:18:58 +00003364 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003365 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003366 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003367 goto exit_drop_index;
3368 }
danielk1977da184232006-01-05 11:34:32 +00003369 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003370#ifndef SQLITE_OMIT_AUTHORIZATION
3371 {
3372 int code = SQLITE_DROP_INDEX;
3373 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003374 const char *zDb = db->aDb[iDb].zName;
3375 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003376 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003377 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003378 }
danielk1977da184232006-01-05 11:34:32 +00003379 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003380 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003381 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003382 }
drhed6c8672003-01-12 18:02:16 +00003383 }
drhe5f9c642003-01-13 23:27:31 +00003384#endif
drh75897232000-05-29 14:26:00 +00003385
3386 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003387 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003388 if( v ){
drh77658e22007-12-04 16:54:52 +00003389 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003390 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003391 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003392 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003393 );
drha5ae4c32011-08-07 01:31:52 +00003394 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003395 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003396 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003397 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003398 }
3399
drhd24cc422003-03-27 12:51:24 +00003400exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003401 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003402}
3403
3404/*
dan9ace1122012-03-29 07:51:45 +00003405** pArray is a pointer to an array of objects. Each object in the
3406** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3407** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003408**
dan9ace1122012-03-29 07:51:45 +00003409** When this function is called, *pnEntry contains the current size of
3410** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3411** in total).
drh13449892005-09-07 21:22:45 +00003412**
dan9ace1122012-03-29 07:51:45 +00003413** If the realloc() is successful (i.e. if no OOM condition occurs), the
3414** space allocated for the new object is zeroed, *pnEntry updated to
3415** reflect the new size of the array and a pointer to the new allocation
3416** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003417**
dan9ace1122012-03-29 07:51:45 +00003418** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3419** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003420*/
drhcf643722007-03-27 13:36:37 +00003421void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003422 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003423 void *pArray, /* Array of objects. Might be reallocated */
3424 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003425 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003426 int *pIdx /* Write the index of a new slot here */
3427){
3428 char *z;
drh6c535152012-02-02 03:38:30 +00003429 int n = *pnEntry;
3430 if( (n & (n-1))==0 ){
3431 int sz = (n==0) ? 1 : 2*n;
3432 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003433 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003434 *pIdx = -1;
3435 return pArray;
drh13449892005-09-07 21:22:45 +00003436 }
drhcf643722007-03-27 13:36:37 +00003437 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003438 }
drhcf643722007-03-27 13:36:37 +00003439 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003440 memset(&z[n * szEntry], 0, szEntry);
3441 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003442 ++*pnEntry;
3443 return pArray;
drh13449892005-09-07 21:22:45 +00003444}
3445
3446/*
drh75897232000-05-29 14:26:00 +00003447** Append a new element to the given IdList. Create a new IdList if
3448** need be.
drhdaffd0e2001-04-11 14:28:42 +00003449**
3450** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003451*/
drh17435752007-08-16 04:30:38 +00003452IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003453 int i;
drh75897232000-05-29 14:26:00 +00003454 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003455 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003456 if( pList==0 ) return 0;
3457 }
drhcf643722007-03-27 13:36:37 +00003458 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003459 db,
drhcf643722007-03-27 13:36:37 +00003460 pList->a,
3461 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003462 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003463 &i
3464 );
drh13449892005-09-07 21:22:45 +00003465 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003466 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003467 return 0;
drh75897232000-05-29 14:26:00 +00003468 }
drh17435752007-08-16 04:30:38 +00003469 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003470 return pList;
3471}
3472
3473/*
drhfe05af82005-07-21 03:14:59 +00003474** Delete an IdList.
3475*/
drh633e6d52008-07-28 19:34:53 +00003476void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003477 int i;
3478 if( pList==0 ) return;
3479 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003480 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003481 }
drh633e6d52008-07-28 19:34:53 +00003482 sqlite3DbFree(db, pList->a);
3483 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003484}
3485
3486/*
3487** Return the index in pList of the identifier named zId. Return -1
3488** if not found.
3489*/
3490int sqlite3IdListIndex(IdList *pList, const char *zName){
3491 int i;
3492 if( pList==0 ) return -1;
3493 for(i=0; i<pList->nId; i++){
3494 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3495 }
3496 return -1;
3497}
3498
3499/*
drha78c22c2008-11-11 18:28:58 +00003500** Expand the space allocated for the given SrcList object by
3501** creating nExtra new slots beginning at iStart. iStart is zero based.
3502** New slots are zeroed.
3503**
3504** For example, suppose a SrcList initially contains two entries: A,B.
3505** To append 3 new entries onto the end, do this:
3506**
3507** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3508**
3509** After the call above it would contain: A, B, nil, nil, nil.
3510** If the iStart argument had been 1 instead of 2, then the result
3511** would have been: A, nil, nil, nil, B. To prepend the new slots,
3512** the iStart value would be 0. The result then would
3513** be: nil, nil, nil, A, B.
3514**
3515** If a memory allocation fails the SrcList is unchanged. The
3516** db->mallocFailed flag will be set to true.
3517*/
3518SrcList *sqlite3SrcListEnlarge(
3519 sqlite3 *db, /* Database connection to notify of OOM errors */
3520 SrcList *pSrc, /* The SrcList to be enlarged */
3521 int nExtra, /* Number of new slots to add to pSrc->a[] */
3522 int iStart /* Index in pSrc->a[] of first new slot */
3523){
3524 int i;
3525
3526 /* Sanity checking on calling parameters */
3527 assert( iStart>=0 );
3528 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003529 assert( pSrc!=0 );
3530 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003531
3532 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003533 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003534 SrcList *pNew;
3535 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003536 int nGot;
drha78c22c2008-11-11 18:28:58 +00003537 pNew = sqlite3DbRealloc(db, pSrc,
3538 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3539 if( pNew==0 ){
3540 assert( db->mallocFailed );
3541 return pSrc;
3542 }
3543 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003544 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003545 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003546 }
3547
3548 /* Move existing slots that come after the newly inserted slots
3549 ** out of the way */
3550 for(i=pSrc->nSrc-1; i>=iStart; i--){
3551 pSrc->a[i+nExtra] = pSrc->a[i];
3552 }
drh6d1626e2014-03-05 15:52:43 +00003553 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003554
3555 /* Zero the newly allocated slots */
3556 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3557 for(i=iStart; i<iStart+nExtra; i++){
3558 pSrc->a[i].iCursor = -1;
3559 }
3560
3561 /* Return a pointer to the enlarged SrcList */
3562 return pSrc;
3563}
3564
3565
3566/*
drhad3cab52002-05-24 02:04:32 +00003567** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003568** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003569**
drha78c22c2008-11-11 18:28:58 +00003570** A SrcList is returned, or NULL if there is an OOM error. The returned
3571** SrcList might be the same as the SrcList that was input or it might be
3572** a new one. If an OOM error does occurs, then the prior value of pList
3573** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003574**
3575** If pDatabase is not null, it means that the table has an optional
3576** database name prefix. Like this: "database.table". The pDatabase
3577** points to the table name and the pTable points to the database name.
3578** The SrcList.a[].zName field is filled with the table name which might
3579** come from pTable (if pDatabase is NULL) or from pDatabase.
3580** SrcList.a[].zDatabase is filled with the database name from pTable,
3581** or with NULL if no database is specified.
3582**
3583** In other words, if call like this:
3584**
drh17435752007-08-16 04:30:38 +00003585** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003586**
3587** Then B is a table name and the database name is unspecified. If called
3588** like this:
3589**
drh17435752007-08-16 04:30:38 +00003590** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003591**
drhd3001712009-05-12 17:46:53 +00003592** Then C is the table name and B is the database name. If C is defined
3593** then so is B. In other words, we never have a case where:
3594**
3595** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003596**
3597** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3598** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003599*/
drh17435752007-08-16 04:30:38 +00003600SrcList *sqlite3SrcListAppend(
3601 sqlite3 *db, /* Connection to notify of malloc failures */
3602 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3603 Token *pTable, /* Table to append */
3604 Token *pDatabase /* Database of the table */
3605){
drha99db3b2004-06-19 14:49:12 +00003606 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003607 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003608 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003609 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003610 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003611 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003612 }
drha78c22c2008-11-11 18:28:58 +00003613 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3614 if( db->mallocFailed ){
3615 sqlite3SrcListDelete(db, pList);
3616 return 0;
drhad3cab52002-05-24 02:04:32 +00003617 }
drha78c22c2008-11-11 18:28:58 +00003618 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003619 if( pDatabase && pDatabase->z==0 ){
3620 pDatabase = 0;
3621 }
drhd3001712009-05-12 17:46:53 +00003622 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003623 Token *pTemp = pDatabase;
3624 pDatabase = pTable;
3625 pTable = pTemp;
3626 }
drh17435752007-08-16 04:30:38 +00003627 pItem->zName = sqlite3NameFromToken(db, pTable);
3628 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003629 return pList;
3630}
3631
3632/*
drhdfe88ec2008-11-03 20:55:06 +00003633** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003634*/
danielk19774adee202004-05-08 08:23:19 +00003635void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003636 int i;
drh9b3187e2005-01-18 14:45:47 +00003637 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003638 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003639 if( pList ){
3640 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3641 if( pItem->iCursor>=0 ) break;
3642 pItem->iCursor = pParse->nTab++;
3643 if( pItem->pSelect ){
3644 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3645 }
drh63eb5f22003-04-29 16:20:44 +00003646 }
3647 }
3648}
3649
3650/*
drhad3cab52002-05-24 02:04:32 +00003651** Delete an entire SrcList including all its substructure.
3652*/
drh633e6d52008-07-28 19:34:53 +00003653void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003654 int i;
drhbe5c89a2004-07-26 00:31:09 +00003655 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003656 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003657 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003658 sqlite3DbFree(db, pItem->zDatabase);
3659 sqlite3DbFree(db, pItem->zName);
3660 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003661 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003662 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003663 sqlite3SelectDelete(db, pItem->pSelect);
3664 sqlite3ExprDelete(db, pItem->pOn);
3665 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003666 }
drh633e6d52008-07-28 19:34:53 +00003667 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003668}
3669
drh982cef72000-05-30 16:27:03 +00003670/*
drh61dfc312006-12-16 16:25:15 +00003671** This routine is called by the parser to add a new term to the
3672** end of a growing FROM clause. The "p" parameter is the part of
3673** the FROM clause that has already been constructed. "p" is NULL
3674** if this is the first term of the FROM clause. pTable and pDatabase
3675** are the name of the table and database named in the FROM clause term.
3676** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003677** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003678** alias token. If the term is a subquery, then pSubquery is the
3679** SELECT statement that the subquery encodes. The pTable and
3680** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3681** parameters are the content of the ON and USING clauses.
3682**
3683** Return a new SrcList which encodes is the FROM with the new
3684** term added.
3685*/
3686SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003687 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003688 SrcList *p, /* The left part of the FROM clause already seen */
3689 Token *pTable, /* Name of the table to add to the FROM clause */
3690 Token *pDatabase, /* Name of the database containing pTable */
3691 Token *pAlias, /* The right-hand side of the AS subexpression */
3692 Select *pSubquery, /* A subquery used in place of a table name */
3693 Expr *pOn, /* The ON clause of a join */
3694 IdList *pUsing /* The USING clause of a join */
3695){
3696 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003697 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003698 if( !p && (pOn || pUsing) ){
3699 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3700 (pOn ? "ON" : "USING")
3701 );
3702 goto append_from_error;
3703 }
drh17435752007-08-16 04:30:38 +00003704 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003705 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003706 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003707 }
3708 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003709 assert( pAlias!=0 );
3710 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003711 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003712 }
3713 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003714 pItem->pOn = pOn;
3715 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003716 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003717
3718 append_from_error:
3719 assert( p==0 );
3720 sqlite3ExprDelete(db, pOn);
3721 sqlite3IdListDelete(db, pUsing);
3722 sqlite3SelectDelete(db, pSubquery);
3723 return 0;
drh61dfc312006-12-16 16:25:15 +00003724}
3725
3726/*
danielk1977b1c685b2008-10-06 16:18:39 +00003727** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3728** element of the source-list passed as the second argument.
3729*/
3730void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003731 assert( pIndexedBy!=0 );
3732 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003733 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3734 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3735 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3736 /* A "NOT INDEXED" clause was supplied. See parse.y
3737 ** construct "indexed_opt" for details. */
3738 pItem->notIndexed = 1;
3739 }else{
3740 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3741 }
3742 }
3743}
3744
3745/*
drh61dfc312006-12-16 16:25:15 +00003746** When building up a FROM clause in the parser, the join operator
3747** is initially attached to the left operand. But the code generator
3748** expects the join operator to be on the right operand. This routine
3749** Shifts all join operators from left to right for an entire FROM
3750** clause.
3751**
3752** Example: Suppose the join is like this:
3753**
3754** A natural cross join B
3755**
3756** The operator is "natural cross join". The A and B operands are stored
3757** in p->a[0] and p->a[1], respectively. The parser initially stores the
3758** operator with A. This routine shifts that operator over to B.
3759*/
3760void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003761 if( p ){
drh61dfc312006-12-16 16:25:15 +00003762 int i;
drhd017ab92011-08-23 00:01:58 +00003763 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003764 for(i=p->nSrc-1; i>0; i--){
3765 p->a[i].jointype = p->a[i-1].jointype;
3766 }
3767 p->a[0].jointype = 0;
3768 }
3769}
3770
3771/*
drhc4a3c772001-04-04 11:48:57 +00003772** Begin a transaction
3773*/
drh684917c2004-10-05 02:41:42 +00003774void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003775 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003776 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003777 int i;
drh5e00f6c2001-09-13 13:46:56 +00003778
drhd3001712009-05-12 17:46:53 +00003779 assert( pParse!=0 );
3780 db = pParse->db;
3781 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003782/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003783 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3784 return;
3785 }
danielk19771d850a72004-05-31 08:26:49 +00003786 v = sqlite3GetVdbe(pParse);
3787 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003788 if( type!=TK_DEFERRED ){
3789 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003790 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003791 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003792 }
3793 }
drh66a51672008-01-03 00:01:23 +00003794 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003795}
3796
3797/*
3798** Commit a transaction
3799*/
danielk19774adee202004-05-08 08:23:19 +00003800void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003801 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003802
drhd3001712009-05-12 17:46:53 +00003803 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003804 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003805 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3806 return;
3807 }
danielk19771d850a72004-05-31 08:26:49 +00003808 v = sqlite3GetVdbe(pParse);
3809 if( v ){
drh66a51672008-01-03 00:01:23 +00003810 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003811 }
drhc4a3c772001-04-04 11:48:57 +00003812}
3813
3814/*
3815** Rollback a transaction
3816*/
danielk19774adee202004-05-08 08:23:19 +00003817void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003818 Vdbe *v;
3819
drhd3001712009-05-12 17:46:53 +00003820 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003821 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003822 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3823 return;
3824 }
danielk19774adee202004-05-08 08:23:19 +00003825 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003826 if( v ){
drh66a51672008-01-03 00:01:23 +00003827 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003828 }
drhc4a3c772001-04-04 11:48:57 +00003829}
drhf57b14a2001-09-14 18:54:08 +00003830
3831/*
danielk1977fd7f0452008-12-17 17:30:26 +00003832** This function is called by the parser when it parses a command to create,
3833** release or rollback an SQL savepoint.
3834*/
3835void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003836 char *zName = sqlite3NameFromToken(pParse->db, pName);
3837 if( zName ){
3838 Vdbe *v = sqlite3GetVdbe(pParse);
3839#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003840 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003841 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3842#endif
3843 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3844 sqlite3DbFree(pParse->db, zName);
3845 return;
3846 }
3847 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003848 }
3849}
3850
3851/*
drhdc3ff9c2004-08-18 02:10:15 +00003852** Make sure the TEMP database is open and available for use. Return
3853** the number of errors. Leave any error messages in the pParse structure.
3854*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003855int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003856 sqlite3 *db = pParse->db;
3857 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003858 int rc;
drh10a76c92010-01-26 01:25:26 +00003859 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003860 static const int flags =
3861 SQLITE_OPEN_READWRITE |
3862 SQLITE_OPEN_CREATE |
3863 SQLITE_OPEN_EXCLUSIVE |
3864 SQLITE_OPEN_DELETEONCLOSE |
3865 SQLITE_OPEN_TEMP_DB;
3866
dan3a6d8ae2011-04-23 15:54:54 +00003867 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003868 if( rc!=SQLITE_OK ){
3869 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3870 "file for storing temporary tables");
3871 pParse->rc = rc;
3872 return 1;
3873 }
drh10a76c92010-01-26 01:25:26 +00003874 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003875 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003876 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3877 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003878 return 1;
drh10a76c92010-01-26 01:25:26 +00003879 }
drhdc3ff9c2004-08-18 02:10:15 +00003880 }
3881 return 0;
3882}
3883
3884/*
drhaceb31b2014-02-08 01:40:27 +00003885** Record the fact that the schema cookie will need to be verified
3886** for database iDb. The code to actually verify the schema cookie
3887** will occur at the end of the top-level VDBE and will be generated
3888** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003889*/
danielk19774adee202004-05-08 08:23:19 +00003890void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003891 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003892 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003893
drhaceb31b2014-02-08 01:40:27 +00003894 assert( iDb>=0 && iDb<db->nDb );
3895 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3896 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3897 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003898 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3899 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003900 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3901 if( !OMIT_TEMPDB && iDb==1 ){
3902 sqlite3OpenTempDatabase(pToplevel);
3903 }
drh001bbcb2003-03-19 03:14:00 +00003904 }
drh001bbcb2003-03-19 03:14:00 +00003905}
3906
3907/*
dan57966752011-04-09 17:32:58 +00003908** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3909** attached database. Otherwise, invoke it for the database named zDb only.
3910*/
3911void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3912 sqlite3 *db = pParse->db;
3913 int i;
3914 for(i=0; i<db->nDb; i++){
3915 Db *pDb = &db->aDb[i];
3916 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3917 sqlite3CodeVerifySchema(pParse, i);
3918 }
3919 }
3920}
3921
3922/*
drh1c928532002-01-31 15:54:21 +00003923** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003924** might change the database.
3925**
3926** This routine starts a new transaction if we are not already within
3927** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003928** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003929** be set for operations that might fail (due to a constraint) part of
3930** the way through and which will need to undo some writes without having to
3931** rollback the whole transaction. For operations where all constraints
3932** can be checked before any changes are made to the database, it is never
3933** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003934*/
drh7f0f12e2004-05-21 13:39:50 +00003935void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003936 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003937 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003938 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003939 pToplevel->isMultiWrite |= setStatement;
3940}
3941
drhff738bc2009-09-24 00:09:58 +00003942/*
3943** Indicate that the statement currently under construction might write
3944** more than one entry (example: deleting one row then inserting another,
3945** inserting multiple rows in a table, or inserting a row and index entries.)
3946** If an abort occurs after some of these writes have completed, then it will
3947** be necessary to undo the completed writes.
3948*/
3949void sqlite3MultiWrite(Parse *pParse){
3950 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3951 pToplevel->isMultiWrite = 1;
3952}
3953
dane0af83a2009-09-08 19:15:01 +00003954/*
drhff738bc2009-09-24 00:09:58 +00003955** The code generator calls this routine if is discovers that it is
3956** possible to abort a statement prior to completion. In order to
3957** perform this abort without corrupting the database, we need to make
3958** sure that the statement is protected by a statement transaction.
3959**
3960** Technically, we only need to set the mayAbort flag if the
3961** isMultiWrite flag was previously set. There is a time dependency
3962** such that the abort must occur after the multiwrite. This makes
3963** some statements involving the REPLACE conflict resolution algorithm
3964** go a little faster. But taking advantage of this time dependency
3965** makes it more difficult to prove that the code is correct (in
3966** particular, it prevents us from writing an effective
3967** implementation of sqlite3AssertMayAbort()) and so we have chosen
3968** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003969*/
3970void sqlite3MayAbort(Parse *pParse){
3971 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3972 pToplevel->mayAbort = 1;
3973}
3974
3975/*
3976** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3977** error. The onError parameter determines which (if any) of the statement
3978** and/or current transaction is rolled back.
3979*/
drhd91c1a12013-02-09 13:58:25 +00003980void sqlite3HaltConstraint(
3981 Parse *pParse, /* Parsing context */
3982 int errCode, /* extended error code */
3983 int onError, /* Constraint type */
3984 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003985 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3986 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003987){
dane0af83a2009-09-08 19:15:01 +00003988 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003989 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003990 if( onError==OE_Abort ){
3991 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003992 }
drhd91c1a12013-02-09 13:58:25 +00003993 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003994 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3995}
3996
3997/*
3998** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
3999*/
4000void sqlite3UniqueConstraint(
4001 Parse *pParse, /* Parsing context */
4002 int onError, /* Constraint type */
4003 Index *pIdx /* The index that triggers the constraint */
4004){
4005 char *zErr;
4006 int j;
4007 StrAccum errMsg;
4008 Table *pTab = pIdx->pTable;
4009
4010 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4011 errMsg.db = pParse->db;
4012 for(j=0; j<pIdx->nKeyCol; j++){
4013 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4014 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004015 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004016 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004017 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004018 }
4019 zErr = sqlite3StrAccumFinish(&errMsg);
4020 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004021 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4022 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004023 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004024}
4025
4026
4027/*
4028** Code an OP_Halt due to non-unique rowid.
4029*/
4030void sqlite3RowidConstraint(
4031 Parse *pParse, /* Parsing context */
4032 int onError, /* Conflict resolution algorithm */
4033 Table *pTab /* The table with the non-unique rowid */
4034){
4035 char *zMsg;
4036 int rc;
4037 if( pTab->iPKey>=0 ){
4038 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4039 pTab->aCol[pTab->iPKey].zName);
4040 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4041 }else{
4042 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4043 rc = SQLITE_CONSTRAINT_ROWID;
4044 }
4045 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4046 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004047}
4048
drh4343fea2004-11-05 23:46:15 +00004049/*
4050** Check to see if pIndex uses the collating sequence pColl. Return
4051** true if it does and false if it does not.
4052*/
4053#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004054static int collationMatch(const char *zColl, Index *pIndex){
4055 int i;
drh04491712009-05-13 17:21:13 +00004056 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004057 for(i=0; i<pIndex->nColumn; i++){
4058 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004059 assert( z!=0 || pIndex->aiColumn[i]<0 );
4060 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004061 return 1;
4062 }
drh4343fea2004-11-05 23:46:15 +00004063 }
4064 return 0;
4065}
4066#endif
4067
4068/*
4069** Recompute all indices of pTab that use the collating sequence pColl.
4070** If pColl==0 then recompute all indices of pTab.
4071*/
4072#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004073static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004074 Index *pIndex; /* An index associated with pTab */
4075
4076 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004077 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004078 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4079 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004080 sqlite3RefillIndex(pParse, pIndex, -1);
4081 }
4082 }
4083}
4084#endif
4085
4086/*
4087** Recompute all indices of all tables in all databases where the
4088** indices use the collating sequence pColl. If pColl==0 then recompute
4089** all indices everywhere.
4090*/
4091#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004092static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004093 Db *pDb; /* A single database */
4094 int iDb; /* The database index number */
4095 sqlite3 *db = pParse->db; /* The database connection */
4096 HashElem *k; /* For looping over tables in pDb */
4097 Table *pTab; /* A table in the database */
4098
drh21206082011-04-04 18:22:02 +00004099 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004100 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004101 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004102 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004103 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004104 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004105 }
4106 }
4107}
4108#endif
4109
4110/*
drheee46cf2004-11-06 00:02:48 +00004111** Generate code for the REINDEX command.
4112**
4113** REINDEX -- 1
4114** REINDEX <collation> -- 2
4115** REINDEX ?<database>.?<tablename> -- 3
4116** REINDEX ?<database>.?<indexname> -- 4
4117**
4118** Form 1 causes all indices in all attached databases to be rebuilt.
4119** Form 2 rebuilds all indices in all databases that use the named
4120** collating function. Forms 3 and 4 rebuild the named index or all
4121** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004122*/
4123#ifndef SQLITE_OMIT_REINDEX
4124void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4125 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4126 char *z; /* Name of a table or index */
4127 const char *zDb; /* Name of the database */
4128 Table *pTab; /* A table in the database */
4129 Index *pIndex; /* An index associated with pTab */
4130 int iDb; /* The database index number */
4131 sqlite3 *db = pParse->db; /* The database connection */
4132 Token *pObjName; /* Name of the table or index to be reindexed */
4133
danielk197733a5edc2005-01-27 00:22:02 +00004134 /* Read the database schema. If an error occurs, leave an error message
4135 ** and code in pParse and return NULL. */
4136 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004137 return;
danielk197733a5edc2005-01-27 00:22:02 +00004138 }
4139
drh8af73d42009-05-13 22:58:28 +00004140 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004141 reindexDatabases(pParse, 0);
4142 return;
drhd3001712009-05-12 17:46:53 +00004143 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004144 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004145 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004146 zColl = sqlite3NameFromToken(pParse->db, pName1);
4147 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004148 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004149 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004150 reindexDatabases(pParse, zColl);
4151 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004152 return;
4153 }
drh633e6d52008-07-28 19:34:53 +00004154 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004155 }
4156 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4157 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004158 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004159 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004160 zDb = db->aDb[iDb].zName;
4161 pTab = sqlite3FindTable(db, z, zDb);
4162 if( pTab ){
4163 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004164 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004165 return;
4166 }
4167 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004168 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004169 if( pIndex ){
4170 sqlite3BeginWriteOperation(pParse, 0, iDb);
4171 sqlite3RefillIndex(pParse, pIndex, -1);
4172 return;
4173 }
4174 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4175}
4176#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004177
4178/*
drh2ec2fb22013-11-06 19:59:23 +00004179** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004180**
drh2ec2fb22013-11-06 19:59:23 +00004181** The KeyInfo structure for an index is cached in the Index object.
4182** So there might be multiple references to the returned pointer. The
4183** caller should not try to modify the KeyInfo object.
4184**
4185** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4186** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004187*/
drh2ec2fb22013-11-06 19:59:23 +00004188KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004189 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004190#ifndef SQLITE_OMIT_SHARED_CACHE
4191 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4192 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4193 pIdx->pKeyInfo = 0;
4194 }
4195#endif
drh2ec2fb22013-11-06 19:59:23 +00004196 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004197 int i;
4198 int nCol = pIdx->nColumn;
4199 int nKey = pIdx->nKeyCol;
4200 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004201 if( pIdx->uniqNotNull ){
4202 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4203 }else{
4204 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4205 }
4206 if( pKey ){
4207 assert( sqlite3KeyInfoIsWriteable(pKey) );
4208 for(i=0; i<nCol; i++){
4209 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004210 assert( zColl!=0 );
4211 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4212 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004213 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4214 }
4215 if( pParse->nErr ){
4216 sqlite3KeyInfoUnref(pKey);
4217 }else{
4218 pIdx->pKeyInfo = pKey;
4219 }
danielk1977b3bf5562006-01-10 17:58:23 +00004220 }
danielk1977b3bf5562006-01-10 17:58:23 +00004221 }
drh2ec2fb22013-11-06 19:59:23 +00004222 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004223}
drh8b471862014-01-11 13:22:17 +00004224
4225#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004226/*
4227** This routine is invoked once per CTE by the parser while parsing a
4228** WITH clause.
drh8b471862014-01-11 13:22:17 +00004229*/
dan7d562db2014-01-11 19:19:36 +00004230With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004231 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004232 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004233 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004234 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004235 Select *pQuery /* Query used to initialize the table */
4236){
dan4e9119d2014-01-13 15:12:23 +00004237 sqlite3 *db = pParse->db;
4238 With *pNew;
4239 char *zName;
4240
4241 /* Check that the CTE name is unique within this WITH clause. If
4242 ** not, store an error in the Parse structure. */
4243 zName = sqlite3NameFromToken(pParse->db, pName);
4244 if( zName && pWith ){
4245 int i;
4246 for(i=0; i<pWith->nCte; i++){
4247 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004248 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004249 }
4250 }
4251 }
4252
4253 if( pWith ){
4254 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4255 pNew = sqlite3DbRealloc(db, pWith, nByte);
4256 }else{
4257 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4258 }
4259 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004260 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004261
4262 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004263 sqlite3ExprListDelete(db, pArglist);
4264 sqlite3SelectDelete(db, pQuery);
4265 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004266 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004267 }else{
4268 pNew->a[pNew->nCte].pSelect = pQuery;
4269 pNew->a[pNew->nCte].pCols = pArglist;
4270 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004271 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004272 pNew->nCte++;
4273 }
4274
4275 return pNew;
drh8b471862014-01-11 13:22:17 +00004276}
4277
dan7d562db2014-01-11 19:19:36 +00004278/*
4279** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004280*/
dan7d562db2014-01-11 19:19:36 +00004281void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004282 if( pWith ){
4283 int i;
4284 for(i=0; i<pWith->nCte; i++){
4285 struct Cte *pCte = &pWith->a[i];
4286 sqlite3ExprListDelete(db, pCte->pCols);
4287 sqlite3SelectDelete(db, pCte->pSelect);
4288 sqlite3DbFree(db, pCte->zName);
4289 }
4290 sqlite3DbFree(db, pWith);
4291 }
drh8b471862014-01-11 13:22:17 +00004292}
4293#endif /* !defined(SQLITE_OMIT_CTE) */