blob: d95cf849e6529ac3d4d520c374f698b0b15d2884 [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 ){
161 if( db->auth.authLevel<UAUTH_User ){
162 if( db->auth.authLevel==UAUTH_Unknown ){
163 u8 authLevel = UAUTH_Fail;
164 sqlite3UserAuthCheckLogin(db, "main", &authLevel);
165 db->auth.authLevel = authLevel;
166 if( authLevel<UAUTH_Admin ) db->flags &= ~SQLITE_WriteSchema;
167 }
168 if( db->auth.authLevel<UAUTH_User ){
169 pParse->rc = SQLITE_AUTH_USER;
170 sqlite3ErrorMsg(pParse, "user not authenticated");
171 return;
172 }
173 }
174 }
175#endif
176
drh0e3d7472004-06-19 17:33:07 +0000177 /* The cookie mask contains one bit for each database file open.
178 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
179 ** set for each database that is used. Generate code to start a
180 ** transaction on each used database and to verify the schema cookie
181 ** on each used database.
182 */
drha7ab6d82014-07-21 15:44:39 +0000183 if( db->mallocFailed==0
184 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
185 ){
drhaceb31b2014-02-08 01:40:27 +0000186 int iDb, i;
187 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
188 sqlite3VdbeJumpHere(v, 0);
drha7ab6d82014-07-21 15:44:39 +0000189 for(iDb=0; iDb<db->nDb; iDb++){
190 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000191 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000192 sqlite3VdbeAddOp4Int(v,
193 OP_Transaction, /* Opcode */
194 iDb, /* P1 */
drha7ab6d82014-07-21 15:44:39 +0000195 DbMaskTest(pParse->writeMask,iDb), /* P2 */
drhb22f7c82014-02-06 23:56:27 +0000196 pParse->cookieValue[iDb], /* P3 */
197 db->aDb[iDb].pSchema->iGeneration /* P4 */
198 );
199 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
drh80242052004-06-09 00:48:12 +0000200 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000201#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000202 for(i=0; i<pParse->nVtabLock; i++){
203 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
204 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000205 }
drhf30a9692013-11-15 01:10:18 +0000206 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000207#endif
danielk1977c00da102006-01-07 13:21:04 +0000208
209 /* Once all the cookies have been verified and transactions opened,
210 ** obtain the required table-locks. This is a no-op unless the
211 ** shared-cache feature is enabled.
212 */
213 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000214
215 /* Initialize any AUTOINCREMENT data structures required.
216 */
217 sqlite3AutoincrementBegin(pParse);
218
drhf30a9692013-11-15 01:10:18 +0000219 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000220 if( pParse->pConstExpr ){
221 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000222 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000223 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000224 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000225 }
226 }
227
drh0b9f50d2009-06-23 20:28:53 +0000228 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000229 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000230 }
drh71c697e2004-08-08 23:39:19 +0000231 }
232
drh3f7d4e42004-07-24 14:35:58 +0000233
drh80242052004-06-09 00:48:12 +0000234 /* Get the VDBE program ready for execution
235 */
drh04491712009-05-13 17:21:13 +0000236 if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000237 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000238 /* A minimum of one cursor is required if autoincrement is used
239 * See ticket [a696379c1f08866] */
240 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000241 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000242 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000243 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000244 }else{
drh483750b2003-01-29 18:46:51 +0000245 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000246 }
drha226d052002-09-25 19:04:07 +0000247 pParse->nTab = 0;
248 pParse->nMem = 0;
249 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000250 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000251 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000252}
253
254/*
drh205f48e2004-11-05 00:43:11 +0000255** Run the parser and code generator recursively in order to generate
256** code for the SQL statement given onto the end of the pParse context
257** currently under construction. When the parser is run recursively
258** this way, the final OP_Halt is not appended and other initialization
259** and finalization steps are omitted because those are handling by the
260** outermost parser.
261**
262** Not everything is nestable. This facility is designed to permit
263** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000264** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000265*/
266void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
267 va_list ap;
268 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000269 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000270 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000271# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
272 char saveBuf[SAVE_SZ];
273
drh205f48e2004-11-05 00:43:11 +0000274 if( pParse->nErr ) return;
275 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
276 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000277 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000278 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000279 if( zSql==0 ){
280 return; /* A malloc must have failed */
281 }
drh205f48e2004-11-05 00:43:11 +0000282 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000283 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
284 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000285 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000286 sqlite3DbFree(db, zErrMsg);
287 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000288 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000289 pParse->nested--;
290}
291
drhd4530972014-09-09 14:47:53 +0000292#if SQLITE_USER_AUTHENTICATION
293/*
294** Return TRUE if zTable is the name of the system table that stores the
295** list of users and their access credentials.
296*/
297int sqlite3UserAuthTable(const char *zTable){
298 return sqlite3_stricmp(zTable, "sqlite_user")==0;
299}
300#endif
301
drh205f48e2004-11-05 00:43:11 +0000302/*
danielk19778a414492004-06-29 08:59:35 +0000303** Locate the in-memory structure that describes a particular database
304** table given the name of that table and (optionally) the name of the
305** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000306**
danielk19778a414492004-06-29 08:59:35 +0000307** If zDatabase is 0, all databases are searched for the table and the
308** first matching table is returned. (No checking for duplicate table
309** names is done.) The search order is TEMP first, then MAIN, then any
310** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000311**
danielk19774adee202004-05-08 08:23:19 +0000312** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000313*/
drh9bb575f2004-09-06 17:24:11 +0000314Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000315 Table *p = 0;
316 int i;
drh645f63e2004-06-22 13:22:40 +0000317 assert( zName!=0 );
drh21206082011-04-04 18:22:02 +0000318 /* All mutexes are required for schema access. Make sure we hold them. */
319 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000320#if SQLITE_USER_AUTHENTICATION
321 /* Only the admin user is allowed to know that the sqlite_user table
322 ** exists */
drhe933b832014-09-10 17:34:28 +0000323 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
324 return 0;
325 }
drhd4530972014-09-09 14:47:53 +0000326#endif
danielk197753c0f742005-03-29 03:10:59 +0000327 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000328 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000329 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000330 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000331 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000332 if( p ) break;
333 }
drh74e24cd2002-01-09 03:19:59 +0000334 return p;
drh75897232000-05-29 14:26:00 +0000335}
336
337/*
danielk19778a414492004-06-29 08:59:35 +0000338** Locate the in-memory structure that describes a particular database
339** table given the name of that table and (optionally) the name of the
340** database containing the table. Return NULL if not found. Also leave an
341** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000342**
danielk19778a414492004-06-29 08:59:35 +0000343** The difference between this routine and sqlite3FindTable() is that this
344** routine leaves an error message in pParse->zErrMsg where
345** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000346*/
drhca424112008-01-25 15:04:48 +0000347Table *sqlite3LocateTable(
348 Parse *pParse, /* context in which to report errors */
349 int isView, /* True if looking for a VIEW rather than a TABLE */
350 const char *zName, /* Name of the table we are looking for */
351 const char *zDbase /* Name of the database. Might be NULL */
352){
drha69d9162003-04-17 22:57:53 +0000353 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000354
danielk19778a414492004-06-29 08:59:35 +0000355 /* Read the database schema. If an error occurs, leave an error message
356 ** and code in pParse and return NULL. */
357 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
358 return 0;
359 }
360
danielk19774adee202004-05-08 08:23:19 +0000361 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000362 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000363 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000364 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000365 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000366 }else{
drhca424112008-01-25 15:04:48 +0000367 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000368 }
drha6ecd332004-06-10 00:29:09 +0000369 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000370 }
drhe933b832014-09-10 17:34:28 +0000371#if SQLITE_USER_AUTHENICATION
372 else if( pParse->db->auth.authLevel<UAUTH_User ){
373 sqlite3ErrorMsg(pParse, "user not authenticated");
374 p = 0;
375 }
376#endif
drha69d9162003-04-17 22:57:53 +0000377 return p;
378}
379
380/*
dan41fb5cd2012-10-04 19:33:00 +0000381** Locate the table identified by *p.
382**
383** This is a wrapper around sqlite3LocateTable(). The difference between
384** sqlite3LocateTable() and this function is that this function restricts
385** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
386** non-NULL if it is part of a view or trigger program definition. See
387** sqlite3FixSrcList() for details.
388*/
389Table *sqlite3LocateTableItem(
390 Parse *pParse,
391 int isView,
392 struct SrcList_item *p
393){
394 const char *zDb;
395 assert( p->pSchema==0 || p->zDatabase==0 );
396 if( p->pSchema ){
397 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
398 zDb = pParse->db->aDb[iDb].zName;
399 }else{
400 zDb = p->zDatabase;
401 }
402 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
403}
404
405/*
drha69d9162003-04-17 22:57:53 +0000406** Locate the in-memory structure that describes
407** a particular index given the name of that index
408** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000409** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000410**
411** If zDatabase is 0, all databases are searched for the
412** table and the first matching index is returned. (No checking
413** for duplicate index names is done.) The search order is
414** TEMP first, then MAIN, then any auxiliary databases added
415** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000416*/
drh9bb575f2004-09-06 17:24:11 +0000417Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000418 Index *p = 0;
419 int i;
drh21206082011-04-04 18:22:02 +0000420 /* All mutexes are required for schema access. Make sure we hold them. */
421 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000422 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000423 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000424 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000425 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000426 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000427 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000428 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000429 if( p ) break;
430 }
drh74e24cd2002-01-09 03:19:59 +0000431 return p;
drh75897232000-05-29 14:26:00 +0000432}
433
434/*
drh956bc922004-07-24 17:38:29 +0000435** Reclaim the memory used by an index
436*/
dan1feeaed2010-07-23 15:41:47 +0000437static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000438#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000439 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000440#endif
drh2ec2fb22013-11-06 19:59:23 +0000441 if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
drh1fe05372013-07-31 18:12:26 +0000442 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000443 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000444 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh633e6d52008-07-28 19:34:53 +0000445 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000446}
447
448/*
drhc96d8532005-05-03 12:30:33 +0000449** For the index called zIdxName which is found in the database iDb,
450** unlike that index from its Table then remove the index from
451** the index hash table and free all memory structures associated
452** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000453*/
drh9bb575f2004-09-06 17:24:11 +0000454void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000455 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000456 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000457
drh21206082011-04-04 18:22:02 +0000458 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
459 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000460 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000461 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000462 if( pIndex->pTable->pIndex==pIndex ){
463 pIndex->pTable->pIndex = pIndex->pNext;
464 }else{
465 Index *p;
drh04491712009-05-13 17:21:13 +0000466 /* Justification of ALWAYS(); The index must be on the list of
467 ** indices. */
468 p = pIndex->pTable->pIndex;
469 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
470 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000471 p->pNext = pIndex->pNext;
472 }
drh5e00f6c2001-09-13 13:46:56 +0000473 }
dan1feeaed2010-07-23 15:41:47 +0000474 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000475 }
drh956bc922004-07-24 17:38:29 +0000476 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000477}
478
479/*
drh81028a42012-05-15 18:28:27 +0000480** Look through the list of open database files in db->aDb[] and if
481** any have been closed, remove them from the list. Reallocate the
482** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000483**
drh81028a42012-05-15 18:28:27 +0000484** Entry 0 (the "main" database) and entry 1 (the "temp" database)
485** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000486*/
drh81028a42012-05-15 18:28:27 +0000487void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000488 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000489 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000490 struct Db *pDb = &db->aDb[i];
491 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000492 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000493 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000494 continue;
495 }
496 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000497 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000498 }
drh8bf8dc92003-05-17 17:35:10 +0000499 j++;
drh1c2d8412003-03-31 00:30:47 +0000500 }
501 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
502 db->nDb = j;
503 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
504 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000505 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000506 db->aDb = db->aDbStatic;
507 }
drhe0bc4042002-06-25 01:09:11 +0000508}
509
510/*
drh81028a42012-05-15 18:28:27 +0000511** Reset the schema for the database at index iDb. Also reset the
512** TEMP schema.
513*/
514void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000515 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000516 assert( iDb<db->nDb );
517
518 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000519 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000520 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
521 assert( pDb->pSchema!=0 );
522 sqlite3SchemaClear(pDb->pSchema);
523
524 /* If any database other than TEMP is reset, then also reset TEMP
525 ** since TEMP might be holding triggers that reference tables in the
526 ** other database.
527 */
528 if( iDb!=1 ){
529 pDb = &db->aDb[1];
530 assert( pDb->pSchema!=0 );
531 sqlite3SchemaClear(pDb->pSchema);
532 }
533 return;
534}
535
536/*
537** Erase all schema information from all attached databases (including
538** "main" and "temp") for a single database connection.
539*/
540void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
541 int i;
542 sqlite3BtreeEnterAll(db);
543 for(i=0; i<db->nDb; i++){
544 Db *pDb = &db->aDb[i];
545 if( pDb->pSchema ){
546 sqlite3SchemaClear(pDb->pSchema);
547 }
548 }
549 db->flags &= ~SQLITE_InternChanges;
550 sqlite3VtabUnlockList(db);
551 sqlite3BtreeLeaveAll(db);
552 sqlite3CollapseDatabaseArray(db);
553}
554
555/*
drhe0bc4042002-06-25 01:09:11 +0000556** This routine is called when a commit occurs.
557*/
drh9bb575f2004-09-06 17:24:11 +0000558void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000559 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000560}
561
562/*
dand46def72010-07-24 11:28:28 +0000563** Delete memory allocated for the column names of a table or view (the
564** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000565*/
dand46def72010-07-24 11:28:28 +0000566static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000567 int i;
568 Column *pCol;
569 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000570 if( (pCol = pTable->aCol)!=0 ){
571 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000572 sqlite3DbFree(db, pCol->zName);
573 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000574 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000575 sqlite3DbFree(db, pCol->zType);
576 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000577 }
drh633e6d52008-07-28 19:34:53 +0000578 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000579 }
drh956bc922004-07-24 17:38:29 +0000580}
581
582/*
drh75897232000-05-29 14:26:00 +0000583** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000584** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000585**
586** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000587** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000588** memory structures of the indices and foreign keys associated with
589** the table.
drh29ddd3a2012-05-15 12:49:32 +0000590**
591** The db parameter is optional. It is needed if the Table object
592** contains lookaside memory. (Table objects in the schema do not use
593** lookaside memory, but some ephemeral Table objects do.) Or the
594** db parameter can be used with db->pnBytesFreed to measure the memory
595** used by the Table object.
drh75897232000-05-29 14:26:00 +0000596*/
dan1feeaed2010-07-23 15:41:47 +0000597void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000598 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000599 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000600
dand46def72010-07-24 11:28:28 +0000601 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000602
drhed8a3bb2005-06-06 21:19:56 +0000603 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000604 if( !pTable ) return;
605 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000606
drh29ddd3a2012-05-15 12:49:32 +0000607 /* Record the number of outstanding lookaside allocations in schema Tables
608 ** prior to doing any free() operations. Since schema Tables do not use
609 ** lookaside, this number should not change. */
610 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
611 db->lookaside.nOut : 0 );
612
dand46def72010-07-24 11:28:28 +0000613 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000614 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
615 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000616 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000617 if( !db || db->pnBytesFreed==0 ){
618 char *zName = pIndex->zName;
619 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000620 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000621 );
drh21206082011-04-04 18:22:02 +0000622 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000623 assert( pOld==pIndex || pOld==0 );
624 }
625 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000626 }
627
dan1da40a32009-09-19 17:00:31 +0000628 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000629 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000630
631 /* Delete the Table structure itself.
632 */
dand46def72010-07-24 11:28:28 +0000633 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000634 sqlite3DbFree(db, pTable->zName);
635 sqlite3DbFree(db, pTable->zColAff);
636 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000637#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000638 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000639#endif
drh078e4082010-07-28 19:17:51 +0000640#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000641 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000642#endif
drh633e6d52008-07-28 19:34:53 +0000643 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000644
645 /* Verify that no lookaside memory was used by schema tables */
646 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000647}
648
649/*
drh5edc3122001-09-13 21:53:09 +0000650** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000651** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000652*/
drh9bb575f2004-09-06 17:24:11 +0000653void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000654 Table *p;
drh956bc922004-07-24 17:38:29 +0000655 Db *pDb;
656
drhd229ca92002-01-09 13:30:41 +0000657 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000658 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000659 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000660 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000661 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000662 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000663 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000664 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000665 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000666}
667
668/*
drha99db3b2004-06-19 14:49:12 +0000669** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000670** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000671** is obtained from sqliteMalloc() and must be freed by the calling
672** function.
drh75897232000-05-29 14:26:00 +0000673**
drh24fb6272009-05-01 21:13:36 +0000674** Any quotation marks (ex: "name", 'name', [name], or `name`) that
675** surround the body of the token are removed.
676**
drhc96d8532005-05-03 12:30:33 +0000677** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000678** are not \000 terminated and are not persistent. The returned string
679** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000680*/
drh17435752007-08-16 04:30:38 +0000681char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000682 char *zName;
683 if( pName ){
drh17435752007-08-16 04:30:38 +0000684 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000685 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000686 }else{
687 zName = 0;
688 }
drh75897232000-05-29 14:26:00 +0000689 return zName;
690}
691
692/*
danielk1977cbb18d22004-05-28 11:37:27 +0000693** Open the sqlite_master table stored in database number iDb for
694** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000695*/
danielk1977c00da102006-01-07 13:21:04 +0000696void sqlite3OpenMasterTable(Parse *p, int iDb){
697 Vdbe *v = sqlite3GetVdbe(p);
698 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000699 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000700 if( p->nTab==0 ){
701 p->nTab = 1;
702 }
drhe0bc4042002-06-25 01:09:11 +0000703}
704
705/*
danielk197704103022009-02-03 16:51:24 +0000706** Parameter zName points to a nul-terminated buffer containing the name
707** of a database ("main", "temp" or the name of an attached db). This
708** function returns the index of the named database in db->aDb[], or
709** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000710*/
danielk197704103022009-02-03 16:51:24 +0000711int sqlite3FindDbName(sqlite3 *db, const char *zName){
712 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000713 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000714 Db *pDb;
715 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000716 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000717 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000718 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000719 break;
drh73c42a12004-11-20 18:13:10 +0000720 }
danielk1977cbb18d22004-05-28 11:37:27 +0000721 }
722 }
danielk1977576ec6b2005-01-21 11:55:25 +0000723 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000724}
725
danielk197704103022009-02-03 16:51:24 +0000726/*
727** The token *pName contains the name of a database (either "main" or
728** "temp" or the name of an attached db). This routine returns the
729** index of the named database in db->aDb[], or -1 if the named db
730** does not exist.
731*/
732int sqlite3FindDb(sqlite3 *db, Token *pName){
733 int i; /* Database number */
734 char *zName; /* Name we are searching for */
735 zName = sqlite3NameFromToken(db, pName);
736 i = sqlite3FindDbName(db, zName);
737 sqlite3DbFree(db, zName);
738 return i;
739}
740
drh0e3d7472004-06-19 17:33:07 +0000741/* The table or view or trigger name is passed to this routine via tokens
742** pName1 and pName2. If the table name was fully qualified, for example:
743**
744** CREATE TABLE xxx.yyy (...);
745**
746** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
747** the table name is not fully qualified, i.e.:
748**
749** CREATE TABLE yyy(...);
750**
751** Then pName1 is set to "yyy" and pName2 is "".
752**
753** This routine sets the *ppUnqual pointer to point at the token (pName1 or
754** pName2) that stores the unqualified table name. The index of the
755** database "xxx" is returned.
756*/
danielk1977ef2cb632004-05-29 02:37:19 +0000757int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000758 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000759 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000760 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
761 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000762){
drh0e3d7472004-06-19 17:33:07 +0000763 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000764 sqlite3 *db = pParse->db;
765
drhc4a64fa2009-05-11 20:53:28 +0000766 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000767 if( db->init.busy ) {
768 sqlite3ErrorMsg(pParse, "corrupt database");
769 pParse->nErr++;
770 return -1;
771 }
danielk1977cbb18d22004-05-28 11:37:27 +0000772 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000773 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000774 if( iDb<0 ){
775 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
776 pParse->nErr++;
777 return -1;
778 }
779 }else{
780 assert( db->init.iDb==0 || db->init.busy );
781 iDb = db->init.iDb;
782 *pUnqual = pName1;
783 }
784 return iDb;
785}
786
787/*
danielk1977d8123362004-06-12 09:25:12 +0000788** This routine is used to check if the UTF-8 string zName is a legal
789** unqualified name for a new schema object (table, index, view or
790** trigger). All names are legal except those that begin with the string
791** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
792** is reserved for internal use.
793*/
794int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000795 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000796 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000797 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000798 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
799 return SQLITE_ERROR;
800 }
801 return SQLITE_OK;
802}
803
804/*
drh44156282013-10-23 22:23:03 +0000805** Return the PRIMARY KEY index of a table
806*/
807Index *sqlite3PrimaryKeyIndex(Table *pTab){
808 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000809 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000810 return p;
811}
812
813/*
814** Return the column of index pIdx that corresponds to table
815** column iCol. Return -1 if not found.
816*/
817i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
818 int i;
819 for(i=0; i<pIdx->nColumn; i++){
820 if( iCol==pIdx->aiColumn[i] ) return i;
821 }
822 return -1;
823}
824
825/*
drh75897232000-05-29 14:26:00 +0000826** Begin constructing a new table representation in memory. This is
827** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000828** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000829** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000830** flag is true if the table should be stored in the auxiliary database
831** file instead of in the main database file. This is normally the case
832** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000833** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000834**
drhf57b3392001-10-08 13:22:32 +0000835** The new table record is initialized and put in pParse->pNewTable.
836** As more of the CREATE TABLE statement is parsed, additional action
837** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000838** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000839** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000840*/
danielk19774adee202004-05-08 08:23:19 +0000841void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000842 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000843 Token *pName1, /* First part of the name of the table or view */
844 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000845 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000846 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000847 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000848 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000849){
drh75897232000-05-29 14:26:00 +0000850 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000851 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000852 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000853 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000854 int iDb; /* Database number to create the table in */
855 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000856
danielk1977cbb18d22004-05-28 11:37:27 +0000857 /* The table or view name to create is passed to this routine via tokens
858 ** pName1 and pName2. If the table name was fully qualified, for example:
859 **
860 ** CREATE TABLE xxx.yyy (...);
861 **
862 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
863 ** the table name is not fully qualified, i.e.:
864 **
865 ** CREATE TABLE yyy(...);
866 **
867 ** Then pName1 is set to "yyy" and pName2 is "".
868 **
869 ** The call below sets the pName pointer to point at the token (pName1 or
870 ** pName2) that stores the unqualified table name. The variable iDb is
871 ** set to the index of the database that the table or view is to be
872 ** created in.
873 */
danielk1977ef2cb632004-05-29 02:37:19 +0000874 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000875 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000876 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
877 /* If creating a temp table, the name may not be qualified. Unless
878 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000879 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000880 return;
881 }
danielk197753c0f742005-03-29 03:10:59 +0000882 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000883
884 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000885 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000886 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000887 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000888 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000889 }
drh1d85d932004-02-14 23:05:52 +0000890 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000891#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000892 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000893 {
894 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000895 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000896 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000897 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000898 }
drhe5f9c642003-01-13 23:27:31 +0000899 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000900 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000901 code = SQLITE_CREATE_TEMP_VIEW;
902 }else{
903 code = SQLITE_CREATE_VIEW;
904 }
905 }else{
danielk197753c0f742005-03-29 03:10:59 +0000906 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000907 code = SQLITE_CREATE_TEMP_TABLE;
908 }else{
909 code = SQLITE_CREATE_TABLE;
910 }
911 }
danielk1977f1a381e2006-06-16 08:01:02 +0000912 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000913 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000914 }
915 }
916#endif
drhf57b3392001-10-08 13:22:32 +0000917
drhf57b3392001-10-08 13:22:32 +0000918 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000919 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000920 ** it does. The exception is if the statement being parsed was passed
921 ** to an sqlite3_declare_vtab() call. In that case only the column names
922 ** and types will be used, so there is no need to test for namespace
923 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000924 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000925 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000926 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000927 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
928 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000929 }
dana16d1062010-09-28 17:37:28 +0000930 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000931 if( pTable ){
932 if( !noErr ){
933 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000934 }else{
935 assert( !db->init.busy );
936 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000937 }
938 goto begin_table_error;
939 }
drh8a8a0d12010-09-28 20:26:44 +0000940 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000941 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
942 goto begin_table_error;
943 }
drh75897232000-05-29 14:26:00 +0000944 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000945
danielk197726783a52007-08-29 14:06:22 +0000946 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000947 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000948 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000949 pParse->rc = SQLITE_NOMEM;
950 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000951 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000952 }
drh75897232000-05-29 14:26:00 +0000953 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000954 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000955 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000956 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000957 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000958 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000959 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000960
drh4794f732004-11-05 17:17:50 +0000961 /* If this is the magic sqlite_sequence table used by autoincrement,
962 ** then record a pointer to this table in the main database structure
963 ** so that INSERT can find the table easily.
964 */
965#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000966 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000967 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000968 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000969 }
970#endif
971
drh17f71932002-02-21 12:01:27 +0000972 /* Begin generating the code that will insert the table record into
973 ** the SQLITE_MASTER table. Note in particular that we must go ahead
974 ** and allocate the record number for the table entry now. Before any
975 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
976 ** indices to be created and the table record must come before the
977 ** indices. Hence, the record number for the table must be allocated
978 ** now.
979 */
danielk19774adee202004-05-08 08:23:19 +0000980 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000981 int j1;
drhe321c292006-01-12 01:56:43 +0000982 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000983 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000984 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000985
danielk197720b1eaf2006-07-26 16:22:14 +0000986#ifndef SQLITE_OMIT_VIRTUALTABLE
987 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000988 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000989 }
990#endif
991
danielk197736963fd2005-02-19 08:18:05 +0000992 /* If the file format and encoding in the database have not been set,
993 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000994 */
drhb7654112008-01-12 12:48:07 +0000995 reg1 = pParse->regRowid = ++pParse->nMem;
996 reg2 = pParse->regRoot = ++pParse->nMem;
997 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000998 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000999 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +00001000 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +00001001 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +00001002 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +00001003 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001004 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001005 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001006 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001007 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001008
drh4794f732004-11-05 17:17:50 +00001009 /* This just creates a place-holder record in the sqlite_master table.
1010 ** The record created does not contain anything yet. It will be replaced
1011 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001012 **
drh0fa991b2009-03-21 16:19:26 +00001013 ** The rowid for the new entry is left in register pParse->regRowid.
1014 ** The root page number of the new table is left in reg pParse->regRoot.
1015 ** The rowid and root page number values are needed by the code that
1016 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001017 */
danielk1977f1a381e2006-06-16 08:01:02 +00001018#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1019 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001020 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001021 }else
1022#endif
1023 {
drh8a120f82013-11-01 17:59:53 +00001024 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001025 }
danielk1977c00da102006-01-07 13:21:04 +00001026 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001027 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1028 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1029 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1030 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001031 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001032 }
drh23bf66d2004-12-14 03:34:34 +00001033
1034 /* Normal (non-error) return. */
1035 return;
1036
1037 /* If an error occurs, we jump here */
1038begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001039 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001040 return;
drh75897232000-05-29 14:26:00 +00001041}
1042
1043/*
danielk1977c60e9b82005-01-31 12:42:29 +00001044** This macro is used to compare two strings in a case-insensitive manner.
1045** It is slightly faster than calling sqlite3StrICmp() directly, but
1046** produces larger code.
1047**
1048** WARNING: This macro is not compatible with the strcmp() family. It
1049** returns true if the two strings are equal, otherwise false.
1050*/
1051#define STRICMP(x, y) (\
1052sqlite3UpperToLower[*(unsigned char *)(x)]== \
1053sqlite3UpperToLower[*(unsigned char *)(y)] \
1054&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1055
1056/*
drh75897232000-05-29 14:26:00 +00001057** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001058**
1059** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001060** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001061** first to get things going. Then this routine is called for each
1062** column.
drh75897232000-05-29 14:26:00 +00001063*/
danielk19774adee202004-05-08 08:23:19 +00001064void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001065 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001066 int i;
drha99db3b2004-06-19 14:49:12 +00001067 char *z;
drhc9b84a12002-06-20 11:36:48 +00001068 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001069 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001070 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001071#if SQLITE_MAX_COLUMN
1072 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001073 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1074 return;
1075 }
drhbb4957f2008-03-20 14:03:29 +00001076#endif
danielk1977ae74e032008-12-23 11:11:51 +00001077 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001078 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001079 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001080 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001081 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001082 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001083 return;
1084 }
1085 }
drh75897232000-05-29 14:26:00 +00001086 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001087 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001088 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001089 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001090 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001091 return;
1092 }
drh6d4abfb2001-10-22 02:58:08 +00001093 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001094 }
drhc9b84a12002-06-20 11:36:48 +00001095 pCol = &p->aCol[p->nCol];
1096 memset(pCol, 0, sizeof(p->aCol[0]));
1097 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001098
1099 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001100 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1101 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001102 */
danielk19774f057f92004-06-08 00:02:33 +00001103 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001104 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001105 p->nCol++;
drh75897232000-05-29 14:26:00 +00001106}
1107
1108/*
drh382c0242001-10-06 16:33:02 +00001109** This routine is called by the parser while in the middle of
1110** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1111** been seen on a column. This routine sets the notNull flag on
1112** the column currently under construction.
1113*/
danielk19774adee202004-05-08 08:23:19 +00001114void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001115 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001116 p = pParse->pNewTable;
1117 if( p==0 || NEVER(p->nCol<1) ) return;
1118 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001119}
1120
1121/*
danielk197752a83fb2005-01-31 12:56:44 +00001122** Scan the column type name zType (length nType) and return the
1123** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001124**
1125** This routine does a case-independent search of zType for the
1126** substrings in the following table. If one of the substrings is
1127** found, the corresponding affinity is returned. If zType contains
1128** more than one of the substrings, entries toward the top of
1129** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001130** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001131**
1132** Substring | Affinity
1133** --------------------------------
1134** 'INT' | SQLITE_AFF_INTEGER
1135** 'CHAR' | SQLITE_AFF_TEXT
1136** 'CLOB' | SQLITE_AFF_TEXT
1137** 'TEXT' | SQLITE_AFF_TEXT
1138** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001139** 'REAL' | SQLITE_AFF_REAL
1140** 'FLOA' | SQLITE_AFF_REAL
1141** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001142**
1143** If none of the substrings in the above table are found,
1144** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001145*/
drhfdaac672013-10-04 15:30:21 +00001146char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001147 u32 h = 0;
1148 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001149 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001150
drhfdaac672013-10-04 15:30:21 +00001151 if( zIn==0 ) return aff;
1152 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001153 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001154 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001155 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001156 aff = SQLITE_AFF_TEXT;
1157 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001158 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1159 aff = SQLITE_AFF_TEXT;
1160 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1161 aff = SQLITE_AFF_TEXT;
1162 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001163 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001164 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001165 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001166#ifndef SQLITE_OMIT_FLOATING_POINT
1167 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1168 && aff==SQLITE_AFF_NUMERIC ){
1169 aff = SQLITE_AFF_REAL;
1170 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1171 && aff==SQLITE_AFF_NUMERIC ){
1172 aff = SQLITE_AFF_REAL;
1173 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1174 && aff==SQLITE_AFF_NUMERIC ){
1175 aff = SQLITE_AFF_REAL;
1176#endif
danielk1977201f7162005-02-01 02:13:29 +00001177 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001178 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001179 break;
danielk197752a83fb2005-01-31 12:56:44 +00001180 }
1181 }
drhd3037a42013-10-04 18:29:25 +00001182
1183 /* If pszEst is not NULL, store an estimate of the field size. The
1184 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001185 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001186 *pszEst = 1; /* default size is approx 4 bytes */
1187 if( aff<=SQLITE_AFF_NONE ){
1188 if( zChar ){
1189 while( zChar[0] ){
1190 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001191 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001192 sqlite3GetInt32(zChar, &v);
1193 v = v/4 + 1;
1194 if( v>255 ) v = 255;
1195 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1196 break;
1197 }
1198 zChar++;
drhfdaac672013-10-04 15:30:21 +00001199 }
drhd3037a42013-10-04 18:29:25 +00001200 }else{
1201 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001202 }
drhfdaac672013-10-04 15:30:21 +00001203 }
1204 }
danielk1977b3dff962005-02-01 01:21:55 +00001205 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001206}
1207
1208/*
drh382c0242001-10-06 16:33:02 +00001209** This routine is called by the parser while in the middle of
1210** parsing a CREATE TABLE statement. The pFirst token is the first
1211** token in the sequence of tokens that describe the type of the
1212** column currently under construction. pLast is the last token
1213** in the sequence. Use this information to construct a string
1214** that contains the typename of the column and store that string
1215** in zType.
1216*/
drh487e2622005-06-25 18:42:14 +00001217void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001218 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001219 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001220
drhc4a64fa2009-05-11 20:53:28 +00001221 p = pParse->pNewTable;
1222 if( p==0 || NEVER(p->nCol<1) ) return;
1223 pCol = &p->aCol[p->nCol-1];
1224 assert( pCol->zType==0 );
1225 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001226 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001227}
1228
1229/*
danielk19777977a172004-11-09 12:44:37 +00001230** The expression is the default value for the most recently added column
1231** of the table currently under construction.
1232**
1233** Default value expressions must be constant. Raise an exception if this
1234** is not the case.
drhd9b02572001-04-15 00:37:09 +00001235**
1236** This routine is called by the parser while in the middle of
1237** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001238*/
drhb7916a72009-05-27 10:31:29 +00001239void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001240 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001241 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001242 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001243 p = pParse->pNewTable;
1244 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001245 pCol = &(p->aCol[p->nCol-1]);
drhb7916a72009-05-27 10:31:29 +00001246 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
drh42b9d7c2005-08-13 00:56:27 +00001247 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1248 pCol->zName);
1249 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001250 /* A copy of pExpr is used instead of the original, as pExpr contains
1251 ** tokens that point to volatile memory. The 'span' of the expression
1252 ** is required by pragma table_info.
1253 */
drh633e6d52008-07-28 19:34:53 +00001254 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001255 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1256 sqlite3DbFree(db, pCol->zDflt);
1257 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001258 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001259 }
danielk19777977a172004-11-09 12:44:37 +00001260 }
drhb7916a72009-05-27 10:31:29 +00001261 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001262}
1263
1264/*
drh4a324312001-12-21 14:30:42 +00001265** Designate the PRIMARY KEY for the table. pList is a list of names
1266** of columns that form the primary key. If pList is NULL, then the
1267** most recently added column of the table is the primary key.
1268**
1269** A table can have at most one primary key. If the table already has
1270** a primary key (and this is the second primary key) then create an
1271** error.
1272**
1273** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001274** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001275** field of the table under construction to be the index of the
1276** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1277** no INTEGER PRIMARY KEY.
1278**
1279** If the key is not an INTEGER PRIMARY KEY, then create a unique
1280** index for the key. No index is created for INTEGER PRIMARY KEYs.
1281*/
drh205f48e2004-11-05 00:43:11 +00001282void sqlite3AddPrimaryKey(
1283 Parse *pParse, /* Parsing context */
1284 ExprList *pList, /* List of field names to be indexed */
1285 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001286 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1287 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001288){
drh4a324312001-12-21 14:30:42 +00001289 Table *pTab = pParse->pNewTable;
1290 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001291 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001292 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001293 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001294 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001295 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001296 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001297 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001298 }
drh7d10d5a2008-08-20 16:35:10 +00001299 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001300 if( pList==0 ){
1301 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001302 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001303 zType = pTab->aCol[iCol].zType;
1304 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001305 }else{
drh8ea30bf2013-10-22 01:18:17 +00001306 nTerm = pList->nExpr;
1307 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001308 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001309 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001310 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1311 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001312 break;
1313 }
drh78100cc2003-08-23 22:40:53 +00001314 }
drh4a324312001-12-21 14:30:42 +00001315 }
1316 }
drh8ea30bf2013-10-22 01:18:17 +00001317 if( nTerm==1
1318 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1319 && sortOrder==SQLITE_SO_ASC
1320 ){
drh4a324312001-12-21 14:30:42 +00001321 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001322 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001323 assert( autoInc==0 || autoInc==1 );
1324 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001325 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001326 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001327#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001328 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1329 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001330#endif
drh4a324312001-12-21 14:30:42 +00001331 }else{
drhc6bd4e42013-11-02 14:37:18 +00001332 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001333 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001334 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001335 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001336 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001337 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001338 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001339 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001340 }
drhe0194f22003-02-26 13:52:51 +00001341 pList = 0;
drh4a324312001-12-21 14:30:42 +00001342 }
drhe0194f22003-02-26 13:52:51 +00001343
1344primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001345 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001346 return;
drh4a324312001-12-21 14:30:42 +00001347}
1348
1349/*
drhffe07b22005-11-03 00:41:17 +00001350** Add a new CHECK constraint to the table currently under construction.
1351*/
1352void sqlite3AddCheckConstraint(
1353 Parse *pParse, /* Parsing context */
1354 Expr *pCheckExpr /* The check expression */
1355){
1356#ifndef SQLITE_OMIT_CHECK
1357 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001358 sqlite3 *db = pParse->db;
1359 if( pTab && !IN_DECLARE_VTAB
1360 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1361 ){
drh2938f922012-03-07 19:13:29 +00001362 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1363 if( pParse->constraintName.n ){
1364 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1365 }
drh33e619f2009-05-28 01:00:55 +00001366 }else
drhffe07b22005-11-03 00:41:17 +00001367#endif
drh33e619f2009-05-28 01:00:55 +00001368 {
drh2938f922012-03-07 19:13:29 +00001369 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001370 }
drhffe07b22005-11-03 00:41:17 +00001371}
1372
1373/*
drhd3d39e92004-05-20 22:16:29 +00001374** Set the collation function of the most recently parsed table column
1375** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001376*/
danielk197739002502007-11-12 09:50:26 +00001377void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001378 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001379 int i;
danielk197739002502007-11-12 09:50:26 +00001380 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001381 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001382
danielk1977b8cbb872006-06-19 05:33:45 +00001383 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001384 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001385 db = pParse->db;
1386 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001387 if( !zColl ) return;
1388
drhc4a64fa2009-05-11 20:53:28 +00001389 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001390 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001391 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001392 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001393
1394 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1395 ** then an index may have been created on this column before the
1396 ** collation type was added. Correct this if it is the case.
1397 */
1398 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001399 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001400 if( pIdx->aiColumn[0]==i ){
1401 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001402 }
1403 }
danielk197739002502007-11-12 09:50:26 +00001404 }else{
drh633e6d52008-07-28 19:34:53 +00001405 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001406 }
danielk19777cedc8d2004-06-10 10:50:08 +00001407}
1408
danielk1977466be562004-06-10 02:16:01 +00001409/*
1410** This function returns the collation sequence for database native text
1411** encoding identified by the string zName, length nName.
1412**
1413** If the requested collation sequence is not available, or not available
1414** in the database native encoding, the collation factory is invoked to
1415** request it. If the collation factory does not supply such a sequence,
1416** and the sequence is available in another text encoding, then that is
1417** returned instead.
1418**
1419** If no versions of the requested collations sequence are available, or
1420** another error occurs, NULL is returned and an error message written into
1421** pParse.
drha34001c2007-02-02 12:44:37 +00001422**
1423** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1424** invokes the collation factory if the named collation cannot be found
1425** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001426**
1427** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001428*/
drhc4a64fa2009-05-11 20:53:28 +00001429CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001430 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001431 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001432 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001433 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001434
drhc4a64fa2009-05-11 20:53:28 +00001435 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001436 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001437 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001438 }
1439
danielk19770202b292004-06-09 09:55:16 +00001440 return pColl;
1441}
1442
1443
drh8e2ca022002-06-17 17:07:19 +00001444/*
drh3f7d4e42004-07-24 14:35:58 +00001445** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001446**
1447** The schema cookie is used to determine when the schema for the
1448** database changes. After each schema change, the cookie value
1449** changes. When a process first reads the schema it records the
1450** cookie. Thereafter, whenever it goes to access the database,
1451** it checks the cookie to make sure the schema has not changed
1452** since it was last read.
1453**
1454** This plan is not completely bullet-proof. It is possible for
1455** the schema to change multiple times and for the cookie to be
1456** set back to prior value. But schema changes are infrequent
1457** and the probability of hitting the same cookie value is only
1458** 1 chance in 2^32. So we're safe enough.
1459*/
drh9cbf3422008-01-17 16:22:13 +00001460void sqlite3ChangeCookie(Parse *pParse, int iDb){
1461 int r1 = sqlite3GetTempReg(pParse);
1462 sqlite3 *db = pParse->db;
1463 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001464 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001465 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001466 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001467 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001468}
1469
1470/*
drh969fa7c2002-02-18 18:30:32 +00001471** Measure the number of characters needed to output the given
1472** identifier. The number returned includes any quotes used
1473** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001474**
1475** The estimate is conservative. It might be larger that what is
1476** really needed.
drh969fa7c2002-02-18 18:30:32 +00001477*/
1478static int identLength(const char *z){
1479 int n;
drh17f71932002-02-21 12:01:27 +00001480 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001481 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001482 }
drh234c39d2004-07-24 03:30:47 +00001483 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001484}
1485
1486/*
danielk19771b870de2009-03-14 08:37:23 +00001487** The first parameter is a pointer to an output buffer. The second
1488** parameter is a pointer to an integer that contains the offset at
1489** which to write into the output buffer. This function copies the
1490** nul-terminated string pointed to by the third parameter, zSignedIdent,
1491** to the specified offset in the buffer and updates *pIdx to refer
1492** to the first byte after the last byte written before returning.
1493**
1494** If the string zSignedIdent consists entirely of alpha-numeric
1495** characters, does not begin with a digit and is not an SQL keyword,
1496** then it is copied to the output buffer exactly as it is. Otherwise,
1497** it is quoted using double-quotes.
1498*/
drhc4a64fa2009-05-11 20:53:28 +00001499static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001500 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001501 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001502 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001503
drh17f71932002-02-21 12:01:27 +00001504 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001505 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001506 }
drhc7407522014-01-10 20:38:12 +00001507 needQuote = sqlite3Isdigit(zIdent[0])
1508 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1509 || zIdent[j]!=0
1510 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001511
drh234c39d2004-07-24 03:30:47 +00001512 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001513 for(j=0; zIdent[j]; j++){
1514 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001515 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001516 }
drh234c39d2004-07-24 03:30:47 +00001517 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001518 z[i] = 0;
1519 *pIdx = i;
1520}
1521
1522/*
1523** Generate a CREATE TABLE statement appropriate for the given
1524** table. Memory to hold the text of the statement is obtained
1525** from sqliteMalloc() and must be freed by the calling function.
1526*/
drh1d34fde2009-02-03 15:50:33 +00001527static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001528 int i, k, n;
1529 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001530 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001531 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001532 n = 0;
drh234c39d2004-07-24 03:30:47 +00001533 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001534 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001535 }
1536 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001537 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001538 zSep = "";
1539 zSep2 = ",";
1540 zEnd = ")";
1541 }else{
1542 zSep = "\n ";
1543 zSep2 = ",\n ";
1544 zEnd = "\n)";
1545 }
drhe0bc4042002-06-25 01:09:11 +00001546 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001547 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001548 if( zStmt==0 ){
1549 db->mallocFailed = 1;
1550 return 0;
1551 }
drhbdb339f2009-02-02 18:03:21 +00001552 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001553 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001554 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001555 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001556 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001557 static const char * const azType[] = {
1558 /* SQLITE_AFF_TEXT */ " TEXT",
1559 /* SQLITE_AFF_NONE */ "",
1560 /* SQLITE_AFF_NUMERIC */ " NUM",
1561 /* SQLITE_AFF_INTEGER */ " INT",
1562 /* SQLITE_AFF_REAL */ " REAL"
1563 };
1564 int len;
1565 const char *zType;
1566
drh5bb3eb92007-05-04 13:15:55 +00001567 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001568 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001569 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001570 identPut(zStmt, &k, pCol->zName);
1571 assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
drhfcd71b62011-04-05 22:08:24 +00001572 assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001573 testcase( pCol->affinity==SQLITE_AFF_TEXT );
1574 testcase( pCol->affinity==SQLITE_AFF_NONE );
1575 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1576 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1577 testcase( pCol->affinity==SQLITE_AFF_REAL );
1578
1579 zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
1580 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001581 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001582 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001583 memcpy(&zStmt[k], zType, len);
1584 k += len;
1585 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001586 }
drh5bb3eb92007-05-04 13:15:55 +00001587 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001588 return zStmt;
1589}
1590
1591/*
drh7f9c5db2013-10-23 00:32:58 +00001592** Resize an Index object to hold N columns total. Return SQLITE_OK
1593** on success and SQLITE_NOMEM on an OOM error.
1594*/
1595static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1596 char *zExtra;
1597 int nByte;
1598 if( pIdx->nColumn>=N ) return SQLITE_OK;
1599 assert( pIdx->isResized==0 );
1600 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1601 zExtra = sqlite3DbMallocZero(db, nByte);
1602 if( zExtra==0 ) return SQLITE_NOMEM;
1603 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1604 pIdx->azColl = (char**)zExtra;
1605 zExtra += sizeof(char*)*N;
1606 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1607 pIdx->aiColumn = (i16*)zExtra;
1608 zExtra += sizeof(i16)*N;
1609 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1610 pIdx->aSortOrder = (u8*)zExtra;
1611 pIdx->nColumn = N;
1612 pIdx->isResized = 1;
1613 return SQLITE_OK;
1614}
1615
1616/*
drhfdaac672013-10-04 15:30:21 +00001617** Estimate the total row width for a table.
1618*/
drhe13e9f52013-10-05 19:18:00 +00001619static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001620 unsigned wTable = 0;
1621 const Column *pTabCol;
1622 int i;
1623 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1624 wTable += pTabCol->szEst;
1625 }
1626 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001627 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001628}
1629
1630/*
drhe13e9f52013-10-05 19:18:00 +00001631** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001632*/
drhe13e9f52013-10-05 19:18:00 +00001633static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001634 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001635 int i;
1636 const Column *aCol = pIdx->pTable->aCol;
1637 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001638 i16 x = pIdx->aiColumn[i];
1639 assert( x<pIdx->pTable->nCol );
1640 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001641 }
drhe13e9f52013-10-05 19:18:00 +00001642 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001643}
1644
drh7f9c5db2013-10-23 00:32:58 +00001645/* Return true if value x is found any of the first nCol entries of aiCol[]
1646*/
1647static int hasColumn(const i16 *aiCol, int nCol, int x){
1648 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1649 return 0;
1650}
1651
1652/*
drhc6bd4e42013-11-02 14:37:18 +00001653** This routine runs at the end of parsing a CREATE TABLE statement that
1654** has a WITHOUT ROWID clause. The job of this routine is to convert both
1655** internal schema data structures and the generated VDBE code so that they
1656** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1657** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001658**
drhc6bd4e42013-11-02 14:37:18 +00001659** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1660** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1661** data storage is a covering index btree.
1662** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001663** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001664** identified by the sqlite_master table entry of the table itself.
1665** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1666** schema to the rootpage from the main table.
1667** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1668** (5) Add all table columns to the PRIMARY KEY Index object
1669** so that the PRIMARY KEY is a covering index. The surplus
1670** columns are part of KeyInfo.nXField and are not used for
1671** sorting or lookup or uniqueness checks.
1672** (6) Replace the rowid tail on all automatically generated UNIQUE
1673** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001674*/
1675static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1676 Index *pIdx;
1677 Index *pPk;
1678 int nPk;
1679 int i, j;
1680 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001681 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001682
1683 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001684 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001685 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001686 */
1687 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001688 assert( v );
1689 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1690 }
1691
1692 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1693 ** table entry.
1694 */
1695 if( pParse->addrSkipPK ){
1696 assert( v );
1697 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001698 }
1699
1700 /* Locate the PRIMARY KEY index. Or, if this table was originally
1701 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1702 */
1703 if( pTab->iPKey>=0 ){
1704 ExprList *pList;
1705 pList = sqlite3ExprListAppend(pParse, 0, 0);
1706 if( pList==0 ) return;
1707 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1708 pTab->aCol[pTab->iPKey].zName);
1709 pList->a[0].sortOrder = pParse->iPkSortOrder;
1710 assert( pParse->pNewTable==pTab );
1711 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1712 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001713 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001714 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001715 }else{
1716 pPk = sqlite3PrimaryKeyIndex(pTab);
drh7f9c5db2013-10-23 00:32:58 +00001717 }
drh12826092013-11-05 22:39:17 +00001718 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001719 assert( pPk!=0 );
1720 nPk = pPk->nKeyCol;
1721
drhec95c442013-10-23 01:57:32 +00001722 /* Make sure every column of the PRIMARY KEY is NOT NULL */
1723 for(i=0; i<nPk; i++){
1724 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1725 }
drh9eade082013-10-24 14:16:10 +00001726 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001727
drhc6bd4e42013-11-02 14:37:18 +00001728 /* The root page of the PRIMARY KEY is the table root page */
1729 pPk->tnum = pTab->tnum;
1730
drh7f9c5db2013-10-23 00:32:58 +00001731 /* Update the in-memory representation of all UNIQUE indices by converting
1732 ** the final rowid column into one or more columns of the PRIMARY KEY.
1733 */
1734 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1735 int n;
drh48dd1d82014-05-27 18:18:58 +00001736 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001737 for(i=n=0; i<nPk; i++){
1738 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1739 }
drh5a9a37b2013-11-05 17:30:04 +00001740 if( n==0 ){
1741 /* This index is a superset of the primary key */
1742 pIdx->nColumn = pIdx->nKeyCol;
1743 continue;
1744 }
drh7f9c5db2013-10-23 00:32:58 +00001745 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1746 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001747 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001748 pIdx->aiColumn[j] = pPk->aiColumn[i];
1749 pIdx->azColl[j] = pPk->azColl[i];
1750 j++;
1751 }
1752 }
drh00012df2013-11-05 01:59:07 +00001753 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1754 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001755 }
1756
1757 /* Add all table columns to the PRIMARY KEY index
1758 */
1759 if( nPk<pTab->nCol ){
1760 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1761 for(i=0, j=nPk; i<pTab->nCol; i++){
1762 if( !hasColumn(pPk->aiColumn, j, i) ){
1763 assert( j<pPk->nColumn );
1764 pPk->aiColumn[j] = i;
1765 pPk->azColl[j] = "BINARY";
1766 j++;
1767 }
1768 }
1769 assert( pPk->nColumn==j );
1770 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001771 }else{
1772 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001773 }
1774}
1775
drhfdaac672013-10-04 15:30:21 +00001776/*
drh75897232000-05-29 14:26:00 +00001777** This routine is called to report the final ")" that terminates
1778** a CREATE TABLE statement.
1779**
drhf57b3392001-10-08 13:22:32 +00001780** The table structure that other action routines have been building
1781** is added to the internal hash tables, assuming no errors have
1782** occurred.
drh75897232000-05-29 14:26:00 +00001783**
drh1d85d932004-02-14 23:05:52 +00001784** An entry for the table is made in the master table on disk, unless
1785** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001786** it means we are reading the sqlite_master table because we just
1787** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001788** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001789** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001790**
1791** If the pSelect argument is not NULL, it means that this routine
1792** was called to create a table generated from a
1793** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1794** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001795*/
danielk197719a8e7e2005-03-17 05:03:38 +00001796void sqlite3EndTable(
1797 Parse *pParse, /* Parse context */
1798 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001799 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1800 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001801 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1802){
drhfdaac672013-10-04 15:30:21 +00001803 Table *p; /* The new table */
1804 sqlite3 *db = pParse->db; /* The database connection */
1805 int iDb; /* Database in which the table lives */
1806 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001807
drh5969da42013-10-21 02:14:45 +00001808 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1809 return;
danielk1977261919c2005-12-06 12:52:59 +00001810 }
drh28037572000-08-02 13:47:41 +00001811 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001812 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001813
danielk1977517eb642004-06-07 10:00:31 +00001814 assert( !db->init.busy || !pSelect );
1815
drhc6bd4e42013-11-02 14:37:18 +00001816 /* If the db->init.busy is 1 it means we are reading the SQL off the
1817 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1818 ** So do not write to the disk again. Extract the root page number
1819 ** for the table from the db->init.newTnum field. (The page number
1820 ** should have been put there by the sqliteOpenCb routine.)
1821 */
1822 if( db->init.busy ){
1823 p->tnum = db->init.newTnum;
1824 }
1825
1826 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001827 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001828 if( (p->tabFlags & TF_Autoincrement) ){
1829 sqlite3ErrorMsg(pParse,
1830 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1831 return;
1832 }
drh5969da42013-10-21 02:14:45 +00001833 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001834 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001835 }else{
1836 p->tabFlags |= TF_WithoutRowid;
1837 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001838 }
1839 }
1840
drhb9bb7c12006-06-11 23:41:55 +00001841 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001842
drhffe07b22005-11-03 00:41:17 +00001843#ifndef SQLITE_OMIT_CHECK
1844 /* Resolve names in all CHECK constraint expressions.
1845 */
1846 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001847 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001848 }
1849#endif /* !defined(SQLITE_OMIT_CHECK) */
1850
drhe13e9f52013-10-05 19:18:00 +00001851 /* Estimate the average row size for the table and for all implied indices */
1852 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001853 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001854 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001855 }
1856
drhe3c41372001-09-17 20:25:58 +00001857 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001858 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001859 **
drhe0bc4042002-06-25 01:09:11 +00001860 ** If this is a TEMPORARY table, write the entry into the auxiliary
1861 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001862 */
drh1d85d932004-02-14 23:05:52 +00001863 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001864 int n;
drhd8bc7082000-06-07 23:51:50 +00001865 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001866 char *zType; /* "view" or "table" */
1867 char *zType2; /* "VIEW" or "TABLE" */
1868 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001869
danielk19774adee202004-05-08 08:23:19 +00001870 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001871 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001872
drh66a51672008-01-03 00:01:23 +00001873 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001874
drh0fa991b2009-03-21 16:19:26 +00001875 /*
1876 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001877 */
drh4ff6dfa2002-03-03 23:06:00 +00001878 if( p->pSelect==0 ){
1879 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001880 zType = "table";
1881 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001882#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001883 }else{
1884 /* A view */
drh4794f732004-11-05 17:17:50 +00001885 zType = "view";
1886 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001887#endif
drh4ff6dfa2002-03-03 23:06:00 +00001888 }
danielk1977517eb642004-06-07 10:00:31 +00001889
danielk1977517eb642004-06-07 10:00:31 +00001890 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1891 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001892 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001893 **
1894 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1895 ** suitable state to query for the column names and types to be used
1896 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001897 **
1898 ** A shared-cache write-lock is not required to write to the new table,
1899 ** as a schema-lock must have already been obtained to create it. Since
1900 ** a schema-lock excludes all other database users, the write-lock would
1901 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001902 */
1903 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001904 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001905 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001906
danielk19776ab3a2e2009-02-19 14:39:25 +00001907 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001908 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001909 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001910 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001911 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001912 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001913 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001914 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001915 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
drh5969da42013-10-21 02:14:45 +00001916 if( pSelTab==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001917 assert( p->aCol==0 );
1918 p->nCol = pSelTab->nCol;
1919 p->aCol = pSelTab->aCol;
1920 pSelTab->nCol = 0;
1921 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00001922 sqlite3DeleteTable(db, pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001923 }
1924 }
drh4794f732004-11-05 17:17:50 +00001925
drh4794f732004-11-05 17:17:50 +00001926 /* Compute the complete text of the CREATE statement */
1927 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001928 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001929 }else{
drh8ea30bf2013-10-22 01:18:17 +00001930 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1931 n = (int)(pEnd2->z - pParse->sNameToken.z);
1932 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001933 zStmt = sqlite3MPrintf(db,
1934 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1935 );
drh4794f732004-11-05 17:17:50 +00001936 }
1937
1938 /* A slot for the record has already been allocated in the
1939 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001940 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001941 */
1942 sqlite3NestedParse(pParse,
1943 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001944 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1945 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001946 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001947 zType,
1948 p->zName,
1949 p->zName,
drhb7654112008-01-12 12:48:07 +00001950 pParse->regRoot,
1951 zStmt,
1952 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001953 );
drh633e6d52008-07-28 19:34:53 +00001954 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001955 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001956
1957#ifndef SQLITE_OMIT_AUTOINCREMENT
1958 /* Check to see if we need to create an sqlite_sequence table for
1959 ** keeping track of autoincrement keys.
1960 */
drh7d10d5a2008-08-20 16:35:10 +00001961 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001962 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001963 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001964 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001965 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001966 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1967 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001968 );
1969 }
1970 }
1971#endif
drh4794f732004-11-05 17:17:50 +00001972
1973 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00001974 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00001975 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00001976 }
drh17e9e292003-02-01 13:53:28 +00001977
drh2958a4e2004-11-12 03:56:15 +00001978
drh17e9e292003-02-01 13:53:28 +00001979 /* Add the table to the in-memory representation of the database.
1980 */
drh8af73d42009-05-13 22:58:28 +00001981 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00001982 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00001983 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00001984 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00001985 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00001986 if( pOld ){
1987 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001988 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00001989 return;
drh17e9e292003-02-01 13:53:28 +00001990 }
drh17e9e292003-02-01 13:53:28 +00001991 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00001992 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001993
1994#ifndef SQLITE_OMIT_ALTERTABLE
1995 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001996 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001997 int nName;
drh5969da42013-10-21 02:14:45 +00001998 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001999 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002000 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002001 }
drh1bd10f82008-12-10 21:19:56 +00002002 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002003 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002004 }
2005#endif
drh17e9e292003-02-01 13:53:28 +00002006 }
drh75897232000-05-29 14:26:00 +00002007}
2008
drhb7f91642004-10-31 02:22:47 +00002009#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002010/*
drha76b5df2002-02-23 02:32:10 +00002011** The parser calls this routine in order to create a new VIEW
2012*/
danielk19774adee202004-05-08 08:23:19 +00002013void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002014 Parse *pParse, /* The parsing context */
2015 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002016 Token *pName1, /* The token that holds the name of the view */
2017 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002018 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002019 int isTemp, /* TRUE for a TEMPORARY view */
2020 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002021){
drha76b5df2002-02-23 02:32:10 +00002022 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002023 int n;
drhb7916a72009-05-27 10:31:29 +00002024 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002025 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002026 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002027 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002028 int iDb;
drh17435752007-08-16 04:30:38 +00002029 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002030
drh7c3d64f2005-06-06 15:32:08 +00002031 if( pParse->nVar>0 ){
2032 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002033 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002034 return;
2035 }
drhfdd48a72006-09-11 23:45:48 +00002036 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002037 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002038 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002039 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002040 return;
2041 }
danielk1977ef2cb632004-05-29 02:37:19 +00002042 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002043 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002044 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2045 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002046 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002047 return;
2048 }
drh174b6192002-12-03 02:22:52 +00002049
drh4b59ab52002-08-24 18:24:51 +00002050 /* Make a copy of the entire SELECT statement that defines the view.
2051 ** This will force all the Expr.token.z values to be dynamically
2052 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002053 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002054 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002055 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002056 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002057 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002058 return;
2059 }
drh17435752007-08-16 04:30:38 +00002060 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002061 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002062 }
drh4b59ab52002-08-24 18:24:51 +00002063
2064 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2065 ** the end.
2066 */
drha76b5df2002-02-23 02:32:10 +00002067 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002068 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002069 sEnd.z += sEnd.n;
2070 }
2071 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002072 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002073 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002074 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002075 sEnd.z = &z[n-1];
2076 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002077
danielk19774adee202004-05-08 08:23:19 +00002078 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002079 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002080 return;
drh417be792002-03-03 18:59:40 +00002081}
drhb7f91642004-10-31 02:22:47 +00002082#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002083
danielk1977fe3fcbe22006-06-12 12:08:45 +00002084#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002085/*
2086** The Table structure pTable is really a VIEW. Fill in the names of
2087** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002088** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002089*/
danielk19774adee202004-05-08 08:23:19 +00002090int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002091 Table *pSelTab; /* A fake table from which we get the result set */
2092 Select *pSel; /* Copy of the SELECT that implements the view */
2093 int nErr = 0; /* Number of errors encountered */
2094 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002095 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002096 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002097
2098 assert( pTable );
2099
danielk1977fe3fcbe22006-06-12 12:08:45 +00002100#ifndef SQLITE_OMIT_VIRTUALTABLE
2101 if( sqlite3VtabCallConnect(pParse, pTable) ){
2102 return SQLITE_ERROR;
2103 }
drh4cbdda92006-06-14 19:00:20 +00002104 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002105#endif
2106
2107#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002108 /* A positive nCol means the columns names for this view are
2109 ** already known.
2110 */
2111 if( pTable->nCol>0 ) return 0;
2112
2113 /* A negative nCol is a special marker meaning that we are currently
2114 ** trying to compute the column names. If we enter this routine with
2115 ** a negative nCol, it means two or more views form a loop, like this:
2116 **
2117 ** CREATE VIEW one AS SELECT * FROM two;
2118 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002119 **
drh768578e2009-05-12 00:40:12 +00002120 ** Actually, the error above is now caught prior to reaching this point.
2121 ** But the following test is still important as it does come up
2122 ** in the following:
2123 **
2124 ** CREATE TABLE main.ex1(a);
2125 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2126 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002127 */
2128 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002129 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002130 return 1;
2131 }
drh85c23c62005-08-20 03:03:04 +00002132 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002133
2134 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002135 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2136 ** "*" elements in the results set of the view and will assign cursors
2137 ** to the elements of the FROM clause. But we do not want these changes
2138 ** to be permanent. So the computation is done on a copy of the SELECT
2139 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002140 */
drh9b3187e2005-01-18 14:45:47 +00002141 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002142 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002143 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002144 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002145 n = pParse->nTab;
2146 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2147 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002148 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002149#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002150 xAuth = db->xAuth;
2151 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002152 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002153 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002154#else
drh7d10d5a2008-08-20 16:35:10 +00002155 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002156#endif
drhd9da78a2009-03-24 15:08:09 +00002157 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002158 pParse->nTab = n;
2159 if( pSelTab ){
2160 assert( pTable->aCol==0 );
2161 pTable->nCol = pSelTab->nCol;
2162 pTable->aCol = pSelTab->aCol;
2163 pSelTab->nCol = 0;
2164 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002165 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002166 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002167 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002168 }else{
2169 pTable->nCol = 0;
2170 nErr++;
2171 }
drh633e6d52008-07-28 19:34:53 +00002172 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002173 } else {
drh417be792002-03-03 18:59:40 +00002174 nErr++;
2175 }
drhb7f91642004-10-31 02:22:47 +00002176#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002177 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002178}
2179#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002180
drhb7f91642004-10-31 02:22:47 +00002181#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002182/*
drh8bf8dc92003-05-17 17:35:10 +00002183** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002184*/
drh9bb575f2004-09-06 17:24:11 +00002185static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002186 HashElem *i;
drh21206082011-04-04 18:22:02 +00002187 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002188 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002189 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002190 Table *pTab = sqliteHashData(i);
2191 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002192 sqliteDeleteColumnNames(db, pTab);
2193 pTab->aCol = 0;
2194 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002195 }
2196 }
drh8bf8dc92003-05-17 17:35:10 +00002197 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002198}
drhb7f91642004-10-31 02:22:47 +00002199#else
2200# define sqliteViewResetAll(A,B)
2201#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002202
drh75897232000-05-29 14:26:00 +00002203/*
danielk1977a0bf2652004-11-04 14:30:04 +00002204** This function is called by the VDBE to adjust the internal schema
2205** used by SQLite when the btree layer moves a table root page. The
2206** root-page of a table or index in database iDb has changed from iFrom
2207** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002208**
2209** Ticket #1728: The symbol table might still contain information
2210** on tables and/or indices that are the process of being deleted.
2211** If you are unlucky, one of those deleted indices or tables might
2212** have the same rootpage number as the real table or index that is
2213** being moved. So we cannot stop searching after the first match
2214** because the first match might be for one of the deleted indices
2215** or tables and not the table/index that is actually being moved.
2216** We must continue looping until all tables and indices with
2217** rootpage==iFrom have been converted to have a rootpage of iTo
2218** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002219*/
2220#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002221void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002222 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002223 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002224 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002225
drhcdf011d2011-04-04 21:25:28 +00002226 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2227 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002228 pHash = &pDb->pSchema->tblHash;
2229 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002230 Table *pTab = sqliteHashData(pElem);
2231 if( pTab->tnum==iFrom ){
2232 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002233 }
2234 }
danielk1977da184232006-01-05 11:34:32 +00002235 pHash = &pDb->pSchema->idxHash;
2236 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002237 Index *pIdx = sqliteHashData(pElem);
2238 if( pIdx->tnum==iFrom ){
2239 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002240 }
2241 }
danielk1977a0bf2652004-11-04 14:30:04 +00002242}
2243#endif
2244
2245/*
2246** Write code to erase the table with root-page iTable from database iDb.
2247** Also write code to modify the sqlite_master table and internal schema
2248** if a root-page of another table is moved by the btree-layer whilst
2249** erasing iTable (this can happen with an auto-vacuum database).
2250*/
drh4e0cff62004-11-05 05:10:28 +00002251static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2252 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002253 int r1 = sqlite3GetTempReg(pParse);
2254 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002255 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002256#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002257 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002258 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002259 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002260 ** reflect this.
2261 **
drh0fa991b2009-03-21 16:19:26 +00002262 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002263 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2264 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002265 */
danielk197763e3e9f2004-11-05 09:19:27 +00002266 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002267 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2268 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002269#endif
drhb7654112008-01-12 12:48:07 +00002270 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002271}
2272
2273/*
2274** Write VDBE code to erase table pTab and all associated indices on disk.
2275** Code to update the sqlite_master tables and internal schema definitions
2276** in case a root-page belonging to another table is moved by the btree layer
2277** is also added (this can happen with an auto-vacuum database).
2278*/
drh4e0cff62004-11-05 05:10:28 +00002279static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002280#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002281 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002282 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2283 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002284 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002285 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002286 }
2287#else
2288 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2289 ** is not defined), then it is important to call OP_Destroy on the
2290 ** table and index root-pages in order, starting with the numerically
2291 ** largest root-page number. This guarantees that none of the root-pages
2292 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2293 ** following were coded:
2294 **
2295 ** OP_Destroy 4 0
2296 ** ...
2297 ** OP_Destroy 5 0
2298 **
2299 ** and root page 5 happened to be the largest root-page number in the
2300 ** database, then root page 5 would be moved to page 4 by the
2301 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2302 ** a free-list page.
2303 */
2304 int iTab = pTab->tnum;
2305 int iDestroyed = 0;
2306
2307 while( 1 ){
2308 Index *pIdx;
2309 int iLargest = 0;
2310
2311 if( iDestroyed==0 || iTab<iDestroyed ){
2312 iLargest = iTab;
2313 }
2314 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2315 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002316 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002317 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2318 iLargest = iIdx;
2319 }
2320 }
danielk1977da184232006-01-05 11:34:32 +00002321 if( iLargest==0 ){
2322 return;
2323 }else{
2324 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002325 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002326 destroyRootPage(pParse, iLargest, iDb);
2327 iDestroyed = iLargest;
2328 }
danielk1977a0bf2652004-11-04 14:30:04 +00002329 }
2330#endif
2331}
2332
2333/*
drh74e7c8f2011-10-21 19:06:32 +00002334** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002335** after a DROP INDEX or DROP TABLE command.
2336*/
2337static void sqlite3ClearStatTables(
2338 Parse *pParse, /* The parsing context */
2339 int iDb, /* The database number */
2340 const char *zType, /* "idx" or "tbl" */
2341 const char *zName /* Name of index or table */
2342){
drha5ae4c32011-08-07 01:31:52 +00002343 int i;
2344 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002345 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002346 char zTab[24];
2347 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2348 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002349 sqlite3NestedParse(pParse,
2350 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002351 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002352 );
2353 }
2354 }
2355}
2356
2357/*
drhfaacf172011-08-12 01:51:45 +00002358** Generate code to drop a table.
2359*/
2360void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2361 Vdbe *v;
2362 sqlite3 *db = pParse->db;
2363 Trigger *pTrigger;
2364 Db *pDb = &db->aDb[iDb];
2365
2366 v = sqlite3GetVdbe(pParse);
2367 assert( v!=0 );
2368 sqlite3BeginWriteOperation(pParse, 1, iDb);
2369
2370#ifndef SQLITE_OMIT_VIRTUALTABLE
2371 if( IsVirtual(pTab) ){
2372 sqlite3VdbeAddOp0(v, OP_VBegin);
2373 }
2374#endif
2375
2376 /* Drop all triggers associated with the table being dropped. Code
2377 ** is generated to remove entries from sqlite_master and/or
2378 ** sqlite_temp_master if required.
2379 */
2380 pTrigger = sqlite3TriggerList(pParse, pTab);
2381 while( pTrigger ){
2382 assert( pTrigger->pSchema==pTab->pSchema ||
2383 pTrigger->pSchema==db->aDb[1].pSchema );
2384 sqlite3DropTriggerPtr(pParse, pTrigger);
2385 pTrigger = pTrigger->pNext;
2386 }
2387
2388#ifndef SQLITE_OMIT_AUTOINCREMENT
2389 /* Remove any entries of the sqlite_sequence table associated with
2390 ** the table being dropped. This is done before the table is dropped
2391 ** at the btree level, in case the sqlite_sequence table needs to
2392 ** move as a result of the drop (can happen in auto-vacuum mode).
2393 */
2394 if( pTab->tabFlags & TF_Autoincrement ){
2395 sqlite3NestedParse(pParse,
2396 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2397 pDb->zName, pTab->zName
2398 );
2399 }
2400#endif
2401
2402 /* Drop all SQLITE_MASTER table and index entries that refer to the
2403 ** table. The program name loops through the master table and deletes
2404 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002405 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002406 ** created in the temp database that refers to a table in another
2407 ** database.
2408 */
2409 sqlite3NestedParse(pParse,
2410 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2411 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002412 if( !isView && !IsVirtual(pTab) ){
2413 destroyTable(pParse, pTab);
2414 }
2415
2416 /* Remove the table entry from SQLite's internal schema and modify
2417 ** the schema cookie.
2418 */
2419 if( IsVirtual(pTab) ){
2420 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2421 }
2422 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2423 sqlite3ChangeCookie(pParse, iDb);
2424 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002425}
2426
2427/*
drh75897232000-05-29 14:26:00 +00002428** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002429** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002430*/
drha0733842005-12-29 01:11:36 +00002431void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002432 Table *pTab;
drh75897232000-05-29 14:26:00 +00002433 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002434 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002435 int iDb;
drh75897232000-05-29 14:26:00 +00002436
drh8af73d42009-05-13 22:58:28 +00002437 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002438 goto exit_drop_table;
2439 }
drh8af73d42009-05-13 22:58:28 +00002440 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002441 assert( pName->nSrc==1 );
drha7564662010-02-22 19:32:31 +00002442 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002443 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002444 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002445
drha0733842005-12-29 01:11:36 +00002446 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002447 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002448 goto exit_drop_table;
2449 }
danielk1977da184232006-01-05 11:34:32 +00002450 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002451 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002452
2453 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2454 ** it is initialized.
2455 */
2456 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2457 goto exit_drop_table;
2458 }
drhe5f9c642003-01-13 23:27:31 +00002459#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002460 {
2461 int code;
danielk1977da184232006-01-05 11:34:32 +00002462 const char *zTab = SCHEMA_TABLE(iDb);
2463 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002464 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002465 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002466 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002467 }
drhe5f9c642003-01-13 23:27:31 +00002468 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002469 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002470 code = SQLITE_DROP_TEMP_VIEW;
2471 }else{
2472 code = SQLITE_DROP_VIEW;
2473 }
danielk19774b2688a2006-06-20 11:01:07 +00002474#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002475 }else if( IsVirtual(pTab) ){
2476 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002477 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002478#endif
drhe5f9c642003-01-13 23:27:31 +00002479 }else{
danielk197753c0f742005-03-29 03:10:59 +00002480 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002481 code = SQLITE_DROP_TEMP_TABLE;
2482 }else{
2483 code = SQLITE_DROP_TABLE;
2484 }
2485 }
danielk1977f1a381e2006-06-16 08:01:02 +00002486 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002487 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002488 }
danielk1977a8858102004-05-28 12:11:21 +00002489 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2490 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002491 }
drhe5f9c642003-01-13 23:27:31 +00002492 }
2493#endif
drh08ccfaa2011-10-07 23:52:25 +00002494 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2495 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002496 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002497 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002498 }
danielk1977576ec6b2005-01-21 11:55:25 +00002499
2500#ifndef SQLITE_OMIT_VIEW
2501 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2502 ** on a table.
2503 */
danielk1977a8858102004-05-28 12:11:21 +00002504 if( isView && pTab->pSelect==0 ){
2505 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2506 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002507 }
danielk1977a8858102004-05-28 12:11:21 +00002508 if( !isView && pTab->pSelect ){
2509 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2510 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002511 }
danielk1977576ec6b2005-01-21 11:55:25 +00002512#endif
drh75897232000-05-29 14:26:00 +00002513
drh1ccde152000-06-17 13:12:39 +00002514 /* Generate code to remove the table from the master table
2515 ** on disk.
2516 */
danielk19774adee202004-05-08 08:23:19 +00002517 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002518 if( v ){
drh77658e22007-12-04 16:54:52 +00002519 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002520 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002521 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002522 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002523 }
danielk1977a8858102004-05-28 12:11:21 +00002524
2525exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002526 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002527}
2528
2529/*
drhc2eef3b2002-08-31 18:53:06 +00002530** This routine is called to create a new foreign key on the table
2531** currently under construction. pFromCol determines which columns
2532** in the current table point to the foreign key. If pFromCol==0 then
2533** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002534** the table referred to (a.k.a the "parent" table). pToCol is a list
2535** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002536** information about the conflict resolution algorithms specified
2537** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2538**
2539** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002540** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002541**
2542** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002543** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002544*/
danielk19774adee202004-05-08 08:23:19 +00002545void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002546 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002547 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002548 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002549 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002550 int flags /* Conflict resolution algorithms. */
2551){
danielk197718576932008-08-06 13:47:40 +00002552 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002553#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002554 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002555 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002556 Table *p = pParse->pNewTable;
2557 int nByte;
2558 int i;
2559 int nCol;
2560 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002561
2562 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002563 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002564 if( pFromCol==0 ){
2565 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002566 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002567 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002568 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002569 " should reference only one column of table %T",
2570 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002571 goto fk_end;
2572 }
2573 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002574 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002575 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002576 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002577 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002578 goto fk_end;
2579 }else{
danielk19770202b292004-06-09 09:55:16 +00002580 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002581 }
drhe61922a2009-05-02 13:29:37 +00002582 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002583 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002584 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002585 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002586 }
2587 }
drh633e6d52008-07-28 19:34:53 +00002588 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002589 if( pFKey==0 ){
2590 goto fk_end;
2591 }
drhc2eef3b2002-08-31 18:53:06 +00002592 pFKey->pFrom = p;
2593 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002594 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002595 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002596 memcpy(z, pTo->z, pTo->n);
2597 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002598 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002599 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002600 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002601 if( pFromCol==0 ){
2602 pFKey->aCol[0].iFrom = p->nCol-1;
2603 }else{
2604 for(i=0; i<nCol; i++){
2605 int j;
2606 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002607 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002608 pFKey->aCol[i].iFrom = j;
2609 break;
2610 }
2611 }
2612 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002613 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002614 "unknown column \"%s\" in foreign key definition",
2615 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002616 goto fk_end;
2617 }
2618 }
2619 }
2620 if( pToCol ){
2621 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002622 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002623 pFKey->aCol[i].zCol = z;
2624 memcpy(z, pToCol->a[i].zName, n);
2625 z[n] = 0;
2626 z += n+1;
2627 }
2628 }
2629 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002630 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2631 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002632
drh21206082011-04-04 18:22:02 +00002633 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002634 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002635 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002636 );
danf59c5ca2009-09-22 16:55:38 +00002637 if( pNextTo==pFKey ){
2638 db->mallocFailed = 1;
2639 goto fk_end;
2640 }
dan1da40a32009-09-19 17:00:31 +00002641 if( pNextTo ){
2642 assert( pNextTo->pPrevTo==0 );
2643 pFKey->pNextTo = pNextTo;
2644 pNextTo->pPrevTo = pFKey;
2645 }
2646
drhc2eef3b2002-08-31 18:53:06 +00002647 /* Link the foreign key to the table as the last step.
2648 */
2649 p->pFKey = pFKey;
2650 pFKey = 0;
2651
2652fk_end:
drh633e6d52008-07-28 19:34:53 +00002653 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002654#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002655 sqlite3ExprListDelete(db, pFromCol);
2656 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002657}
2658
2659/*
2660** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2661** clause is seen as part of a foreign key definition. The isDeferred
2662** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2663** The behavior of the most recently created foreign key is adjusted
2664** accordingly.
2665*/
danielk19774adee202004-05-08 08:23:19 +00002666void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002667#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002668 Table *pTab;
2669 FKey *pFKey;
2670 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002671 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002672 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002673#endif
drhc2eef3b2002-08-31 18:53:06 +00002674}
2675
2676/*
drh063336a2004-11-05 20:58:39 +00002677** Generate code that will erase and refill index *pIdx. This is
2678** used to initialize a newly created index or to recompute the
2679** content of an index in response to a REINDEX command.
2680**
2681** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002682** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002683** root page number of the index. If memRootPage is negative, then
2684** the index already exists and must be cleared before being refilled and
2685** the root page number of the index is taken from pIndex->tnum.
2686*/
2687static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2688 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002689 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2690 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002691 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002692 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002693 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002694 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002695 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002696 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002697 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002698 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002699 sqlite3 *db = pParse->db; /* The database connection */
2700 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002701
danielk19771d54df82004-11-23 15:41:16 +00002702#ifndef SQLITE_OMIT_AUTHORIZATION
2703 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002704 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002705 return;
2706 }
2707#endif
2708
danielk1977c00da102006-01-07 13:21:04 +00002709 /* Require a write-lock on the table to perform this operation */
2710 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2711
drh063336a2004-11-05 20:58:39 +00002712 v = sqlite3GetVdbe(pParse);
2713 if( v==0 ) return;
2714 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002715 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002716 }else{
2717 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002718 }
drh2ec2fb22013-11-06 19:59:23 +00002719 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002720
dan689ab892011-08-12 15:02:00 +00002721 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002722 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002723 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002724 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002725
2726 /* Open the table. Loop through all rows of the table, inserting index
2727 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002728 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002729 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002730 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002731
drh1c2c0b72014-01-04 19:27:05 +00002732 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002733 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002734 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002735 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002736 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002737 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2738 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002739 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002740 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2741
drh688852a2014-02-17 22:40:43 +00002742 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002743 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002744 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002745 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2746 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2747 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002748 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002749 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002750 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002751 }else{
2752 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002753 }
drhca892a72011-09-03 00:17:51 +00002754 sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
2755 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
2756 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002757 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002758 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002759 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002760
drh66a51672008-01-03 00:01:23 +00002761 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2762 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002763 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002764}
2765
2766/*
drh77e57df2013-10-22 14:28:02 +00002767** Allocate heap space to hold an Index object with nCol columns.
2768**
2769** Increase the allocation size to provide an extra nExtra bytes
2770** of 8-byte aligned space after the Index object and return a
2771** pointer to this extra space in *ppExtra.
2772*/
2773Index *sqlite3AllocateIndexObject(
2774 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002775 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002776 int nExtra, /* Number of bytes of extra space to alloc */
2777 char **ppExtra /* Pointer to the "extra" space */
2778){
2779 Index *p; /* Allocated index object */
2780 int nByte; /* Bytes of space for Index object + arrays */
2781
2782 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2783 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002784 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002785 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002786 sizeof(u8)*nCol); /* Index.aSortOrder */
2787 p = sqlite3DbMallocZero(db, nByte + nExtra);
2788 if( p ){
2789 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002790 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2791 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2792 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002793 p->aSortOrder = (u8*)pExtra;
2794 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002795 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002796 *ppExtra = ((char*)p) + nByte;
2797 }
2798 return p;
2799}
2800
2801/*
drh23bf66d2004-12-14 03:34:34 +00002802** Create a new index for an SQL table. pName1.pName2 is the name of the index
2803** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002804** be NULL for a primary key or an index that is created to satisfy a
2805** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002806** as the table to be indexed. pParse->pNewTable is a table that is
2807** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002808**
drh382c0242001-10-06 16:33:02 +00002809** pList is a list of columns to be indexed. pList will be NULL if this
2810** is a primary key or unique-constraint on the most recent column added
2811** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002812**
2813** If the index is created successfully, return a pointer to the new Index
2814** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002815** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002816*/
dan1da40a32009-09-19 17:00:31 +00002817Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002818 Parse *pParse, /* All information about this parse */
2819 Token *pName1, /* First part of index name. May be NULL */
2820 Token *pName2, /* Second part of index name. May be NULL */
2821 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002822 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002823 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002824 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002825 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002826 int sortOrder, /* Sort order of primary key when pList==NULL */
2827 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002828){
dan1da40a32009-09-19 17:00:31 +00002829 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002830 Table *pTab = 0; /* Table to be indexed */
2831 Index *pIndex = 0; /* The index to be created */
2832 char *zName = 0; /* Name of the index */
2833 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002834 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002835 DbFixer sFix; /* For assigning database names to pTable */
2836 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002837 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002838 Db *pDb; /* The specific table containing the indexed database */
2839 int iDb; /* Index of the database that is being written */
2840 Token *pName = 0; /* Unqualified name of the index to create */
2841 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002842 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002843 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002844 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002845 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002846 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002847
drh8af73d42009-05-13 22:58:28 +00002848 assert( pParse->nErr==0 ); /* Never called with prior errors */
2849 if( db->mallocFailed || IN_DECLARE_VTAB ){
drhd3001712009-05-12 17:46:53 +00002850 goto exit_create_index;
2851 }
2852 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002853 goto exit_create_index;
2854 }
drhdaffd0e2001-04-11 14:28:42 +00002855
drh75897232000-05-29 14:26:00 +00002856 /*
2857 ** Find the table that is to be indexed. Return early if not found.
2858 */
danielk1977cbb18d22004-05-28 11:37:27 +00002859 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002860
2861 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002862 ** to search for the table. 'Fix' the table name to this db
2863 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002864 */
2865 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002866 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002867 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002868 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002869
danielk197753c0f742005-03-29 03:10:59 +00002870#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002871 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002872 ** is a temp table. If so, set the database to 1. Do not do this
2873 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002874 */
danielk1977fe910332007-12-02 11:46:34 +00002875 if( !db->init.busy ){
2876 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002877 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002878 iDb = 1;
2879 }
danielk1977ef2cb632004-05-29 02:37:19 +00002880 }
danielk197753c0f742005-03-29 03:10:59 +00002881#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002882
drhd100f692013-10-03 15:39:44 +00002883 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2884 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002885 /* Because the parser constructs pTblName from a single identifier,
2886 ** sqlite3FixSrcList can never fail. */
2887 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002888 }
dan41fb5cd2012-10-04 19:33:00 +00002889 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002890 assert( db->mallocFailed==0 || pTab==0 );
2891 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002892 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2893 sqlite3ErrorMsg(pParse,
2894 "cannot create a TEMP index on non-TEMP table \"%s\"",
2895 pTab->zName);
2896 goto exit_create_index;
2897 }
drh44156282013-10-23 22:23:03 +00002898 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002899 }else{
drhe3c41372001-09-17 20:25:58 +00002900 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002901 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002902 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002903 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002904 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002905 }
drhfdd6e852005-12-16 01:06:16 +00002906 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002907
drhd3001712009-05-12 17:46:53 +00002908 assert( pTab!=0 );
2909 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002910 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drhd4530972014-09-09 14:47:53 +00002911#if SQLITE_USER_AUTHENTICATION
2912 && sqlite3UserAuthTable(pTab->zName)==0
2913#endif
drh503a6862013-03-01 01:07:17 +00002914 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002915 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002916 goto exit_create_index;
2917 }
danielk1977576ec6b2005-01-21 11:55:25 +00002918#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002919 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002920 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002921 goto exit_create_index;
2922 }
danielk1977576ec6b2005-01-21 11:55:25 +00002923#endif
danielk19775ee9d692006-06-21 12:36:25 +00002924#ifndef SQLITE_OMIT_VIRTUALTABLE
2925 if( IsVirtual(pTab) ){
2926 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2927 goto exit_create_index;
2928 }
2929#endif
drh75897232000-05-29 14:26:00 +00002930
2931 /*
2932 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002933 ** index or table with the same name.
2934 **
2935 ** Exception: If we are reading the names of permanent indices from the
2936 ** sqlite_master table (because some other process changed the schema) and
2937 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002938 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002939 **
2940 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002941 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2942 ** own name.
drh75897232000-05-29 14:26:00 +00002943 */
danielk1977d8123362004-06-12 09:25:12 +00002944 if( pName ){
drh17435752007-08-16 04:30:38 +00002945 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002946 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002947 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002948 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002949 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002950 }
danielk1977d8123362004-06-12 09:25:12 +00002951 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002952 if( sqlite3FindTable(db, zName, 0)!=0 ){
2953 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2954 goto exit_create_index;
2955 }
2956 }
danielk197759a33f92007-03-17 10:26:59 +00002957 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2958 if( !ifNotExist ){
2959 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002960 }else{
2961 assert( !db->init.busy );
2962 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002963 }
danielk197759a33f92007-03-17 10:26:59 +00002964 goto exit_create_index;
2965 }
danielk1977a21c6b62005-01-24 10:25:59 +00002966 }else{
drhadbca9c2001-09-27 15:11:53 +00002967 int n;
2968 Index *pLoop;
2969 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002970 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002971 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002972 goto exit_create_index;
2973 }
drh75897232000-05-29 14:26:00 +00002974 }
2975
drhe5f9c642003-01-13 23:27:31 +00002976 /* Check for authorization to create an index.
2977 */
2978#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002979 {
drhfdd6e852005-12-16 01:06:16 +00002980 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002981 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002982 goto exit_create_index;
2983 }
2984 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002985 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002986 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002987 goto exit_create_index;
2988 }
drhe5f9c642003-01-13 23:27:31 +00002989 }
2990#endif
2991
drh75897232000-05-29 14:26:00 +00002992 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002993 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002994 ** So create a fake list to simulate this.
2995 */
2996 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00002997 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00002998 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00002999 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
3000 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00003001 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00003002 }
3003
danielk1977b3bf5562006-01-10 17:58:23 +00003004 /* Figure out how many bytes of space are required to store explicitly
3005 ** specified collation sequence names.
3006 */
3007 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003008 Expr *pExpr = pList->a[i].pExpr;
3009 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00003010 assert( pExpr->op==TK_COLLATE );
3011 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003012 }
3013 }
3014
drh75897232000-05-29 14:26:00 +00003015 /*
3016 ** Allocate the index structure.
3017 */
drhea678832008-12-10 19:26:22 +00003018 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003019 nExtraCol = pPk ? pPk->nKeyCol : 1;
3020 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003021 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003022 if( db->mallocFailed ){
3023 goto exit_create_index;
3024 }
dancfc9df72014-04-25 15:01:01 +00003025 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003026 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003027 pIndex->zName = zExtra;
3028 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003029 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003030 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003031 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003032 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003033 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003034 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003035 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003036 if( pPIWhere ){
3037 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3038 pIndex->pPartIdxWhere = pPIWhere;
3039 pPIWhere = 0;
3040 }
drh21206082011-04-04 18:22:02 +00003041 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003042
drhfdd6e852005-12-16 01:06:16 +00003043 /* Check to see if we should honor DESC requests on index columns
3044 */
danielk1977da184232006-01-05 11:34:32 +00003045 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003046 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003047 }else{
3048 sortOrderMask = 0; /* Ignore DESC */
3049 }
3050
drh1ccde152000-06-17 13:12:39 +00003051 /* Scan the names of the columns of the table to be indexed and
3052 ** load the column indices into the Index structure. Report an error
3053 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003054 **
3055 ** TODO: Add a test to make sure that the same column is not named
3056 ** more than once within the same index. Only the first instance of
3057 ** the column will ever be used by the optimizer. Note that using the
3058 ** same column more than once cannot be an error because that would
3059 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003060 */
drhfdd6e852005-12-16 01:06:16 +00003061 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3062 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003063 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003064 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003065
drhfdd6e852005-12-16 01:06:16 +00003066 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3067 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003068 }
3069 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003070 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003071 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003072 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003073 goto exit_create_index;
3074 }
drhbf20a352014-04-04 22:44:59 +00003075 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003076 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003077 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003078 int nColl;
dan911ce412013-05-15 15:16:50 +00003079 assert( pListItem->pExpr->op==TK_COLLATE );
3080 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003081 nColl = sqlite3Strlen30(zColl) + 1;
3082 assert( nExtra>=nColl );
3083 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003084 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003085 zExtra += nColl;
3086 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003087 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003088 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003089 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003090 }
drhb7f24de2009-05-13 17:35:23 +00003091 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003092 goto exit_create_index;
3093 }
danielk1977b3bf5562006-01-10 17:58:23 +00003094 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003095 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003096 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003097 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003098 }
drh44156282013-10-23 22:23:03 +00003099 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003100 for(j=0; j<pPk->nKeyCol; j++){
3101 int x = pPk->aiColumn[j];
3102 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3103 pIndex->nColumn--;
3104 }else{
3105 pIndex->aiColumn[i] = x;
3106 pIndex->azColl[i] = pPk->azColl[j];
3107 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3108 i++;
3109 }
drh44156282013-10-23 22:23:03 +00003110 }
drh7913e412013-11-01 20:30:36 +00003111 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003112 }else{
3113 pIndex->aiColumn[i] = -1;
3114 pIndex->azColl[i] = "BINARY";
3115 }
drh51147ba2005-07-23 22:59:55 +00003116 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003117 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003118
danielk1977d8123362004-06-12 09:25:12 +00003119 if( pTab==pParse->pNewTable ){
3120 /* This routine has been called to create an automatic index as a
3121 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3122 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3123 ** i.e. one of:
3124 **
3125 ** CREATE TABLE t(x PRIMARY KEY, y);
3126 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3127 **
3128 ** Either way, check to see if the table already has such an index. If
3129 ** so, don't bother creating this one. This only applies to
3130 ** automatically created indices. Users can do as they wish with
3131 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003132 **
3133 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3134 ** (and thus suppressing the second one) even if they have different
3135 ** sort orders.
3136 **
3137 ** If there are different collating sequences or if the columns of
3138 ** the constraint occur in different orders, then the constraints are
3139 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003140 */
3141 Index *pIdx;
3142 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3143 int k;
drh5f1d1d92014-07-31 22:59:04 +00003144 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003145 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003146 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003147
drhbbbdc832013-10-22 18:01:40 +00003148 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3149 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003150 const char *z1;
3151 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003152 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003153 z1 = pIdx->azColl[k];
3154 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003155 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003156 }
drhbbbdc832013-10-22 18:01:40 +00003157 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003158 if( pIdx->onError!=pIndex->onError ){
3159 /* This constraint creates the same index as a previous
3160 ** constraint specified somewhere in the CREATE TABLE statement.
3161 ** However the ON CONFLICT clauses are different. If both this
3162 ** constraint and the previous equivalent constraint have explicit
3163 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003164 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003165 */
3166 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3167 sqlite3ErrorMsg(pParse,
3168 "conflicting ON CONFLICT clauses specified", 0);
3169 }
3170 if( pIdx->onError==OE_Default ){
3171 pIdx->onError = pIndex->onError;
3172 }
3173 }
danielk1977d8123362004-06-12 09:25:12 +00003174 goto exit_create_index;
3175 }
3176 }
3177 }
3178
drh75897232000-05-29 14:26:00 +00003179 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003180 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003181 */
drh234c39d2004-07-24 03:30:47 +00003182 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003183 Index *p;
drh21206082011-04-04 18:22:02 +00003184 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003185 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003186 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003187 if( p ){
3188 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003189 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003190 goto exit_create_index;
3191 }
drh5e00f6c2001-09-13 13:46:56 +00003192 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003193 if( pTblName!=0 ){
3194 pIndex->tnum = db->init.newTnum;
3195 }
drhd78eeee2001-09-13 16:18:53 +00003196 }
3197
drh58383402013-11-04 17:00:50 +00003198 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3199 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3200 ** emit code to allocate the index rootpage on disk and make an entry for
3201 ** the index in the sqlite_master table and populate the index with
3202 ** content. But, do not do this if we are simply reading the sqlite_master
3203 ** table to parse the schema, or if this index is the PRIMARY KEY index
3204 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003205 **
drh58383402013-11-04 17:00:50 +00003206 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3207 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003208 ** has just been created, it contains no data and the index initialization
3209 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003210 */
drh58383402013-11-04 17:00:50 +00003211 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003212 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003213 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003214 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003215
danielk19774adee202004-05-08 08:23:19 +00003216 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003217 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003218
drhfdd6e852005-12-16 01:06:16 +00003219
drh063336a2004-11-05 20:58:39 +00003220 /* Create the rootpage for the index
3221 */
drhaee128d2005-02-14 20:48:18 +00003222 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003223 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003224
3225 /* Gather the complete text of the CREATE INDEX statement into
3226 ** the zStmt variable
3227 */
drhd3001712009-05-12 17:46:53 +00003228 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003229 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003230 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003231 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003232 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003233 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003234 }else{
3235 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003236 /* zStmt = sqlite3MPrintf(""); */
3237 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003238 }
drh063336a2004-11-05 20:58:39 +00003239
3240 /* Add an entry in sqlite_master for this index
3241 */
3242 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003243 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003244 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3245 pIndex->zName,
3246 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003247 iMem,
drh063336a2004-11-05 20:58:39 +00003248 zStmt
3249 );
drh633e6d52008-07-28 19:34:53 +00003250 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003251
danielk1977a21c6b62005-01-24 10:25:59 +00003252 /* Fill the index with data and reparse the schema. Code an OP_Expire
3253 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003254 */
danielk1977cbb18d22004-05-28 11:37:27 +00003255 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003256 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003257 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003258 sqlite3VdbeAddParseSchemaOp(v, iDb,
3259 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003260 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003261 }
drh75897232000-05-29 14:26:00 +00003262 }
3263
danielk1977d8123362004-06-12 09:25:12 +00003264 /* When adding an index to the list of indices for a table, make
3265 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003266 ** OE_Ignore. This is necessary for the correct constraint check
3267 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3268 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003269 */
drh234c39d2004-07-24 03:30:47 +00003270 if( db->init.busy || pTblName==0 ){
3271 if( onError!=OE_Replace || pTab->pIndex==0
3272 || pTab->pIndex->onError==OE_Replace){
3273 pIndex->pNext = pTab->pIndex;
3274 pTab->pIndex = pIndex;
3275 }else{
3276 Index *pOther = pTab->pIndex;
3277 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3278 pOther = pOther->pNext;
3279 }
3280 pIndex->pNext = pOther->pNext;
3281 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003282 }
dan1da40a32009-09-19 17:00:31 +00003283 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003284 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003285 }
danielk1977d8123362004-06-12 09:25:12 +00003286
drh75897232000-05-29 14:26:00 +00003287 /* Clean up before exiting */
3288exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003289 if( pIndex ) freeIndex(db, pIndex);
3290 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003291 sqlite3ExprListDelete(db, pList);
3292 sqlite3SrcListDelete(db, pTblName);
3293 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003294 return pRet;
drh75897232000-05-29 14:26:00 +00003295}
3296
3297/*
drh51147ba2005-07-23 22:59:55 +00003298** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003299** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003300**
peter.d.reid60ec9142014-09-06 16:39:46 +00003301** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003302** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3303** number of rows in the table that match any particular value of the
3304** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003305** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003306** of the index. And so forth. It must always be the case that
3307*
3308** aiRowEst[N]<=aiRowEst[N-1]
3309** aiRowEst[N]>=1
3310**
3311** Apart from that, we have little to go on besides intuition as to
3312** how aiRowEst[] should be initialized. The numbers generated here
3313** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003314*/
3315void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003316 /* 10, 9, 8, 7, 6 */
3317 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003318 LogEst *a = pIdx->aiRowLogEst;
3319 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003320 int i;
dancfc9df72014-04-25 15:01:01 +00003321
dan264d2b92014-04-29 19:01:57 +00003322 /* Set the first entry (number of rows in the index) to the estimated
3323 ** number of rows in the table. Or 10, if the estimated number of rows
3324 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003325 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003326 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3327
3328 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3329 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003330 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003331 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3332 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003333 }
dan264d2b92014-04-29 19:01:57 +00003334
3335 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003336 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003337}
3338
3339/*
drh74e24cd2002-01-09 03:19:59 +00003340** This routine will drop an existing named index. This routine
3341** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003342*/
drh4d91a702006-01-04 15:54:36 +00003343void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003344 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003345 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003346 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003347 int iDb;
drh75897232000-05-29 14:26:00 +00003348
drh8af73d42009-05-13 22:58:28 +00003349 assert( pParse->nErr==0 ); /* Never called with prior errors */
3350 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003351 goto exit_drop_index;
3352 }
drhd24cc422003-03-27 12:51:24 +00003353 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003354 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3355 goto exit_drop_index;
3356 }
danielk19774adee202004-05-08 08:23:19 +00003357 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003358 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003359 if( !ifExists ){
3360 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003361 }else{
3362 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003363 }
drha6ecd332004-06-10 00:29:09 +00003364 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003365 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003366 }
drh48dd1d82014-05-27 18:18:58 +00003367 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003368 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003369 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003370 goto exit_drop_index;
3371 }
danielk1977da184232006-01-05 11:34:32 +00003372 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003373#ifndef SQLITE_OMIT_AUTHORIZATION
3374 {
3375 int code = SQLITE_DROP_INDEX;
3376 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003377 const char *zDb = db->aDb[iDb].zName;
3378 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003379 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003380 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003381 }
danielk1977da184232006-01-05 11:34:32 +00003382 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003383 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003384 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003385 }
drhed6c8672003-01-12 18:02:16 +00003386 }
drhe5f9c642003-01-13 23:27:31 +00003387#endif
drh75897232000-05-29 14:26:00 +00003388
3389 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003390 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003391 if( v ){
drh77658e22007-12-04 16:54:52 +00003392 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003393 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003394 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003395 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003396 );
drha5ae4c32011-08-07 01:31:52 +00003397 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003398 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003399 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003400 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003401 }
3402
drhd24cc422003-03-27 12:51:24 +00003403exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003404 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003405}
3406
3407/*
dan9ace1122012-03-29 07:51:45 +00003408** pArray is a pointer to an array of objects. Each object in the
3409** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3410** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003411**
dan9ace1122012-03-29 07:51:45 +00003412** When this function is called, *pnEntry contains the current size of
3413** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3414** in total).
drh13449892005-09-07 21:22:45 +00003415**
dan9ace1122012-03-29 07:51:45 +00003416** If the realloc() is successful (i.e. if no OOM condition occurs), the
3417** space allocated for the new object is zeroed, *pnEntry updated to
3418** reflect the new size of the array and a pointer to the new allocation
3419** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003420**
dan9ace1122012-03-29 07:51:45 +00003421** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3422** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003423*/
drhcf643722007-03-27 13:36:37 +00003424void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003425 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003426 void *pArray, /* Array of objects. Might be reallocated */
3427 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003428 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003429 int *pIdx /* Write the index of a new slot here */
3430){
3431 char *z;
drh6c535152012-02-02 03:38:30 +00003432 int n = *pnEntry;
3433 if( (n & (n-1))==0 ){
3434 int sz = (n==0) ? 1 : 2*n;
3435 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003436 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003437 *pIdx = -1;
3438 return pArray;
drh13449892005-09-07 21:22:45 +00003439 }
drhcf643722007-03-27 13:36:37 +00003440 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003441 }
drhcf643722007-03-27 13:36:37 +00003442 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003443 memset(&z[n * szEntry], 0, szEntry);
3444 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003445 ++*pnEntry;
3446 return pArray;
drh13449892005-09-07 21:22:45 +00003447}
3448
3449/*
drh75897232000-05-29 14:26:00 +00003450** Append a new element to the given IdList. Create a new IdList if
3451** need be.
drhdaffd0e2001-04-11 14:28:42 +00003452**
3453** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003454*/
drh17435752007-08-16 04:30:38 +00003455IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003456 int i;
drh75897232000-05-29 14:26:00 +00003457 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003458 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003459 if( pList==0 ) return 0;
3460 }
drhcf643722007-03-27 13:36:37 +00003461 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003462 db,
drhcf643722007-03-27 13:36:37 +00003463 pList->a,
3464 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003465 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003466 &i
3467 );
drh13449892005-09-07 21:22:45 +00003468 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003469 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003470 return 0;
drh75897232000-05-29 14:26:00 +00003471 }
drh17435752007-08-16 04:30:38 +00003472 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003473 return pList;
3474}
3475
3476/*
drhfe05af82005-07-21 03:14:59 +00003477** Delete an IdList.
3478*/
drh633e6d52008-07-28 19:34:53 +00003479void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003480 int i;
3481 if( pList==0 ) return;
3482 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003483 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003484 }
drh633e6d52008-07-28 19:34:53 +00003485 sqlite3DbFree(db, pList->a);
3486 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003487}
3488
3489/*
3490** Return the index in pList of the identifier named zId. Return -1
3491** if not found.
3492*/
3493int sqlite3IdListIndex(IdList *pList, const char *zName){
3494 int i;
3495 if( pList==0 ) return -1;
3496 for(i=0; i<pList->nId; i++){
3497 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3498 }
3499 return -1;
3500}
3501
3502/*
drha78c22c2008-11-11 18:28:58 +00003503** Expand the space allocated for the given SrcList object by
3504** creating nExtra new slots beginning at iStart. iStart is zero based.
3505** New slots are zeroed.
3506**
3507** For example, suppose a SrcList initially contains two entries: A,B.
3508** To append 3 new entries onto the end, do this:
3509**
3510** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3511**
3512** After the call above it would contain: A, B, nil, nil, nil.
3513** If the iStart argument had been 1 instead of 2, then the result
3514** would have been: A, nil, nil, nil, B. To prepend the new slots,
3515** the iStart value would be 0. The result then would
3516** be: nil, nil, nil, A, B.
3517**
3518** If a memory allocation fails the SrcList is unchanged. The
3519** db->mallocFailed flag will be set to true.
3520*/
3521SrcList *sqlite3SrcListEnlarge(
3522 sqlite3 *db, /* Database connection to notify of OOM errors */
3523 SrcList *pSrc, /* The SrcList to be enlarged */
3524 int nExtra, /* Number of new slots to add to pSrc->a[] */
3525 int iStart /* Index in pSrc->a[] of first new slot */
3526){
3527 int i;
3528
3529 /* Sanity checking on calling parameters */
3530 assert( iStart>=0 );
3531 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003532 assert( pSrc!=0 );
3533 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003534
3535 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003536 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003537 SrcList *pNew;
3538 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003539 int nGot;
drha78c22c2008-11-11 18:28:58 +00003540 pNew = sqlite3DbRealloc(db, pSrc,
3541 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3542 if( pNew==0 ){
3543 assert( db->mallocFailed );
3544 return pSrc;
3545 }
3546 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003547 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003548 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003549 }
3550
3551 /* Move existing slots that come after the newly inserted slots
3552 ** out of the way */
3553 for(i=pSrc->nSrc-1; i>=iStart; i--){
3554 pSrc->a[i+nExtra] = pSrc->a[i];
3555 }
drh6d1626e2014-03-05 15:52:43 +00003556 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003557
3558 /* Zero the newly allocated slots */
3559 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3560 for(i=iStart; i<iStart+nExtra; i++){
3561 pSrc->a[i].iCursor = -1;
3562 }
3563
3564 /* Return a pointer to the enlarged SrcList */
3565 return pSrc;
3566}
3567
3568
3569/*
drhad3cab52002-05-24 02:04:32 +00003570** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003571** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003572**
drha78c22c2008-11-11 18:28:58 +00003573** A SrcList is returned, or NULL if there is an OOM error. The returned
3574** SrcList might be the same as the SrcList that was input or it might be
3575** a new one. If an OOM error does occurs, then the prior value of pList
3576** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003577**
3578** If pDatabase is not null, it means that the table has an optional
3579** database name prefix. Like this: "database.table". The pDatabase
3580** points to the table name and the pTable points to the database name.
3581** The SrcList.a[].zName field is filled with the table name which might
3582** come from pTable (if pDatabase is NULL) or from pDatabase.
3583** SrcList.a[].zDatabase is filled with the database name from pTable,
3584** or with NULL if no database is specified.
3585**
3586** In other words, if call like this:
3587**
drh17435752007-08-16 04:30:38 +00003588** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003589**
3590** Then B is a table name and the database name is unspecified. If called
3591** like this:
3592**
drh17435752007-08-16 04:30:38 +00003593** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003594**
drhd3001712009-05-12 17:46:53 +00003595** Then C is the table name and B is the database name. If C is defined
3596** then so is B. In other words, we never have a case where:
3597**
3598** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003599**
3600** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3601** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003602*/
drh17435752007-08-16 04:30:38 +00003603SrcList *sqlite3SrcListAppend(
3604 sqlite3 *db, /* Connection to notify of malloc failures */
3605 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3606 Token *pTable, /* Table to append */
3607 Token *pDatabase /* Database of the table */
3608){
drha99db3b2004-06-19 14:49:12 +00003609 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003610 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003611 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003612 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003613 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003614 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003615 }
drha78c22c2008-11-11 18:28:58 +00003616 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3617 if( db->mallocFailed ){
3618 sqlite3SrcListDelete(db, pList);
3619 return 0;
drhad3cab52002-05-24 02:04:32 +00003620 }
drha78c22c2008-11-11 18:28:58 +00003621 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003622 if( pDatabase && pDatabase->z==0 ){
3623 pDatabase = 0;
3624 }
drhd3001712009-05-12 17:46:53 +00003625 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003626 Token *pTemp = pDatabase;
3627 pDatabase = pTable;
3628 pTable = pTemp;
3629 }
drh17435752007-08-16 04:30:38 +00003630 pItem->zName = sqlite3NameFromToken(db, pTable);
3631 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003632 return pList;
3633}
3634
3635/*
drhdfe88ec2008-11-03 20:55:06 +00003636** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003637*/
danielk19774adee202004-05-08 08:23:19 +00003638void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003639 int i;
drh9b3187e2005-01-18 14:45:47 +00003640 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003641 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003642 if( pList ){
3643 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3644 if( pItem->iCursor>=0 ) break;
3645 pItem->iCursor = pParse->nTab++;
3646 if( pItem->pSelect ){
3647 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3648 }
drh63eb5f22003-04-29 16:20:44 +00003649 }
3650 }
3651}
3652
3653/*
drhad3cab52002-05-24 02:04:32 +00003654** Delete an entire SrcList including all its substructure.
3655*/
drh633e6d52008-07-28 19:34:53 +00003656void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003657 int i;
drhbe5c89a2004-07-26 00:31:09 +00003658 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003659 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003660 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003661 sqlite3DbFree(db, pItem->zDatabase);
3662 sqlite3DbFree(db, pItem->zName);
3663 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003664 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003665 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003666 sqlite3SelectDelete(db, pItem->pSelect);
3667 sqlite3ExprDelete(db, pItem->pOn);
3668 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003669 }
drh633e6d52008-07-28 19:34:53 +00003670 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003671}
3672
drh982cef72000-05-30 16:27:03 +00003673/*
drh61dfc312006-12-16 16:25:15 +00003674** This routine is called by the parser to add a new term to the
3675** end of a growing FROM clause. The "p" parameter is the part of
3676** the FROM clause that has already been constructed. "p" is NULL
3677** if this is the first term of the FROM clause. pTable and pDatabase
3678** are the name of the table and database named in the FROM clause term.
3679** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003680** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003681** alias token. If the term is a subquery, then pSubquery is the
3682** SELECT statement that the subquery encodes. The pTable and
3683** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3684** parameters are the content of the ON and USING clauses.
3685**
3686** Return a new SrcList which encodes is the FROM with the new
3687** term added.
3688*/
3689SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003690 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003691 SrcList *p, /* The left part of the FROM clause already seen */
3692 Token *pTable, /* Name of the table to add to the FROM clause */
3693 Token *pDatabase, /* Name of the database containing pTable */
3694 Token *pAlias, /* The right-hand side of the AS subexpression */
3695 Select *pSubquery, /* A subquery used in place of a table name */
3696 Expr *pOn, /* The ON clause of a join */
3697 IdList *pUsing /* The USING clause of a join */
3698){
3699 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003700 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003701 if( !p && (pOn || pUsing) ){
3702 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3703 (pOn ? "ON" : "USING")
3704 );
3705 goto append_from_error;
3706 }
drh17435752007-08-16 04:30:38 +00003707 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003708 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003709 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003710 }
3711 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003712 assert( pAlias!=0 );
3713 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003714 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003715 }
3716 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003717 pItem->pOn = pOn;
3718 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003719 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003720
3721 append_from_error:
3722 assert( p==0 );
3723 sqlite3ExprDelete(db, pOn);
3724 sqlite3IdListDelete(db, pUsing);
3725 sqlite3SelectDelete(db, pSubquery);
3726 return 0;
drh61dfc312006-12-16 16:25:15 +00003727}
3728
3729/*
danielk1977b1c685b2008-10-06 16:18:39 +00003730** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3731** element of the source-list passed as the second argument.
3732*/
3733void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003734 assert( pIndexedBy!=0 );
3735 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003736 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3737 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3738 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3739 /* A "NOT INDEXED" clause was supplied. See parse.y
3740 ** construct "indexed_opt" for details. */
3741 pItem->notIndexed = 1;
3742 }else{
3743 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3744 }
3745 }
3746}
3747
3748/*
drh61dfc312006-12-16 16:25:15 +00003749** When building up a FROM clause in the parser, the join operator
3750** is initially attached to the left operand. But the code generator
3751** expects the join operator to be on the right operand. This routine
3752** Shifts all join operators from left to right for an entire FROM
3753** clause.
3754**
3755** Example: Suppose the join is like this:
3756**
3757** A natural cross join B
3758**
3759** The operator is "natural cross join". The A and B operands are stored
3760** in p->a[0] and p->a[1], respectively. The parser initially stores the
3761** operator with A. This routine shifts that operator over to B.
3762*/
3763void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003764 if( p ){
drh61dfc312006-12-16 16:25:15 +00003765 int i;
drhd017ab92011-08-23 00:01:58 +00003766 assert( p->a || p->nSrc==0 );
drh61dfc312006-12-16 16:25:15 +00003767 for(i=p->nSrc-1; i>0; i--){
3768 p->a[i].jointype = p->a[i-1].jointype;
3769 }
3770 p->a[0].jointype = 0;
3771 }
3772}
3773
3774/*
drhc4a3c772001-04-04 11:48:57 +00003775** Begin a transaction
3776*/
drh684917c2004-10-05 02:41:42 +00003777void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003778 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003779 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003780 int i;
drh5e00f6c2001-09-13 13:46:56 +00003781
drhd3001712009-05-12 17:46:53 +00003782 assert( pParse!=0 );
3783 db = pParse->db;
3784 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003785/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003786 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3787 return;
3788 }
danielk19771d850a72004-05-31 08:26:49 +00003789 v = sqlite3GetVdbe(pParse);
3790 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003791 if( type!=TK_DEFERRED ){
3792 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003793 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003794 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003795 }
3796 }
drh66a51672008-01-03 00:01:23 +00003797 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003798}
3799
3800/*
3801** Commit a transaction
3802*/
danielk19774adee202004-05-08 08:23:19 +00003803void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003804 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003805
drhd3001712009-05-12 17:46:53 +00003806 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003807 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003808 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3809 return;
3810 }
danielk19771d850a72004-05-31 08:26:49 +00003811 v = sqlite3GetVdbe(pParse);
3812 if( v ){
drh66a51672008-01-03 00:01:23 +00003813 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003814 }
drhc4a3c772001-04-04 11:48:57 +00003815}
3816
3817/*
3818** Rollback a transaction
3819*/
danielk19774adee202004-05-08 08:23:19 +00003820void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003821 Vdbe *v;
3822
drhd3001712009-05-12 17:46:53 +00003823 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003824 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003825 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3826 return;
3827 }
danielk19774adee202004-05-08 08:23:19 +00003828 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003829 if( v ){
drh66a51672008-01-03 00:01:23 +00003830 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003831 }
drhc4a3c772001-04-04 11:48:57 +00003832}
drhf57b14a2001-09-14 18:54:08 +00003833
3834/*
danielk1977fd7f0452008-12-17 17:30:26 +00003835** This function is called by the parser when it parses a command to create,
3836** release or rollback an SQL savepoint.
3837*/
3838void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003839 char *zName = sqlite3NameFromToken(pParse->db, pName);
3840 if( zName ){
3841 Vdbe *v = sqlite3GetVdbe(pParse);
3842#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003843 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003844 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3845#endif
3846 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3847 sqlite3DbFree(pParse->db, zName);
3848 return;
3849 }
3850 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003851 }
3852}
3853
3854/*
drhdc3ff9c2004-08-18 02:10:15 +00003855** Make sure the TEMP database is open and available for use. Return
3856** the number of errors. Leave any error messages in the pParse structure.
3857*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003858int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003859 sqlite3 *db = pParse->db;
3860 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003861 int rc;
drh10a76c92010-01-26 01:25:26 +00003862 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003863 static const int flags =
3864 SQLITE_OPEN_READWRITE |
3865 SQLITE_OPEN_CREATE |
3866 SQLITE_OPEN_EXCLUSIVE |
3867 SQLITE_OPEN_DELETEONCLOSE |
3868 SQLITE_OPEN_TEMP_DB;
3869
dan3a6d8ae2011-04-23 15:54:54 +00003870 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003871 if( rc!=SQLITE_OK ){
3872 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3873 "file for storing temporary tables");
3874 pParse->rc = rc;
3875 return 1;
3876 }
drh10a76c92010-01-26 01:25:26 +00003877 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003878 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003879 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3880 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003881 return 1;
drh10a76c92010-01-26 01:25:26 +00003882 }
drhdc3ff9c2004-08-18 02:10:15 +00003883 }
3884 return 0;
3885}
3886
3887/*
drhaceb31b2014-02-08 01:40:27 +00003888** Record the fact that the schema cookie will need to be verified
3889** for database iDb. The code to actually verify the schema cookie
3890** will occur at the end of the top-level VDBE and will be generated
3891** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003892*/
danielk19774adee202004-05-08 08:23:19 +00003893void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003894 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003895 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003896
drhaceb31b2014-02-08 01:40:27 +00003897 assert( iDb>=0 && iDb<db->nDb );
3898 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3899 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3900 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003901 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3902 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003903 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3904 if( !OMIT_TEMPDB && iDb==1 ){
3905 sqlite3OpenTempDatabase(pToplevel);
3906 }
drh001bbcb2003-03-19 03:14:00 +00003907 }
drh001bbcb2003-03-19 03:14:00 +00003908}
3909
3910/*
dan57966752011-04-09 17:32:58 +00003911** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3912** attached database. Otherwise, invoke it for the database named zDb only.
3913*/
3914void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3915 sqlite3 *db = pParse->db;
3916 int i;
3917 for(i=0; i<db->nDb; i++){
3918 Db *pDb = &db->aDb[i];
3919 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3920 sqlite3CodeVerifySchema(pParse, i);
3921 }
3922 }
3923}
3924
3925/*
drh1c928532002-01-31 15:54:21 +00003926** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003927** might change the database.
3928**
3929** This routine starts a new transaction if we are not already within
3930** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003931** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003932** be set for operations that might fail (due to a constraint) part of
3933** the way through and which will need to undo some writes without having to
3934** rollback the whole transaction. For operations where all constraints
3935** can be checked before any changes are made to the database, it is never
3936** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003937*/
drh7f0f12e2004-05-21 13:39:50 +00003938void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003939 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003940 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003941 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003942 pToplevel->isMultiWrite |= setStatement;
3943}
3944
drhff738bc2009-09-24 00:09:58 +00003945/*
3946** Indicate that the statement currently under construction might write
3947** more than one entry (example: deleting one row then inserting another,
3948** inserting multiple rows in a table, or inserting a row and index entries.)
3949** If an abort occurs after some of these writes have completed, then it will
3950** be necessary to undo the completed writes.
3951*/
3952void sqlite3MultiWrite(Parse *pParse){
3953 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3954 pToplevel->isMultiWrite = 1;
3955}
3956
dane0af83a2009-09-08 19:15:01 +00003957/*
drhff738bc2009-09-24 00:09:58 +00003958** The code generator calls this routine if is discovers that it is
3959** possible to abort a statement prior to completion. In order to
3960** perform this abort without corrupting the database, we need to make
3961** sure that the statement is protected by a statement transaction.
3962**
3963** Technically, we only need to set the mayAbort flag if the
3964** isMultiWrite flag was previously set. There is a time dependency
3965** such that the abort must occur after the multiwrite. This makes
3966** some statements involving the REPLACE conflict resolution algorithm
3967** go a little faster. But taking advantage of this time dependency
3968** makes it more difficult to prove that the code is correct (in
3969** particular, it prevents us from writing an effective
3970** implementation of sqlite3AssertMayAbort()) and so we have chosen
3971** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00003972*/
3973void sqlite3MayAbort(Parse *pParse){
3974 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3975 pToplevel->mayAbort = 1;
3976}
3977
3978/*
3979** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
3980** error. The onError parameter determines which (if any) of the statement
3981** and/or current transaction is rolled back.
3982*/
drhd91c1a12013-02-09 13:58:25 +00003983void sqlite3HaltConstraint(
3984 Parse *pParse, /* Parsing context */
3985 int errCode, /* extended error code */
3986 int onError, /* Constraint type */
3987 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00003988 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
3989 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00003990){
dane0af83a2009-09-08 19:15:01 +00003991 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00003992 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00003993 if( onError==OE_Abort ){
3994 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00003995 }
drhd91c1a12013-02-09 13:58:25 +00003996 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00003997 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
3998}
3999
4000/*
4001** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4002*/
4003void sqlite3UniqueConstraint(
4004 Parse *pParse, /* Parsing context */
4005 int onError, /* Constraint type */
4006 Index *pIdx /* The index that triggers the constraint */
4007){
4008 char *zErr;
4009 int j;
4010 StrAccum errMsg;
4011 Table *pTab = pIdx->pTable;
4012
4013 sqlite3StrAccumInit(&errMsg, 0, 0, 200);
4014 errMsg.db = pParse->db;
4015 for(j=0; j<pIdx->nKeyCol; j++){
4016 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4017 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004018 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004019 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004020 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004021 }
4022 zErr = sqlite3StrAccumFinish(&errMsg);
4023 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004024 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4025 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004026 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004027}
4028
4029
4030/*
4031** Code an OP_Halt due to non-unique rowid.
4032*/
4033void sqlite3RowidConstraint(
4034 Parse *pParse, /* Parsing context */
4035 int onError, /* Conflict resolution algorithm */
4036 Table *pTab /* The table with the non-unique rowid */
4037){
4038 char *zMsg;
4039 int rc;
4040 if( pTab->iPKey>=0 ){
4041 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4042 pTab->aCol[pTab->iPKey].zName);
4043 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4044 }else{
4045 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4046 rc = SQLITE_CONSTRAINT_ROWID;
4047 }
4048 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4049 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004050}
4051
drh4343fea2004-11-05 23:46:15 +00004052/*
4053** Check to see if pIndex uses the collating sequence pColl. Return
4054** true if it does and false if it does not.
4055*/
4056#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004057static int collationMatch(const char *zColl, Index *pIndex){
4058 int i;
drh04491712009-05-13 17:21:13 +00004059 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004060 for(i=0; i<pIndex->nColumn; i++){
4061 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004062 assert( z!=0 || pIndex->aiColumn[i]<0 );
4063 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004064 return 1;
4065 }
drh4343fea2004-11-05 23:46:15 +00004066 }
4067 return 0;
4068}
4069#endif
4070
4071/*
4072** Recompute all indices of pTab that use the collating sequence pColl.
4073** If pColl==0 then recompute all indices of pTab.
4074*/
4075#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004076static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004077 Index *pIndex; /* An index associated with pTab */
4078
4079 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004080 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004081 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4082 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004083 sqlite3RefillIndex(pParse, pIndex, -1);
4084 }
4085 }
4086}
4087#endif
4088
4089/*
4090** Recompute all indices of all tables in all databases where the
4091** indices use the collating sequence pColl. If pColl==0 then recompute
4092** all indices everywhere.
4093*/
4094#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004095static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004096 Db *pDb; /* A single database */
4097 int iDb; /* The database index number */
4098 sqlite3 *db = pParse->db; /* The database connection */
4099 HashElem *k; /* For looping over tables in pDb */
4100 Table *pTab; /* A table in the database */
4101
drh21206082011-04-04 18:22:02 +00004102 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004103 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004104 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004105 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004106 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004107 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004108 }
4109 }
4110}
4111#endif
4112
4113/*
drheee46cf2004-11-06 00:02:48 +00004114** Generate code for the REINDEX command.
4115**
4116** REINDEX -- 1
4117** REINDEX <collation> -- 2
4118** REINDEX ?<database>.?<tablename> -- 3
4119** REINDEX ?<database>.?<indexname> -- 4
4120**
4121** Form 1 causes all indices in all attached databases to be rebuilt.
4122** Form 2 rebuilds all indices in all databases that use the named
4123** collating function. Forms 3 and 4 rebuild the named index or all
4124** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004125*/
4126#ifndef SQLITE_OMIT_REINDEX
4127void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4128 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4129 char *z; /* Name of a table or index */
4130 const char *zDb; /* Name of the database */
4131 Table *pTab; /* A table in the database */
4132 Index *pIndex; /* An index associated with pTab */
4133 int iDb; /* The database index number */
4134 sqlite3 *db = pParse->db; /* The database connection */
4135 Token *pObjName; /* Name of the table or index to be reindexed */
4136
danielk197733a5edc2005-01-27 00:22:02 +00004137 /* Read the database schema. If an error occurs, leave an error message
4138 ** and code in pParse and return NULL. */
4139 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004140 return;
danielk197733a5edc2005-01-27 00:22:02 +00004141 }
4142
drh8af73d42009-05-13 22:58:28 +00004143 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004144 reindexDatabases(pParse, 0);
4145 return;
drhd3001712009-05-12 17:46:53 +00004146 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004147 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004148 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004149 zColl = sqlite3NameFromToken(pParse->db, pName1);
4150 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004151 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004152 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004153 reindexDatabases(pParse, zColl);
4154 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004155 return;
4156 }
drh633e6d52008-07-28 19:34:53 +00004157 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004158 }
4159 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4160 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004161 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004162 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004163 zDb = db->aDb[iDb].zName;
4164 pTab = sqlite3FindTable(db, z, zDb);
4165 if( pTab ){
4166 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004167 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004168 return;
4169 }
4170 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004171 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004172 if( pIndex ){
4173 sqlite3BeginWriteOperation(pParse, 0, iDb);
4174 sqlite3RefillIndex(pParse, pIndex, -1);
4175 return;
4176 }
4177 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4178}
4179#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004180
4181/*
drh2ec2fb22013-11-06 19:59:23 +00004182** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004183**
drh2ec2fb22013-11-06 19:59:23 +00004184** The KeyInfo structure for an index is cached in the Index object.
4185** So there might be multiple references to the returned pointer. The
4186** caller should not try to modify the KeyInfo object.
4187**
4188** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4189** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004190*/
drh2ec2fb22013-11-06 19:59:23 +00004191KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh2ec2fb22013-11-06 19:59:23 +00004192 if( pParse->nErr ) return 0;
drh41e13e12013-11-07 14:09:39 +00004193#ifndef SQLITE_OMIT_SHARED_CACHE
4194 if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
4195 sqlite3KeyInfoUnref(pIdx->pKeyInfo);
4196 pIdx->pKeyInfo = 0;
4197 }
4198#endif
drh2ec2fb22013-11-06 19:59:23 +00004199 if( pIdx->pKeyInfo==0 ){
drh41e13e12013-11-07 14:09:39 +00004200 int i;
4201 int nCol = pIdx->nColumn;
4202 int nKey = pIdx->nKeyCol;
4203 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004204 if( pIdx->uniqNotNull ){
4205 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4206 }else{
4207 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
4208 }
4209 if( pKey ){
4210 assert( sqlite3KeyInfoIsWriteable(pKey) );
4211 for(i=0; i<nCol; i++){
4212 char *zColl = pIdx->azColl[i];
drhb8a9bb42013-12-06 22:45:31 +00004213 assert( zColl!=0 );
4214 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4215 sqlite3LocateCollSeq(pParse, zColl);
drh2ec2fb22013-11-06 19:59:23 +00004216 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
4217 }
4218 if( pParse->nErr ){
4219 sqlite3KeyInfoUnref(pKey);
4220 }else{
4221 pIdx->pKeyInfo = pKey;
4222 }
danielk1977b3bf5562006-01-10 17:58:23 +00004223 }
danielk1977b3bf5562006-01-10 17:58:23 +00004224 }
drh2ec2fb22013-11-06 19:59:23 +00004225 return sqlite3KeyInfoRef(pIdx->pKeyInfo);
danielk1977b3bf5562006-01-10 17:58:23 +00004226}
drh8b471862014-01-11 13:22:17 +00004227
4228#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004229/*
4230** This routine is invoked once per CTE by the parser while parsing a
4231** WITH clause.
drh8b471862014-01-11 13:22:17 +00004232*/
dan7d562db2014-01-11 19:19:36 +00004233With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004234 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004235 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004236 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004237 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004238 Select *pQuery /* Query used to initialize the table */
4239){
dan4e9119d2014-01-13 15:12:23 +00004240 sqlite3 *db = pParse->db;
4241 With *pNew;
4242 char *zName;
4243
4244 /* Check that the CTE name is unique within this WITH clause. If
4245 ** not, store an error in the Parse structure. */
4246 zName = sqlite3NameFromToken(pParse->db, pName);
4247 if( zName && pWith ){
4248 int i;
4249 for(i=0; i<pWith->nCte; i++){
4250 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004251 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004252 }
4253 }
4254 }
4255
4256 if( pWith ){
4257 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4258 pNew = sqlite3DbRealloc(db, pWith, nByte);
4259 }else{
4260 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4261 }
4262 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004263 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004264
4265 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004266 sqlite3ExprListDelete(db, pArglist);
4267 sqlite3SelectDelete(db, pQuery);
4268 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004269 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004270 }else{
4271 pNew->a[pNew->nCte].pSelect = pQuery;
4272 pNew->a[pNew->nCte].pCols = pArglist;
4273 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004274 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004275 pNew->nCte++;
4276 }
4277
4278 return pNew;
drh8b471862014-01-11 13:22:17 +00004279}
4280
dan7d562db2014-01-11 19:19:36 +00004281/*
4282** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004283*/
dan7d562db2014-01-11 19:19:36 +00004284void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004285 if( pWith ){
4286 int i;
4287 for(i=0; i<pWith->nCte; i++){
4288 struct Cte *pCte = &pWith->a[i];
4289 sqlite3ExprListDelete(db, pCte->pCols);
4290 sqlite3SelectDelete(db, pCte->pSelect);
4291 sqlite3DbFree(db, pCte->zName);
4292 }
4293 sqlite3DbFree(db, pWith);
4294 }
drh8b471862014-01-11 13:22:17 +00004295}
4296#endif /* !defined(SQLITE_OMIT_CTE) */