blob: 44d75e95571aac9f306a659c64fb285c85c01477 [file] [log] [blame]
drh75897232000-05-29 14:26:00 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drh75897232000-05-29 14:26:00 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drh75897232000-05-29 14:26:00 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drh75897232000-05-29 14:26:00 +000010**
11*************************************************************************
drhb19a2bc2001-09-16 00:13:26 +000012** This file contains C code routines that are called by the SQLite parser
13** when syntax rules are reduced. The routines in this file handle the
14** following kinds of SQL syntax:
drh75897232000-05-29 14:26:00 +000015**
drhbed86902000-06-02 13:27:59 +000016** CREATE TABLE
17** DROP TABLE
18** CREATE INDEX
19** DROP INDEX
drh832508b2002-03-02 17:04:07 +000020** creating ID lists
drhb19a2bc2001-09-16 00:13:26 +000021** BEGIN TRANSACTION
22** COMMIT
23** ROLLBACK
drh75897232000-05-29 14:26:00 +000024*/
25#include "sqliteInt.h"
26
27/*
drhe0bc4042002-06-25 01:09:11 +000028** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000029** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000030*/
danielk19774adee202004-05-08 08:23:19 +000031void sqlite3BeginParse(Parse *pParse, int explainFlag){
drh1bd10f82008-12-10 21:19:56 +000032 pParse->explain = (u8)explainFlag;
drh7c972de2003-09-06 22:18:07 +000033 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000034}
35
danielk1977c00da102006-01-07 13:21:04 +000036#ifndef SQLITE_OMIT_SHARED_CACHE
37/*
38** The TableLock structure is only used by the sqlite3TableLock() and
39** codeTableLocks() functions.
40*/
41struct TableLock {
drhd698bc12006-03-23 23:33:26 +000042 int iDb; /* The database containing the table to be locked */
43 int iTab; /* The root page of the table to be locked */
44 u8 isWriteLock; /* True for write lock. False for a read lock */
45 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000046};
47
48/*
drhd698bc12006-03-23 23:33:26 +000049** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000050**
drhd698bc12006-03-23 23:33:26 +000051** The table to be locked has root page iTab and is found in database iDb.
52** A read or a write lock can be taken depending on isWritelock.
53**
54** This routine just records the fact that the lock is desired. The
55** code to make the lock occur is generated by a later call to
56** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000057*/
58void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000059 Parse *pParse, /* Parsing context */
60 int iDb, /* Index of the database containing the table to lock */
61 int iTab, /* Root page number of the table to be locked */
62 u8 isWriteLock, /* True for a write lock */
63 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000064){
dan65a7cd12009-09-01 12:16:01 +000065 Parse *pToplevel = sqlite3ParseToplevel(pParse);
danielk1977c00da102006-01-07 13:21:04 +000066 int i;
67 int nBytes;
68 TableLock *p;
drh8af73d42009-05-13 22:58:28 +000069 assert( iDb>=0 );
dan165921a2009-08-28 18:53:45 +000070
dan65a7cd12009-09-01 12:16:01 +000071 for(i=0; i<pToplevel->nTableLock; i++){
72 p = &pToplevel->aTableLock[i];
danielk1977c00da102006-01-07 13:21:04 +000073 if( p->iDb==iDb && p->iTab==iTab ){
74 p->isWriteLock = (p->isWriteLock || isWriteLock);
75 return;
76 }
77 }
78
dan65a7cd12009-09-01 12:16:01 +000079 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
80 pToplevel->aTableLock =
81 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
82 if( pToplevel->aTableLock ){
83 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
danielk1977c00da102006-01-07 13:21:04 +000084 p->iDb = iDb;
85 p->iTab = iTab;
86 p->isWriteLock = isWriteLock;
87 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000088 }else{
dan65a7cd12009-09-01 12:16:01 +000089 pToplevel->nTableLock = 0;
90 pToplevel->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000091 }
92}
93
94/*
95** Code an OP_TableLock instruction for each table locked by the
96** statement (configured by calls to sqlite3TableLock()).
97*/
98static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000101
drh04491712009-05-13 17:21:13 +0000102 pVdbe = sqlite3GetVdbe(pParse);
103 assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
danielk1977c00da102006-01-07 13:21:04 +0000104
105 for(i=0; i<pParse->nTableLock; i++){
106 TableLock *p = &pParse->aTableLock[i];
107 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000108 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
109 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000110 }
111}
112#else
113 #define codeTableLocks(x)
114#endif
115
drhe0bc4042002-06-25 01:09:11 +0000116/*
drha7ab6d82014-07-21 15:44:39 +0000117** Return TRUE if the given yDbMask object is empty - if it contains no
118** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
119** macros when SQLITE_MAX_ATTACHED is greater than 30.
120*/
121#if SQLITE_MAX_ATTACHED>30
122int sqlite3DbMaskAllZero(yDbMask m){
123 int i;
124 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
125 return 1;
126}
127#endif
128
129/*
drh75897232000-05-29 14:26:00 +0000130** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000131** parsed and a VDBE program to execute that statement has been
132** prepared. This routine puts the finishing touches on the
133** VDBE program and resets the pParse structure for the next
134** parse.
drh75897232000-05-29 14:26:00 +0000135**
136** Note that if an error occurred, it might be the case that
137** no VDBE code was generated.
138*/
drh80242052004-06-09 00:48:12 +0000139void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000140 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000141 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000142
danf78baaf2012-12-06 19:37:22 +0000143 assert( pParse->pToplevel==0 );
drh17435752007-08-16 04:30:38 +0000144 db = pParse->db;
drh205f48e2004-11-05 00:43:11 +0000145 if( pParse->nested ) return;
drhd99d2832015-04-17 15:58:33 +0000146 if( db->mallocFailed || pParse->nErr ){
147 if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
148 return;
149 }
danielk197748d0d862005-02-01 03:09:52 +0000150
drh80242052004-06-09 00:48:12 +0000151 /* Begin by generating some termination code at the end of the
152 ** vdbe program
153 */
drh80242052004-06-09 00:48:12 +0000154 v = sqlite3GetVdbe(pParse);
danf3677212009-09-10 16:14:50 +0000155 assert( !pParse->isMultiWrite
156 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
drh80242052004-06-09 00:48:12 +0000157 if( v ){
drh61019c72014-01-04 16:49:02 +0000158 while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
drh66a51672008-01-03 00:01:23 +0000159 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000160
drhb2445d52014-09-11 14:01:41 +0000161#if SQLITE_USER_AUTHENTICATION
162 if( pParse->nTableLock>0 && db->init.busy==0 ){
drh7883ecf2014-09-11 16:19:31 +0000163 sqlite3UserAuthInit(db);
drhb2445d52014-09-11 14:01:41 +0000164 if( db->auth.authLevel<UAUTH_User ){
drh7883ecf2014-09-11 16:19:31 +0000165 pParse->rc = SQLITE_AUTH_USER;
166 sqlite3ErrorMsg(pParse, "user not authenticated");
167 return;
drhb2445d52014-09-11 14:01:41 +0000168 }
169 }
170#endif
171
drh0e3d7472004-06-19 17:33:07 +0000172 /* The cookie mask contains one bit for each database file open.
173 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
174 ** set for each database that is used. Generate code to start a
175 ** transaction on each used database and to verify the schema cookie
176 ** on each used database.
177 */
drha7ab6d82014-07-21 15:44:39 +0000178 if( db->mallocFailed==0
179 && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
180 ){
drhaceb31b2014-02-08 01:40:27 +0000181 int iDb, i;
182 assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
183 sqlite3VdbeJumpHere(v, 0);
drha7ab6d82014-07-21 15:44:39 +0000184 for(iDb=0; iDb<db->nDb; iDb++){
185 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000186 sqlite3VdbeUsesBtree(v, iDb);
drhb22f7c82014-02-06 23:56:27 +0000187 sqlite3VdbeAddOp4Int(v,
188 OP_Transaction, /* Opcode */
189 iDb, /* P1 */
drha7ab6d82014-07-21 15:44:39 +0000190 DbMaskTest(pParse->writeMask,iDb), /* P2 */
drhb22f7c82014-02-06 23:56:27 +0000191 pParse->cookieValue[iDb], /* P3 */
192 db->aDb[iDb].pSchema->iGeneration /* P4 */
193 );
194 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
drh80242052004-06-09 00:48:12 +0000195 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000196#ifndef SQLITE_OMIT_VIRTUALTABLE
drhf30a9692013-11-15 01:10:18 +0000197 for(i=0; i<pParse->nVtabLock; i++){
198 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
199 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
danielk1977f9e7dda2006-06-16 16:08:53 +0000200 }
drhf30a9692013-11-15 01:10:18 +0000201 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000202#endif
danielk1977c00da102006-01-07 13:21:04 +0000203
204 /* Once all the cookies have been verified and transactions opened,
205 ** obtain the required table-locks. This is a no-op unless the
206 ** shared-cache feature is enabled.
207 */
208 codeTableLocks(pParse);
drh0b9f50d2009-06-23 20:28:53 +0000209
210 /* Initialize any AUTOINCREMENT data structures required.
211 */
212 sqlite3AutoincrementBegin(pParse);
213
drhf30a9692013-11-15 01:10:18 +0000214 /* Code constant expressions that where factored out of inner loops */
drhf30a9692013-11-15 01:10:18 +0000215 if( pParse->pConstExpr ){
216 ExprList *pEL = pParse->pConstExpr;
drhaceb31b2014-02-08 01:40:27 +0000217 pParse->okConstFactor = 0;
drhf30a9692013-11-15 01:10:18 +0000218 for(i=0; i<pEL->nExpr; i++){
drhc2acc4e2013-11-15 18:15:19 +0000219 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
drhf30a9692013-11-15 01:10:18 +0000220 }
221 }
222
drh0b9f50d2009-06-23 20:28:53 +0000223 /* Finally, jump back to the beginning of the executable code. */
drhaceb31b2014-02-08 01:40:27 +0000224 sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
drh80242052004-06-09 00:48:12 +0000225 }
drh71c697e2004-08-08 23:39:19 +0000226 }
227
drh3f7d4e42004-07-24 14:35:58 +0000228
drh80242052004-06-09 00:48:12 +0000229 /* Get the VDBE program ready for execution
230 */
drh126a6e22015-04-15 04:10:50 +0000231 if( v && pParse->nErr==0 && !db->mallocFailed ){
drhceea3322009-04-23 13:22:42 +0000232 assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
drh3492dd72009-09-14 23:47:24 +0000233 /* A minimum of one cursor is required if autoincrement is used
234 * See ticket [a696379c1f08866] */
235 if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
drh124c0b42011-06-01 18:15:55 +0000236 sqlite3VdbeMakeReady(v, pParse);
danielk1977441daf62005-02-01 03:46:43 +0000237 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000238 pParse->colNamesSet = 0;
drhe294da02010-02-25 23:44:15 +0000239 }else{
drh483750b2003-01-29 18:46:51 +0000240 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000241 }
drha226d052002-09-25 19:04:07 +0000242 pParse->nTab = 0;
243 pParse->nMem = 0;
244 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000245 pParse->nVar = 0;
drha7ab6d82014-07-21 15:44:39 +0000246 DbMaskZero(pParse->cookieMask);
drh75897232000-05-29 14:26:00 +0000247}
248
249/*
drh205f48e2004-11-05 00:43:11 +0000250** Run the parser and code generator recursively in order to generate
251** code for the SQL statement given onto the end of the pParse context
252** currently under construction. When the parser is run recursively
253** this way, the final OP_Halt is not appended and other initialization
254** and finalization steps are omitted because those are handling by the
255** outermost parser.
256**
257** Not everything is nestable. This facility is designed to permit
258** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000259** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000260*/
261void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
262 va_list ap;
263 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000264 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000265 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000266# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
267 char saveBuf[SAVE_SZ];
268
drh205f48e2004-11-05 00:43:11 +0000269 if( pParse->nErr ) return;
270 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
271 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000272 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000273 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000274 if( zSql==0 ){
275 return; /* A malloc must have failed */
276 }
drh205f48e2004-11-05 00:43:11 +0000277 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000278 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
279 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000280 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000281 sqlite3DbFree(db, zErrMsg);
282 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000283 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000284 pParse->nested--;
285}
286
drhd4530972014-09-09 14:47:53 +0000287#if SQLITE_USER_AUTHENTICATION
288/*
289** Return TRUE if zTable is the name of the system table that stores the
290** list of users and their access credentials.
291*/
292int sqlite3UserAuthTable(const char *zTable){
293 return sqlite3_stricmp(zTable, "sqlite_user")==0;
294}
295#endif
296
drh205f48e2004-11-05 00:43:11 +0000297/*
danielk19778a414492004-06-29 08:59:35 +0000298** Locate the in-memory structure that describes a particular database
299** table given the name of that table and (optionally) the name of the
300** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000301**
danielk19778a414492004-06-29 08:59:35 +0000302** If zDatabase is 0, all databases are searched for the table and the
303** first matching table is returned. (No checking for duplicate table
304** names is done.) The search order is TEMP first, then MAIN, then any
305** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000306**
danielk19774adee202004-05-08 08:23:19 +0000307** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000308*/
drh9bb575f2004-09-06 17:24:11 +0000309Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000310 Table *p = 0;
311 int i;
drh9ca95732014-10-24 00:35:58 +0000312
drh21206082011-04-04 18:22:02 +0000313 /* All mutexes are required for schema access. Make sure we hold them. */
314 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
drhd4530972014-09-09 14:47:53 +0000315#if SQLITE_USER_AUTHENTICATION
316 /* Only the admin user is allowed to know that the sqlite_user table
317 ** exists */
drhe933b832014-09-10 17:34:28 +0000318 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
319 return 0;
320 }
drhd4530972014-09-09 14:47:53 +0000321#endif
danielk197753c0f742005-03-29 03:10:59 +0000322 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000323 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000324 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000325 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000326 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
drhd24cc422003-03-27 12:51:24 +0000327 if( p ) break;
328 }
drh74e24cd2002-01-09 03:19:59 +0000329 return p;
drh75897232000-05-29 14:26:00 +0000330}
331
332/*
danielk19778a414492004-06-29 08:59:35 +0000333** Locate the in-memory structure that describes a particular database
334** table given the name of that table and (optionally) the name of the
335** database containing the table. Return NULL if not found. Also leave an
336** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000337**
danielk19778a414492004-06-29 08:59:35 +0000338** The difference between this routine and sqlite3FindTable() is that this
339** routine leaves an error message in pParse->zErrMsg where
340** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000341*/
drhca424112008-01-25 15:04:48 +0000342Table *sqlite3LocateTable(
343 Parse *pParse, /* context in which to report errors */
344 int isView, /* True if looking for a VIEW rather than a TABLE */
345 const char *zName, /* Name of the table we are looking for */
346 const char *zDbase /* Name of the database. Might be NULL */
347){
drha69d9162003-04-17 22:57:53 +0000348 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000349
danielk19778a414492004-06-29 08:59:35 +0000350 /* Read the database schema. If an error occurs, leave an error message
351 ** and code in pParse and return NULL. */
352 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
353 return 0;
354 }
355
danielk19774adee202004-05-08 08:23:19 +0000356 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000357 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000358 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000359 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000360 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000361 }else{
drhca424112008-01-25 15:04:48 +0000362 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000363 }
drha6ecd332004-06-10 00:29:09 +0000364 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000365 }
drhe933b832014-09-10 17:34:28 +0000366#if SQLITE_USER_AUTHENICATION
367 else if( pParse->db->auth.authLevel<UAUTH_User ){
368 sqlite3ErrorMsg(pParse, "user not authenticated");
369 p = 0;
370 }
371#endif
drha69d9162003-04-17 22:57:53 +0000372 return p;
373}
374
375/*
dan41fb5cd2012-10-04 19:33:00 +0000376** Locate the table identified by *p.
377**
378** This is a wrapper around sqlite3LocateTable(). The difference between
379** sqlite3LocateTable() and this function is that this function restricts
380** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
381** non-NULL if it is part of a view or trigger program definition. See
382** sqlite3FixSrcList() for details.
383*/
384Table *sqlite3LocateTableItem(
385 Parse *pParse,
386 int isView,
387 struct SrcList_item *p
388){
389 const char *zDb;
390 assert( p->pSchema==0 || p->zDatabase==0 );
391 if( p->pSchema ){
392 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
393 zDb = pParse->db->aDb[iDb].zName;
394 }else{
395 zDb = p->zDatabase;
396 }
397 return sqlite3LocateTable(pParse, isView, p->zName, zDb);
398}
399
400/*
drha69d9162003-04-17 22:57:53 +0000401** Locate the in-memory structure that describes
402** a particular index given the name of that index
403** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000404** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000405**
406** If zDatabase is 0, all databases are searched for the
407** table and the first matching index is returned. (No checking
408** for duplicate index names is done.) The search order is
409** TEMP first, then MAIN, then any auxiliary databases added
410** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000411*/
drh9bb575f2004-09-06 17:24:11 +0000412Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000413 Index *p = 0;
414 int i;
drh21206082011-04-04 18:22:02 +0000415 /* All mutexes are required for schema access. Make sure we hold them. */
416 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
danielk197753c0f742005-03-29 03:10:59 +0000417 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000418 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000419 Schema *pSchema = db->aDb[j].pSchema;
drh04491712009-05-13 17:21:13 +0000420 assert( pSchema );
danielk19774adee202004-05-08 08:23:19 +0000421 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
drh21206082011-04-04 18:22:02 +0000422 assert( sqlite3SchemaMutexHeld(db, j, 0) );
drhacbcb7e2014-08-21 20:26:37 +0000423 p = sqlite3HashFind(&pSchema->idxHash, zName);
drhd24cc422003-03-27 12:51:24 +0000424 if( p ) break;
425 }
drh74e24cd2002-01-09 03:19:59 +0000426 return p;
drh75897232000-05-29 14:26:00 +0000427}
428
429/*
drh956bc922004-07-24 17:38:29 +0000430** Reclaim the memory used by an index
431*/
dan1feeaed2010-07-23 15:41:47 +0000432static void freeIndex(sqlite3 *db, Index *p){
drh92aa5ea2009-09-11 14:05:06 +0000433#ifndef SQLITE_OMIT_ANALYZE
dand46def72010-07-24 11:28:28 +0000434 sqlite3DeleteIndexSamples(db, p);
drh92aa5ea2009-09-11 14:05:06 +0000435#endif
drh1fe05372013-07-31 18:12:26 +0000436 sqlite3ExprDelete(db, p->pPartIdxWhere);
drh633e6d52008-07-28 19:34:53 +0000437 sqlite3DbFree(db, p->zColAff);
drh7f9c5db2013-10-23 00:32:58 +0000438 if( p->isResized ) sqlite3DbFree(db, p->azColl);
drh75b170b2014-10-04 00:07:44 +0000439#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
440 sqlite3_free(p->aiRowEst);
441#endif
drh633e6d52008-07-28 19:34:53 +0000442 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000443}
444
445/*
drhc96d8532005-05-03 12:30:33 +0000446** For the index called zIdxName which is found in the database iDb,
447** unlike that index from its Table then remove the index from
448** the index hash table and free all memory structures associated
449** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000450*/
drh9bb575f2004-09-06 17:24:11 +0000451void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000452 Index *pIndex;
drh21206082011-04-04 18:22:02 +0000453 Hash *pHash;
drh956bc922004-07-24 17:38:29 +0000454
drh21206082011-04-04 18:22:02 +0000455 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
456 pHash = &db->aDb[iDb].pSchema->idxHash;
drhacbcb7e2014-08-21 20:26:37 +0000457 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
drh22645842011-03-24 01:34:03 +0000458 if( ALWAYS(pIndex) ){
drh956bc922004-07-24 17:38:29 +0000459 if( pIndex->pTable->pIndex==pIndex ){
460 pIndex->pTable->pIndex = pIndex->pNext;
461 }else{
462 Index *p;
drh04491712009-05-13 17:21:13 +0000463 /* Justification of ALWAYS(); The index must be on the list of
464 ** indices. */
465 p = pIndex->pTable->pIndex;
466 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
467 if( ALWAYS(p && p->pNext==pIndex) ){
drh956bc922004-07-24 17:38:29 +0000468 p->pNext = pIndex->pNext;
469 }
drh5e00f6c2001-09-13 13:46:56 +0000470 }
dan1feeaed2010-07-23 15:41:47 +0000471 freeIndex(db, pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000472 }
drh956bc922004-07-24 17:38:29 +0000473 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000474}
475
476/*
drh81028a42012-05-15 18:28:27 +0000477** Look through the list of open database files in db->aDb[] and if
478** any have been closed, remove them from the list. Reallocate the
479** db->aDb[] structure to a smaller size, if possible.
drh1c2d8412003-03-31 00:30:47 +0000480**
drh81028a42012-05-15 18:28:27 +0000481** Entry 0 (the "main" database) and entry 1 (the "temp" database)
482** are never candidates for being collapsed.
drh74e24cd2002-01-09 03:19:59 +0000483*/
drh81028a42012-05-15 18:28:27 +0000484void sqlite3CollapseDatabaseArray(sqlite3 *db){
drh1c2d8412003-03-31 00:30:47 +0000485 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000486 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000487 struct Db *pDb = &db->aDb[i];
488 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000489 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000490 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000491 continue;
492 }
493 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000494 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000495 }
drh8bf8dc92003-05-17 17:35:10 +0000496 j++;
drh1c2d8412003-03-31 00:30:47 +0000497 }
498 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
499 db->nDb = j;
500 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
501 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000502 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000503 db->aDb = db->aDbStatic;
504 }
drhe0bc4042002-06-25 01:09:11 +0000505}
506
507/*
drh81028a42012-05-15 18:28:27 +0000508** Reset the schema for the database at index iDb. Also reset the
509** TEMP schema.
510*/
511void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
drhbae591a2012-06-05 19:20:03 +0000512 Db *pDb;
drh81028a42012-05-15 18:28:27 +0000513 assert( iDb<db->nDb );
514
515 /* Case 1: Reset the single schema identified by iDb */
drhbae591a2012-06-05 19:20:03 +0000516 pDb = &db->aDb[iDb];
drh81028a42012-05-15 18:28:27 +0000517 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
518 assert( pDb->pSchema!=0 );
519 sqlite3SchemaClear(pDb->pSchema);
520
521 /* If any database other than TEMP is reset, then also reset TEMP
522 ** since TEMP might be holding triggers that reference tables in the
523 ** other database.
524 */
525 if( iDb!=1 ){
526 pDb = &db->aDb[1];
527 assert( pDb->pSchema!=0 );
528 sqlite3SchemaClear(pDb->pSchema);
529 }
530 return;
531}
532
533/*
534** Erase all schema information from all attached databases (including
535** "main" and "temp") for a single database connection.
536*/
537void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
538 int i;
539 sqlite3BtreeEnterAll(db);
540 for(i=0; i<db->nDb; i++){
541 Db *pDb = &db->aDb[i];
542 if( pDb->pSchema ){
543 sqlite3SchemaClear(pDb->pSchema);
544 }
545 }
546 db->flags &= ~SQLITE_InternChanges;
547 sqlite3VtabUnlockList(db);
548 sqlite3BtreeLeaveAll(db);
549 sqlite3CollapseDatabaseArray(db);
550}
551
552/*
drhe0bc4042002-06-25 01:09:11 +0000553** This routine is called when a commit occurs.
554*/
drh9bb575f2004-09-06 17:24:11 +0000555void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000556 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000557}
558
559/*
dand46def72010-07-24 11:28:28 +0000560** Delete memory allocated for the column names of a table or view (the
561** Table.aCol[] array).
drh956bc922004-07-24 17:38:29 +0000562*/
dand46def72010-07-24 11:28:28 +0000563static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
drh956bc922004-07-24 17:38:29 +0000564 int i;
565 Column *pCol;
566 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000567 if( (pCol = pTable->aCol)!=0 ){
568 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000569 sqlite3DbFree(db, pCol->zName);
570 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +0000571 sqlite3DbFree(db, pCol->zDflt);
drh633e6d52008-07-28 19:34:53 +0000572 sqlite3DbFree(db, pCol->zType);
573 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000574 }
drh633e6d52008-07-28 19:34:53 +0000575 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000576 }
drh956bc922004-07-24 17:38:29 +0000577}
578
579/*
drh75897232000-05-29 14:26:00 +0000580** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000581** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000582**
583** This routine just deletes the data structure. It does not unlink
drhe61922a2009-05-02 13:29:37 +0000584** the table data structure from the hash table. But it does destroy
drhc2eef3b2002-08-31 18:53:06 +0000585** memory structures of the indices and foreign keys associated with
586** the table.
drh29ddd3a2012-05-15 12:49:32 +0000587**
588** The db parameter is optional. It is needed if the Table object
589** contains lookaside memory. (Table objects in the schema do not use
590** lookaside memory, but some ephemeral Table objects do.) Or the
591** db parameter can be used with db->pnBytesFreed to measure the memory
592** used by the Table object.
drh75897232000-05-29 14:26:00 +0000593*/
dan1feeaed2010-07-23 15:41:47 +0000594void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000595 Index *pIndex, *pNext;
drh29ddd3a2012-05-15 12:49:32 +0000596 TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
drhc2eef3b2002-08-31 18:53:06 +0000597
dand46def72010-07-24 11:28:28 +0000598 assert( !pTable || pTable->nRef>0 );
drhc2eef3b2002-08-31 18:53:06 +0000599
drhed8a3bb2005-06-06 21:19:56 +0000600 /* Do not delete the table until the reference count reaches zero. */
dand46def72010-07-24 11:28:28 +0000601 if( !pTable ) return;
602 if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
drhed8a3bb2005-06-06 21:19:56 +0000603
drh29ddd3a2012-05-15 12:49:32 +0000604 /* Record the number of outstanding lookaside allocations in schema Tables
605 ** prior to doing any free() operations. Since schema Tables do not use
606 ** lookaside, this number should not change. */
607 TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
608 db->lookaside.nOut : 0 );
609
dand46def72010-07-24 11:28:28 +0000610 /* Delete all indices associated with this table. */
drhc2eef3b2002-08-31 18:53:06 +0000611 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
612 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000613 assert( pIndex->pSchema==pTable->pSchema );
dand46def72010-07-24 11:28:28 +0000614 if( !db || db->pnBytesFreed==0 ){
615 char *zName = pIndex->zName;
616 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
drhacbcb7e2014-08-21 20:26:37 +0000617 &pIndex->pSchema->idxHash, zName, 0
dand46def72010-07-24 11:28:28 +0000618 );
drh21206082011-04-04 18:22:02 +0000619 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
dand46def72010-07-24 11:28:28 +0000620 assert( pOld==pIndex || pOld==0 );
621 }
622 freeIndex(db, pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000623 }
624
dan1da40a32009-09-19 17:00:31 +0000625 /* Delete any foreign keys attached to this table. */
dan1feeaed2010-07-23 15:41:47 +0000626 sqlite3FkDelete(db, pTable);
drhc2eef3b2002-08-31 18:53:06 +0000627
628 /* Delete the Table structure itself.
629 */
dand46def72010-07-24 11:28:28 +0000630 sqliteDeleteColumnNames(db, pTable);
drh633e6d52008-07-28 19:34:53 +0000631 sqlite3DbFree(db, pTable->zName);
632 sqlite3DbFree(db, pTable->zColAff);
633 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000634#ifndef SQLITE_OMIT_CHECK
drh2938f922012-03-07 19:13:29 +0000635 sqlite3ExprListDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000636#endif
drh078e4082010-07-28 19:17:51 +0000637#ifndef SQLITE_OMIT_VIRTUALTABLE
dan1feeaed2010-07-23 15:41:47 +0000638 sqlite3VtabClear(db, pTable);
drh078e4082010-07-28 19:17:51 +0000639#endif
drh633e6d52008-07-28 19:34:53 +0000640 sqlite3DbFree(db, pTable);
drh29ddd3a2012-05-15 12:49:32 +0000641
642 /* Verify that no lookaside memory was used by schema tables */
643 assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
drh75897232000-05-29 14:26:00 +0000644}
645
646/*
drh5edc3122001-09-13 21:53:09 +0000647** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000648** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000649*/
drh9bb575f2004-09-06 17:24:11 +0000650void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000651 Table *p;
drh956bc922004-07-24 17:38:29 +0000652 Db *pDb;
653
drhd229ca92002-01-09 13:30:41 +0000654 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000655 assert( iDb>=0 && iDb<db->nDb );
drh972a2312009-12-08 14:34:08 +0000656 assert( zTabName );
drh21206082011-04-04 18:22:02 +0000657 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh972a2312009-12-08 14:34:08 +0000658 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
drh956bc922004-07-24 17:38:29 +0000659 pDb = &db->aDb[iDb];
drhacbcb7e2014-08-21 20:26:37 +0000660 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
dan1feeaed2010-07-23 15:41:47 +0000661 sqlite3DeleteTable(db, p);
drh956bc922004-07-24 17:38:29 +0000662 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000663}
664
665/*
drha99db3b2004-06-19 14:49:12 +0000666** Given a token, return a string that consists of the text of that
drh24fb6272009-05-01 21:13:36 +0000667** token. Space to hold the returned string
drha99db3b2004-06-19 14:49:12 +0000668** is obtained from sqliteMalloc() and must be freed by the calling
669** function.
drh75897232000-05-29 14:26:00 +0000670**
drh24fb6272009-05-01 21:13:36 +0000671** Any quotation marks (ex: "name", 'name', [name], or `name`) that
672** surround the body of the token are removed.
673**
drhc96d8532005-05-03 12:30:33 +0000674** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000675** are not \000 terminated and are not persistent. The returned string
676** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000677*/
drh17435752007-08-16 04:30:38 +0000678char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000679 char *zName;
680 if( pName ){
drh17435752007-08-16 04:30:38 +0000681 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drhb7916a72009-05-27 10:31:29 +0000682 sqlite3Dequote(zName);
drha99db3b2004-06-19 14:49:12 +0000683 }else{
684 zName = 0;
685 }
drh75897232000-05-29 14:26:00 +0000686 return zName;
687}
688
689/*
danielk1977cbb18d22004-05-28 11:37:27 +0000690** Open the sqlite_master table stored in database number iDb for
691** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000692*/
danielk1977c00da102006-01-07 13:21:04 +0000693void sqlite3OpenMasterTable(Parse *p, int iDb){
694 Vdbe *v = sqlite3GetVdbe(p);
695 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
drh261c02d2013-10-25 14:46:15 +0000696 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
danielk19776ab3a2e2009-02-19 14:39:25 +0000697 if( p->nTab==0 ){
698 p->nTab = 1;
699 }
drhe0bc4042002-06-25 01:09:11 +0000700}
701
702/*
danielk197704103022009-02-03 16:51:24 +0000703** Parameter zName points to a nul-terminated buffer containing the name
704** of a database ("main", "temp" or the name of an attached db). This
705** function returns the index of the named database in db->aDb[], or
706** -1 if the named db cannot be found.
danielk1977cbb18d22004-05-28 11:37:27 +0000707*/
danielk197704103022009-02-03 16:51:24 +0000708int sqlite3FindDbName(sqlite3 *db, const char *zName){
709 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000710 if( zName ){
danielk197704103022009-02-03 16:51:24 +0000711 Db *pDb;
712 int n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000713 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000714 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000715 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000716 break;
drh73c42a12004-11-20 18:13:10 +0000717 }
danielk1977cbb18d22004-05-28 11:37:27 +0000718 }
719 }
danielk1977576ec6b2005-01-21 11:55:25 +0000720 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000721}
722
danielk197704103022009-02-03 16:51:24 +0000723/*
724** The token *pName contains the name of a database (either "main" or
725** "temp" or the name of an attached db). This routine returns the
726** index of the named database in db->aDb[], or -1 if the named db
727** does not exist.
728*/
729int sqlite3FindDb(sqlite3 *db, Token *pName){
730 int i; /* Database number */
731 char *zName; /* Name we are searching for */
732 zName = sqlite3NameFromToken(db, pName);
733 i = sqlite3FindDbName(db, zName);
734 sqlite3DbFree(db, zName);
735 return i;
736}
737
drh0e3d7472004-06-19 17:33:07 +0000738/* The table or view or trigger name is passed to this routine via tokens
739** pName1 and pName2. If the table name was fully qualified, for example:
740**
741** CREATE TABLE xxx.yyy (...);
742**
743** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
744** the table name is not fully qualified, i.e.:
745**
746** CREATE TABLE yyy(...);
747**
748** Then pName1 is set to "yyy" and pName2 is "".
749**
750** This routine sets the *ppUnqual pointer to point at the token (pName1 or
751** pName2) that stores the unqualified table name. The index of the
752** database "xxx" is returned.
753*/
danielk1977ef2cb632004-05-29 02:37:19 +0000754int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000755 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000756 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000757 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
758 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000759){
drh0e3d7472004-06-19 17:33:07 +0000760 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000761 sqlite3 *db = pParse->db;
762
drhc4a64fa2009-05-11 20:53:28 +0000763 if( ALWAYS(pName2!=0) && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000764 if( db->init.busy ) {
765 sqlite3ErrorMsg(pParse, "corrupt database");
shanedcc50b72008-11-13 18:29:50 +0000766 return -1;
767 }
danielk1977cbb18d22004-05-28 11:37:27 +0000768 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000769 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000770 if( iDb<0 ){
771 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000772 return -1;
773 }
774 }else{
775 assert( db->init.iDb==0 || db->init.busy );
776 iDb = db->init.iDb;
777 *pUnqual = pName1;
778 }
779 return iDb;
780}
781
782/*
danielk1977d8123362004-06-12 09:25:12 +0000783** This routine is used to check if the UTF-8 string zName is a legal
784** unqualified name for a new schema object (table, index, view or
785** trigger). All names are legal except those that begin with the string
786** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
787** is reserved for internal use.
788*/
789int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000790 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000791 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000792 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000793 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
794 return SQLITE_ERROR;
795 }
796 return SQLITE_OK;
797}
798
799/*
drh44156282013-10-23 22:23:03 +0000800** Return the PRIMARY KEY index of a table
801*/
802Index *sqlite3PrimaryKeyIndex(Table *pTab){
803 Index *p;
drh48dd1d82014-05-27 18:18:58 +0000804 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
drh44156282013-10-23 22:23:03 +0000805 return p;
806}
807
808/*
809** Return the column of index pIdx that corresponds to table
810** column iCol. Return -1 if not found.
811*/
812i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
813 int i;
814 for(i=0; i<pIdx->nColumn; i++){
815 if( iCol==pIdx->aiColumn[i] ) return i;
816 }
817 return -1;
818}
819
820/*
drh75897232000-05-29 14:26:00 +0000821** Begin constructing a new table representation in memory. This is
822** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000823** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000824** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000825** flag is true if the table should be stored in the auxiliary database
826** file instead of in the main database file. This is normally the case
827** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000828** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000829**
drhf57b3392001-10-08 13:22:32 +0000830** The new table record is initialized and put in pParse->pNewTable.
831** As more of the CREATE TABLE statement is parsed, additional action
832** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000833** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000834** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000835*/
danielk19774adee202004-05-08 08:23:19 +0000836void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000837 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000838 Token *pName1, /* First part of the name of the table or view */
839 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000840 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000841 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000842 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000843 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000844){
drh75897232000-05-29 14:26:00 +0000845 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000846 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000847 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000848 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000849 int iDb; /* Database number to create the table in */
850 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000851
danielk1977cbb18d22004-05-28 11:37:27 +0000852 /* The table or view name to create is passed to this routine via tokens
853 ** pName1 and pName2. If the table name was fully qualified, for example:
854 **
855 ** CREATE TABLE xxx.yyy (...);
856 **
857 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
858 ** the table name is not fully qualified, i.e.:
859 **
860 ** CREATE TABLE yyy(...);
861 **
862 ** Then pName1 is set to "yyy" and pName2 is "".
863 **
864 ** The call below sets the pName pointer to point at the token (pName1 or
865 ** pName2) that stores the unqualified table name. The variable iDb is
866 ** set to the index of the database that the table or view is to be
867 ** created in.
868 */
danielk1977ef2cb632004-05-29 02:37:19 +0000869 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000870 if( iDb<0 ) return;
dan72c5ea32010-09-28 15:55:47 +0000871 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
872 /* If creating a temp table, the name may not be qualified. Unless
873 ** the database name is "temp" anyway. */
danielk1977cbb18d22004-05-28 11:37:27 +0000874 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000875 return;
876 }
danielk197753c0f742005-03-29 03:10:59 +0000877 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000878
879 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000880 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000881 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000882 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000883 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000884 }
drh1d85d932004-02-14 23:05:52 +0000885 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000886#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000887 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000888 {
889 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000890 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000891 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000892 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000893 }
drhe5f9c642003-01-13 23:27:31 +0000894 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000895 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000896 code = SQLITE_CREATE_TEMP_VIEW;
897 }else{
898 code = SQLITE_CREATE_VIEW;
899 }
900 }else{
danielk197753c0f742005-03-29 03:10:59 +0000901 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000902 code = SQLITE_CREATE_TEMP_TABLE;
903 }else{
904 code = SQLITE_CREATE_TABLE;
905 }
906 }
danielk1977f1a381e2006-06-16 08:01:02 +0000907 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000908 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000909 }
910 }
911#endif
drhf57b3392001-10-08 13:22:32 +0000912
drhf57b3392001-10-08 13:22:32 +0000913 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000914 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000915 ** it does. The exception is if the statement being parsed was passed
916 ** to an sqlite3_declare_vtab() call. In that case only the column names
917 ** and types will be used, so there is no need to test for namespace
918 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000919 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000920 if( !IN_DECLARE_VTAB ){
dana16d1062010-09-28 17:37:28 +0000921 char *zDb = db->aDb[iDb].zName;
danielk19777e6ebfb2006-06-12 11:24:37 +0000922 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
923 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000924 }
dana16d1062010-09-28 17:37:28 +0000925 pTable = sqlite3FindTable(db, zName, zDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000926 if( pTable ){
927 if( !noErr ){
928 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
dan7687c832011-04-09 15:39:02 +0000929 }else{
drh33c59ec2015-04-19 20:39:17 +0000930 assert( !db->init.busy || CORRUPT_DB );
dan7687c832011-04-09 15:39:02 +0000931 sqlite3CodeVerifySchema(pParse, iDb);
danielk19777e6ebfb2006-06-12 11:24:37 +0000932 }
933 goto begin_table_error;
934 }
drh8a8a0d12010-09-28 20:26:44 +0000935 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
danielk19777e6ebfb2006-06-12 11:24:37 +0000936 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
937 goto begin_table_error;
938 }
drh75897232000-05-29 14:26:00 +0000939 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000940
danielk197726783a52007-08-29 14:06:22 +0000941 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000942 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000943 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000944 pParse->rc = SQLITE_NOMEM;
945 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000946 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000947 }
drh75897232000-05-29 14:26:00 +0000948 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000949 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000950 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000951 pTable->nRef = 1;
dancfc9df72014-04-25 15:01:01 +0000952 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
drhc4a64fa2009-05-11 20:53:28 +0000953 assert( pParse->pNewTable==0 );
drh75897232000-05-29 14:26:00 +0000954 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000955
drh4794f732004-11-05 17:17:50 +0000956 /* If this is the magic sqlite_sequence table used by autoincrement,
957 ** then record a pointer to this table in the main database structure
958 ** so that INSERT can find the table easily.
959 */
960#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000961 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh21206082011-04-04 18:22:02 +0000962 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +0000963 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000964 }
965#endif
966
drh17f71932002-02-21 12:01:27 +0000967 /* Begin generating the code that will insert the table record into
968 ** the SQLITE_MASTER table. Note in particular that we must go ahead
969 ** and allocate the record number for the table entry now. Before any
970 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
971 ** indices to be created and the table record must come before the
972 ** indices. Hence, the record number for the table must be allocated
973 ** now.
974 */
danielk19774adee202004-05-08 08:23:19 +0000975 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000976 int j1;
drhe321c292006-01-12 01:56:43 +0000977 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000978 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000979 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000980
danielk197720b1eaf2006-07-26 16:22:14 +0000981#ifndef SQLITE_OMIT_VIRTUALTABLE
982 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000983 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000984 }
985#endif
986
danielk197736963fd2005-02-19 08:18:05 +0000987 /* If the file format and encoding in the database have not been set,
988 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000989 */
drhb7654112008-01-12 12:48:07 +0000990 reg1 = pParse->regRowid = ++pParse->nMem;
991 reg2 = pParse->regRoot = ++pParse->nMem;
992 reg3 = ++pParse->nMem;
danielk19770d19f7a2009-06-03 11:25:07 +0000993 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
drhfb982642007-08-30 01:19:59 +0000994 sqlite3VdbeUsesBtree(v, iDb);
drh688852a2014-02-17 22:40:43 +0000995 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
drhe321c292006-01-12 01:56:43 +0000996 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000997 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000998 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
danielk19770d19f7a2009-06-03 11:25:07 +0000999 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
drhb7654112008-01-12 12:48:07 +00001000 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
danielk19770d19f7a2009-06-03 11:25:07 +00001001 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
drhb7654112008-01-12 12:48:07 +00001002 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +00001003
drh4794f732004-11-05 17:17:50 +00001004 /* This just creates a place-holder record in the sqlite_master table.
1005 ** The record created does not contain anything yet. It will be replaced
1006 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +00001007 **
drh0fa991b2009-03-21 16:19:26 +00001008 ** The rowid for the new entry is left in register pParse->regRowid.
1009 ** The root page number of the new table is left in reg pParse->regRoot.
1010 ** The rowid and root page number values are needed by the code that
1011 ** sqlite3EndTable will generate.
drh4794f732004-11-05 17:17:50 +00001012 */
danielk1977f1a381e2006-06-16 08:01:02 +00001013#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1014 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +00001015 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001016 }else
1017#endif
1018 {
drh8a120f82013-11-01 17:59:53 +00001019 pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +00001020 }
danielk1977c00da102006-01-07 13:21:04 +00001021 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +00001022 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1023 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
1024 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1025 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +00001026 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +00001027 }
drh23bf66d2004-12-14 03:34:34 +00001028
1029 /* Normal (non-error) return. */
1030 return;
1031
1032 /* If an error occurs, we jump here */
1033begin_table_error:
drh633e6d52008-07-28 19:34:53 +00001034 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +00001035 return;
drh75897232000-05-29 14:26:00 +00001036}
1037
1038/*
danielk1977c60e9b82005-01-31 12:42:29 +00001039** This macro is used to compare two strings in a case-insensitive manner.
1040** It is slightly faster than calling sqlite3StrICmp() directly, but
1041** produces larger code.
1042**
1043** WARNING: This macro is not compatible with the strcmp() family. It
1044** returns true if the two strings are equal, otherwise false.
1045*/
1046#define STRICMP(x, y) (\
1047sqlite3UpperToLower[*(unsigned char *)(x)]== \
1048sqlite3UpperToLower[*(unsigned char *)(y)] \
1049&& sqlite3StrICmp((x)+1,(y)+1)==0 )
1050
1051/*
drh75897232000-05-29 14:26:00 +00001052** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +00001053**
1054** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +00001055** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +00001056** first to get things going. Then this routine is called for each
1057** column.
drh75897232000-05-29 14:26:00 +00001058*/
danielk19774adee202004-05-08 08:23:19 +00001059void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +00001060 Table *p;
drh97fc3d02002-05-22 21:27:03 +00001061 int i;
drha99db3b2004-06-19 14:49:12 +00001062 char *z;
drhc9b84a12002-06-20 11:36:48 +00001063 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +00001064 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001065 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +00001066#if SQLITE_MAX_COLUMN
1067 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +00001068 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1069 return;
1070 }
drhbb4957f2008-03-20 14:03:29 +00001071#endif
danielk1977ae74e032008-12-23 11:11:51 +00001072 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +00001073 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +00001074 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +00001075 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +00001076 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +00001077 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +00001078 return;
1079 }
1080 }
drh75897232000-05-29 14:26:00 +00001081 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +00001082 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +00001083 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001084 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +00001085 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +00001086 return;
1087 }
drh6d4abfb2001-10-22 02:58:08 +00001088 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +00001089 }
drhc9b84a12002-06-20 11:36:48 +00001090 pCol = &p->aCol[p->nCol];
1091 memset(pCol, 0, sizeof(p->aCol[0]));
1092 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +00001093
1094 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +00001095 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
1096 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +00001097 */
danielk19774f057f92004-06-08 00:02:33 +00001098 pCol->affinity = SQLITE_AFF_NONE;
drhfdaac672013-10-04 15:30:21 +00001099 pCol->szEst = 1;
drhc9b84a12002-06-20 11:36:48 +00001100 p->nCol++;
drh75897232000-05-29 14:26:00 +00001101}
1102
1103/*
drh382c0242001-10-06 16:33:02 +00001104** This routine is called by the parser while in the middle of
1105** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1106** been seen on a column. This routine sets the notNull flag on
1107** the column currently under construction.
1108*/
danielk19774adee202004-05-08 08:23:19 +00001109void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +00001110 Table *p;
drhc4a64fa2009-05-11 20:53:28 +00001111 p = pParse->pNewTable;
1112 if( p==0 || NEVER(p->nCol<1) ) return;
1113 p->aCol[p->nCol-1].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +00001114}
1115
1116/*
danielk197752a83fb2005-01-31 12:56:44 +00001117** Scan the column type name zType (length nType) and return the
1118** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001119**
1120** This routine does a case-independent search of zType for the
1121** substrings in the following table. If one of the substrings is
1122** found, the corresponding affinity is returned. If zType contains
1123** more than one of the substrings, entries toward the top of
1124** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001125** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001126**
1127** Substring | Affinity
1128** --------------------------------
1129** 'INT' | SQLITE_AFF_INTEGER
1130** 'CHAR' | SQLITE_AFF_TEXT
1131** 'CLOB' | SQLITE_AFF_TEXT
1132** 'TEXT' | SQLITE_AFF_TEXT
1133** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001134** 'REAL' | SQLITE_AFF_REAL
1135** 'FLOA' | SQLITE_AFF_REAL
1136** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001137**
1138** If none of the substrings in the above table are found,
1139** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001140*/
drhfdaac672013-10-04 15:30:21 +00001141char sqlite3AffinityType(const char *zIn, u8 *pszEst){
danielk1977b3dff962005-02-01 01:21:55 +00001142 u32 h = 0;
1143 char aff = SQLITE_AFF_NUMERIC;
drhd3037a42013-10-04 18:29:25 +00001144 const char *zChar = 0;
danielk197752a83fb2005-01-31 12:56:44 +00001145
drhfdaac672013-10-04 15:30:21 +00001146 if( zIn==0 ) return aff;
1147 while( zIn[0] ){
drhb7916a72009-05-27 10:31:29 +00001148 h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
danielk1977b3dff962005-02-01 01:21:55 +00001149 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001150 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
drhfdaac672013-10-04 15:30:21 +00001151 aff = SQLITE_AFF_TEXT;
1152 zChar = zIn;
danielk1977201f7162005-02-01 02:13:29 +00001153 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1154 aff = SQLITE_AFF_TEXT;
1155 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1156 aff = SQLITE_AFF_TEXT;
1157 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001158 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001159 aff = SQLITE_AFF_NONE;
drhd3037a42013-10-04 18:29:25 +00001160 if( zIn[0]=='(' ) zChar = zIn;
drh8a512562005-11-14 22:29:05 +00001161#ifndef SQLITE_OMIT_FLOATING_POINT
1162 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1163 && aff==SQLITE_AFF_NUMERIC ){
1164 aff = SQLITE_AFF_REAL;
1165 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1166 && aff==SQLITE_AFF_NUMERIC ){
1167 aff = SQLITE_AFF_REAL;
1168 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1169 && aff==SQLITE_AFF_NUMERIC ){
1170 aff = SQLITE_AFF_REAL;
1171#endif
danielk1977201f7162005-02-01 02:13:29 +00001172 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001173 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001174 break;
danielk197752a83fb2005-01-31 12:56:44 +00001175 }
1176 }
drhd3037a42013-10-04 18:29:25 +00001177
1178 /* If pszEst is not NULL, store an estimate of the field size. The
1179 ** estimate is scaled so that the size of an integer is 1. */
drhfdaac672013-10-04 15:30:21 +00001180 if( pszEst ){
drhd3037a42013-10-04 18:29:25 +00001181 *pszEst = 1; /* default size is approx 4 bytes */
drh7ea31cc2014-09-18 14:36:00 +00001182 if( aff<SQLITE_AFF_NUMERIC ){
drhd3037a42013-10-04 18:29:25 +00001183 if( zChar ){
1184 while( zChar[0] ){
1185 if( sqlite3Isdigit(zChar[0]) ){
drh4f991892013-10-11 15:05:05 +00001186 int v = 0;
drhd3037a42013-10-04 18:29:25 +00001187 sqlite3GetInt32(zChar, &v);
1188 v = v/4 + 1;
1189 if( v>255 ) v = 255;
1190 *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1191 break;
1192 }
1193 zChar++;
drhfdaac672013-10-04 15:30:21 +00001194 }
drhd3037a42013-10-04 18:29:25 +00001195 }else{
1196 *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
drhfdaac672013-10-04 15:30:21 +00001197 }
drhfdaac672013-10-04 15:30:21 +00001198 }
1199 }
danielk1977b3dff962005-02-01 01:21:55 +00001200 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001201}
1202
1203/*
drh382c0242001-10-06 16:33:02 +00001204** This routine is called by the parser while in the middle of
1205** parsing a CREATE TABLE statement. The pFirst token is the first
1206** token in the sequence of tokens that describe the type of the
1207** column currently under construction. pLast is the last token
1208** in the sequence. Use this information to construct a string
1209** that contains the typename of the column and store that string
1210** in zType.
1211*/
drh487e2622005-06-25 18:42:14 +00001212void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001213 Table *p;
drhc9b84a12002-06-20 11:36:48 +00001214 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001215
drhc4a64fa2009-05-11 20:53:28 +00001216 p = pParse->pNewTable;
1217 if( p==0 || NEVER(p->nCol<1) ) return;
1218 pCol = &p->aCol[p->nCol-1];
drh5f1d2fa2015-04-19 21:59:19 +00001219 assert( pCol->zType==0 || CORRUPT_DB );
1220 sqlite3DbFree(pParse->db, pCol->zType);
drhc4a64fa2009-05-11 20:53:28 +00001221 pCol->zType = sqlite3NameFromToken(pParse->db, pType);
drhfdaac672013-10-04 15:30:21 +00001222 pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
drh382c0242001-10-06 16:33:02 +00001223}
1224
1225/*
danielk19777977a172004-11-09 12:44:37 +00001226** The expression is the default value for the most recently added column
1227** of the table currently under construction.
1228**
1229** Default value expressions must be constant. Raise an exception if this
1230** is not the case.
drhd9b02572001-04-15 00:37:09 +00001231**
1232** This routine is called by the parser while in the middle of
1233** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001234*/
drhb7916a72009-05-27 10:31:29 +00001235void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
drh7020f652000-06-03 18:06:52 +00001236 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001237 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001238 sqlite3 *db = pParse->db;
drhc4a64fa2009-05-11 20:53:28 +00001239 p = pParse->pNewTable;
1240 if( p!=0 ){
drh42b9d7c2005-08-13 00:56:27 +00001241 pCol = &(p->aCol[p->nCol-1]);
drhfeada2d2014-09-24 13:20:22 +00001242 if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
drh42b9d7c2005-08-13 00:56:27 +00001243 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1244 pCol->zName);
1245 }else{
danielk19776ab3a2e2009-02-19 14:39:25 +00001246 /* A copy of pExpr is used instead of the original, as pExpr contains
1247 ** tokens that point to volatile memory. The 'span' of the expression
1248 ** is required by pragma table_info.
1249 */
drh633e6d52008-07-28 19:34:53 +00001250 sqlite3ExprDelete(db, pCol->pDflt);
drhb7916a72009-05-27 10:31:29 +00001251 pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
1252 sqlite3DbFree(db, pCol->zDflt);
1253 pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001254 (int)(pSpan->zEnd - pSpan->zStart));
drh42b9d7c2005-08-13 00:56:27 +00001255 }
danielk19777977a172004-11-09 12:44:37 +00001256 }
drhb7916a72009-05-27 10:31:29 +00001257 sqlite3ExprDelete(db, pSpan->pExpr);
drh7020f652000-06-03 18:06:52 +00001258}
1259
1260/*
drh4a324312001-12-21 14:30:42 +00001261** Designate the PRIMARY KEY for the table. pList is a list of names
1262** of columns that form the primary key. If pList is NULL, then the
1263** most recently added column of the table is the primary key.
1264**
1265** A table can have at most one primary key. If the table already has
1266** a primary key (and this is the second primary key) then create an
1267** error.
1268**
1269** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001270** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001271** field of the table under construction to be the index of the
1272** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1273** no INTEGER PRIMARY KEY.
1274**
1275** If the key is not an INTEGER PRIMARY KEY, then create a unique
1276** index for the key. No index is created for INTEGER PRIMARY KEYs.
1277*/
drh205f48e2004-11-05 00:43:11 +00001278void sqlite3AddPrimaryKey(
1279 Parse *pParse, /* Parsing context */
1280 ExprList *pList, /* List of field names to be indexed */
1281 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001282 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1283 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001284){
drh4a324312001-12-21 14:30:42 +00001285 Table *pTab = pParse->pNewTable;
1286 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001287 int iCol = -1, i;
drh8ea30bf2013-10-22 01:18:17 +00001288 int nTerm;
danielk1977c7d54102006-06-15 07:29:00 +00001289 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001290 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001291 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001292 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001293 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001294 }
drh7d10d5a2008-08-20 16:35:10 +00001295 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001296 if( pList==0 ){
1297 iCol = pTab->nCol - 1;
drha371ace2012-09-13 14:22:47 +00001298 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
drh8ea30bf2013-10-22 01:18:17 +00001299 zType = pTab->aCol[iCol].zType;
1300 nTerm = 1;
drh78100cc2003-08-23 22:40:53 +00001301 }else{
drh8ea30bf2013-10-22 01:18:17 +00001302 nTerm = pList->nExpr;
1303 for(i=0; i<nTerm; i++){
drh78100cc2003-08-23 22:40:53 +00001304 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001305 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
drh8ea30bf2013-10-22 01:18:17 +00001306 pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
1307 zType = pTab->aCol[iCol].zType;
drhd3d39e92004-05-20 22:16:29 +00001308 break;
1309 }
drh78100cc2003-08-23 22:40:53 +00001310 }
drh4a324312001-12-21 14:30:42 +00001311 }
1312 }
drh8ea30bf2013-10-22 01:18:17 +00001313 if( nTerm==1
1314 && zType && sqlite3StrICmp(zType, "INTEGER")==0
1315 && sortOrder==SQLITE_SO_ASC
1316 ){
drh4a324312001-12-21 14:30:42 +00001317 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001318 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001319 assert( autoInc==0 || autoInc==1 );
1320 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh7f9c5db2013-10-23 00:32:58 +00001321 if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
drh205f48e2004-11-05 00:43:11 +00001322 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001323#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001324 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1325 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001326#endif
drh4a324312001-12-21 14:30:42 +00001327 }else{
drhc6bd4e42013-11-02 14:37:18 +00001328 Vdbe *v = pParse->pVdbe;
dan1da40a32009-09-19 17:00:31 +00001329 Index *p;
drhc6bd4e42013-11-02 14:37:18 +00001330 if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
drh8a9789b2013-08-01 03:36:59 +00001331 p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
drh1fe05372013-07-31 18:12:26 +00001332 0, sortOrder, 0);
dan1da40a32009-09-19 17:00:31 +00001333 if( p ){
drh48dd1d82014-05-27 18:18:58 +00001334 p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drhc6bd4e42013-11-02 14:37:18 +00001335 if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
dan1da40a32009-09-19 17:00:31 +00001336 }
drhe0194f22003-02-26 13:52:51 +00001337 pList = 0;
drh4a324312001-12-21 14:30:42 +00001338 }
drhe0194f22003-02-26 13:52:51 +00001339
1340primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001341 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001342 return;
drh4a324312001-12-21 14:30:42 +00001343}
1344
1345/*
drhffe07b22005-11-03 00:41:17 +00001346** Add a new CHECK constraint to the table currently under construction.
1347*/
1348void sqlite3AddCheckConstraint(
1349 Parse *pParse, /* Parsing context */
1350 Expr *pCheckExpr /* The check expression */
1351){
1352#ifndef SQLITE_OMIT_CHECK
1353 Table *pTab = pParse->pNewTable;
drhc9bbb012014-05-21 08:48:18 +00001354 sqlite3 *db = pParse->db;
1355 if( pTab && !IN_DECLARE_VTAB
1356 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
1357 ){
drh2938f922012-03-07 19:13:29 +00001358 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
1359 if( pParse->constraintName.n ){
1360 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
1361 }
drh33e619f2009-05-28 01:00:55 +00001362 }else
drhffe07b22005-11-03 00:41:17 +00001363#endif
drh33e619f2009-05-28 01:00:55 +00001364 {
drh2938f922012-03-07 19:13:29 +00001365 sqlite3ExprDelete(pParse->db, pCheckExpr);
drh33e619f2009-05-28 01:00:55 +00001366 }
drhffe07b22005-11-03 00:41:17 +00001367}
1368
1369/*
drhd3d39e92004-05-20 22:16:29 +00001370** Set the collation function of the most recently parsed table column
1371** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001372*/
danielk197739002502007-11-12 09:50:26 +00001373void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001374 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001375 int i;
danielk197739002502007-11-12 09:50:26 +00001376 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001377 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001378
danielk1977b8cbb872006-06-19 05:33:45 +00001379 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001380 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001381 db = pParse->db;
1382 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001383 if( !zColl ) return;
1384
drhc4a64fa2009-05-11 20:53:28 +00001385 if( sqlite3LocateCollSeq(pParse, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001386 Index *pIdx;
drhfe685c82013-06-08 19:58:27 +00001387 sqlite3DbFree(db, p->aCol[i].zColl);
danielk197739002502007-11-12 09:50:26 +00001388 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001389
1390 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1391 ** then an index may have been created on this column before the
1392 ** collation type was added. Correct this if it is the case.
1393 */
1394 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhbbbdc832013-10-22 18:01:40 +00001395 assert( pIdx->nKeyCol==1 );
danielk1977b3bf5562006-01-10 17:58:23 +00001396 if( pIdx->aiColumn[0]==i ){
1397 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001398 }
1399 }
danielk197739002502007-11-12 09:50:26 +00001400 }else{
drh633e6d52008-07-28 19:34:53 +00001401 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001402 }
danielk19777cedc8d2004-06-10 10:50:08 +00001403}
1404
danielk1977466be562004-06-10 02:16:01 +00001405/*
1406** This function returns the collation sequence for database native text
1407** encoding identified by the string zName, length nName.
1408**
1409** If the requested collation sequence is not available, or not available
1410** in the database native encoding, the collation factory is invoked to
1411** request it. If the collation factory does not supply such a sequence,
1412** and the sequence is available in another text encoding, then that is
1413** returned instead.
1414**
1415** If no versions of the requested collations sequence are available, or
1416** another error occurs, NULL is returned and an error message written into
1417** pParse.
drha34001c2007-02-02 12:44:37 +00001418**
1419** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1420** invokes the collation factory if the named collation cannot be found
1421** and generates an error message.
drhc4a64fa2009-05-11 20:53:28 +00001422**
1423** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
danielk1977466be562004-06-10 02:16:01 +00001424*/
drhc4a64fa2009-05-11 20:53:28 +00001425CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
danielk19774dade032005-05-25 10:45:10 +00001426 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001427 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001428 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001429 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001430
drhc4a64fa2009-05-11 20:53:28 +00001431 pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001432 if( !initbusy && (!pColl || !pColl->xCmp) ){
drh79e72a52012-10-05 14:43:40 +00001433 pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
danielk1977466be562004-06-10 02:16:01 +00001434 }
1435
danielk19770202b292004-06-09 09:55:16 +00001436 return pColl;
1437}
1438
1439
drh8e2ca022002-06-17 17:07:19 +00001440/*
drh3f7d4e42004-07-24 14:35:58 +00001441** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001442**
1443** The schema cookie is used to determine when the schema for the
1444** database changes. After each schema change, the cookie value
1445** changes. When a process first reads the schema it records the
1446** cookie. Thereafter, whenever it goes to access the database,
1447** it checks the cookie to make sure the schema has not changed
1448** since it was last read.
1449**
1450** This plan is not completely bullet-proof. It is possible for
1451** the schema to change multiple times and for the cookie to be
1452** set back to prior value. But schema changes are infrequent
1453** and the probability of hitting the same cookie value is only
1454** 1 chance in 2^32. So we're safe enough.
1455*/
drh9cbf3422008-01-17 16:22:13 +00001456void sqlite3ChangeCookie(Parse *pParse, int iDb){
1457 int r1 = sqlite3GetTempReg(pParse);
1458 sqlite3 *db = pParse->db;
1459 Vdbe *v = pParse->pVdbe;
drh21206082011-04-04 18:22:02 +00001460 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh9cbf3422008-01-17 16:22:13 +00001461 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
danielk19770d19f7a2009-06-03 11:25:07 +00001462 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
drh9cbf3422008-01-17 16:22:13 +00001463 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001464}
1465
1466/*
drh969fa7c2002-02-18 18:30:32 +00001467** Measure the number of characters needed to output the given
1468** identifier. The number returned includes any quotes used
1469** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001470**
1471** The estimate is conservative. It might be larger that what is
1472** really needed.
drh969fa7c2002-02-18 18:30:32 +00001473*/
1474static int identLength(const char *z){
1475 int n;
drh17f71932002-02-21 12:01:27 +00001476 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001477 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001478 }
drh234c39d2004-07-24 03:30:47 +00001479 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001480}
1481
1482/*
danielk19771b870de2009-03-14 08:37:23 +00001483** The first parameter is a pointer to an output buffer. The second
1484** parameter is a pointer to an integer that contains the offset at
1485** which to write into the output buffer. This function copies the
1486** nul-terminated string pointed to by the third parameter, zSignedIdent,
1487** to the specified offset in the buffer and updates *pIdx to refer
1488** to the first byte after the last byte written before returning.
1489**
1490** If the string zSignedIdent consists entirely of alpha-numeric
1491** characters, does not begin with a digit and is not an SQL keyword,
1492** then it is copied to the output buffer exactly as it is. Otherwise,
1493** it is quoted using double-quotes.
1494*/
drhc4a64fa2009-05-11 20:53:28 +00001495static void identPut(char *z, int *pIdx, char *zSignedIdent){
drh4c755c02004-08-08 20:22:17 +00001496 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001497 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001498 i = *pIdx;
danielk19771b870de2009-03-14 08:37:23 +00001499
drh17f71932002-02-21 12:01:27 +00001500 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001501 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001502 }
drhc7407522014-01-10 20:38:12 +00001503 needQuote = sqlite3Isdigit(zIdent[0])
1504 || sqlite3KeywordCode(zIdent, j)!=TK_ID
1505 || zIdent[j]!=0
1506 || j==0;
danielk19771b870de2009-03-14 08:37:23 +00001507
drh234c39d2004-07-24 03:30:47 +00001508 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001509 for(j=0; zIdent[j]; j++){
1510 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001511 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001512 }
drh234c39d2004-07-24 03:30:47 +00001513 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001514 z[i] = 0;
1515 *pIdx = i;
1516}
1517
1518/*
1519** Generate a CREATE TABLE statement appropriate for the given
1520** table. Memory to hold the text of the statement is obtained
1521** from sqliteMalloc() and must be freed by the calling function.
1522*/
drh1d34fde2009-02-03 15:50:33 +00001523static char *createTableStmt(sqlite3 *db, Table *p){
drh969fa7c2002-02-18 18:30:32 +00001524 int i, k, n;
1525 char *zStmt;
drhc4a64fa2009-05-11 20:53:28 +00001526 char *zSep, *zSep2, *zEnd;
drh234c39d2004-07-24 03:30:47 +00001527 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001528 n = 0;
drh234c39d2004-07-24 03:30:47 +00001529 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001530 n += identLength(pCol->zName) + 5;
drh969fa7c2002-02-18 18:30:32 +00001531 }
1532 n += identLength(p->zName);
drhc4a64fa2009-05-11 20:53:28 +00001533 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001534 zSep = "";
1535 zSep2 = ",";
1536 zEnd = ")";
1537 }else{
1538 zSep = "\n ";
1539 zSep2 = ",\n ";
1540 zEnd = "\n)";
1541 }
drhe0bc4042002-06-25 01:09:11 +00001542 n += 35 + 6*p->nCol;
drhb9755982010-07-24 16:34:37 +00001543 zStmt = sqlite3DbMallocRaw(0, n);
drh820a9062008-01-31 13:35:48 +00001544 if( zStmt==0 ){
1545 db->mallocFailed = 1;
1546 return 0;
1547 }
drhbdb339f2009-02-02 18:03:21 +00001548 sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001549 k = sqlite3Strlen30(zStmt);
drhc4a64fa2009-05-11 20:53:28 +00001550 identPut(zStmt, &k, p->zName);
drh969fa7c2002-02-18 18:30:32 +00001551 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001552 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drhc4a64fa2009-05-11 20:53:28 +00001553 static const char * const azType[] = {
drhc4a64fa2009-05-11 20:53:28 +00001554 /* SQLITE_AFF_NONE */ "",
drh7ea31cc2014-09-18 14:36:00 +00001555 /* SQLITE_AFF_TEXT */ " TEXT",
drhc4a64fa2009-05-11 20:53:28 +00001556 /* SQLITE_AFF_NUMERIC */ " NUM",
1557 /* SQLITE_AFF_INTEGER */ " INT",
1558 /* SQLITE_AFF_REAL */ " REAL"
1559 };
1560 int len;
1561 const char *zType;
1562
drh5bb3eb92007-05-04 13:15:55 +00001563 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001564 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001565 zSep = zSep2;
drhc4a64fa2009-05-11 20:53:28 +00001566 identPut(zStmt, &k, pCol->zName);
drh7ea31cc2014-09-18 14:36:00 +00001567 assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
1568 assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
drhc4a64fa2009-05-11 20:53:28 +00001569 testcase( pCol->affinity==SQLITE_AFF_NONE );
drh7ea31cc2014-09-18 14:36:00 +00001570 testcase( pCol->affinity==SQLITE_AFF_TEXT );
drhc4a64fa2009-05-11 20:53:28 +00001571 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
1572 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
1573 testcase( pCol->affinity==SQLITE_AFF_REAL );
1574
drh7ea31cc2014-09-18 14:36:00 +00001575 zType = azType[pCol->affinity - SQLITE_AFF_NONE];
drhc4a64fa2009-05-11 20:53:28 +00001576 len = sqlite3Strlen30(zType);
drhb7916a72009-05-27 10:31:29 +00001577 assert( pCol->affinity==SQLITE_AFF_NONE
drhfdaac672013-10-04 15:30:21 +00001578 || pCol->affinity==sqlite3AffinityType(zType, 0) );
drhc4a64fa2009-05-11 20:53:28 +00001579 memcpy(&zStmt[k], zType, len);
1580 k += len;
1581 assert( k<=n );
drh969fa7c2002-02-18 18:30:32 +00001582 }
drh5bb3eb92007-05-04 13:15:55 +00001583 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001584 return zStmt;
1585}
1586
1587/*
drh7f9c5db2013-10-23 00:32:58 +00001588** Resize an Index object to hold N columns total. Return SQLITE_OK
1589** on success and SQLITE_NOMEM on an OOM error.
1590*/
1591static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
1592 char *zExtra;
1593 int nByte;
1594 if( pIdx->nColumn>=N ) return SQLITE_OK;
1595 assert( pIdx->isResized==0 );
1596 nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
1597 zExtra = sqlite3DbMallocZero(db, nByte);
1598 if( zExtra==0 ) return SQLITE_NOMEM;
1599 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
1600 pIdx->azColl = (char**)zExtra;
1601 zExtra += sizeof(char*)*N;
1602 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
1603 pIdx->aiColumn = (i16*)zExtra;
1604 zExtra += sizeof(i16)*N;
1605 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
1606 pIdx->aSortOrder = (u8*)zExtra;
1607 pIdx->nColumn = N;
1608 pIdx->isResized = 1;
1609 return SQLITE_OK;
1610}
1611
1612/*
drhfdaac672013-10-04 15:30:21 +00001613** Estimate the total row width for a table.
1614*/
drhe13e9f52013-10-05 19:18:00 +00001615static void estimateTableWidth(Table *pTab){
drhfdaac672013-10-04 15:30:21 +00001616 unsigned wTable = 0;
1617 const Column *pTabCol;
1618 int i;
1619 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
1620 wTable += pTabCol->szEst;
1621 }
1622 if( pTab->iPKey<0 ) wTable++;
drhe13e9f52013-10-05 19:18:00 +00001623 pTab->szTabRow = sqlite3LogEst(wTable*4);
drhfdaac672013-10-04 15:30:21 +00001624}
1625
1626/*
drhe13e9f52013-10-05 19:18:00 +00001627** Estimate the average size of a row for an index.
drhfdaac672013-10-04 15:30:21 +00001628*/
drhe13e9f52013-10-05 19:18:00 +00001629static void estimateIndexWidth(Index *pIdx){
drhbbbdc832013-10-22 18:01:40 +00001630 unsigned wIndex = 0;
drhfdaac672013-10-04 15:30:21 +00001631 int i;
1632 const Column *aCol = pIdx->pTable->aCol;
1633 for(i=0; i<pIdx->nColumn; i++){
drhbbbdc832013-10-22 18:01:40 +00001634 i16 x = pIdx->aiColumn[i];
1635 assert( x<pIdx->pTable->nCol );
1636 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
drhfdaac672013-10-04 15:30:21 +00001637 }
drhe13e9f52013-10-05 19:18:00 +00001638 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
drhfdaac672013-10-04 15:30:21 +00001639}
1640
drh7f9c5db2013-10-23 00:32:58 +00001641/* Return true if value x is found any of the first nCol entries of aiCol[]
1642*/
1643static int hasColumn(const i16 *aiCol, int nCol, int x){
1644 while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
1645 return 0;
1646}
1647
1648/*
drhc6bd4e42013-11-02 14:37:18 +00001649** This routine runs at the end of parsing a CREATE TABLE statement that
1650** has a WITHOUT ROWID clause. The job of this routine is to convert both
1651** internal schema data structures and the generated VDBE code so that they
1652** are appropriate for a WITHOUT ROWID table instead of a rowid table.
1653** Changes include:
drh7f9c5db2013-10-23 00:32:58 +00001654**
drhc6bd4e42013-11-02 14:37:18 +00001655** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
1656** no rowid btree for a WITHOUT ROWID. Instead, the canonical
1657** data storage is a covering index btree.
1658** (2) Bypass the creation of the sqlite_master table entry
peter.d.reid60ec9142014-09-06 16:39:46 +00001659** for the PRIMARY KEY as the primary key index is now
drhc6bd4e42013-11-02 14:37:18 +00001660** identified by the sqlite_master table entry of the table itself.
1661** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
1662** schema to the rootpage from the main table.
1663** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
1664** (5) Add all table columns to the PRIMARY KEY Index object
1665** so that the PRIMARY KEY is a covering index. The surplus
1666** columns are part of KeyInfo.nXField and are not used for
1667** sorting or lookup or uniqueness checks.
1668** (6) Replace the rowid tail on all automatically generated UNIQUE
1669** indices with the PRIMARY KEY columns.
drh7f9c5db2013-10-23 00:32:58 +00001670*/
1671static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
1672 Index *pIdx;
1673 Index *pPk;
1674 int nPk;
1675 int i, j;
1676 sqlite3 *db = pParse->db;
drhc6bd4e42013-11-02 14:37:18 +00001677 Vdbe *v = pParse->pVdbe;
drh7f9c5db2013-10-23 00:32:58 +00001678
1679 /* Convert the OP_CreateTable opcode that would normally create the
peter.d.reid60ec9142014-09-06 16:39:46 +00001680 ** root-page for the table into an OP_CreateIndex opcode. The index
drhc6bd4e42013-11-02 14:37:18 +00001681 ** created will become the PRIMARY KEY index.
drh7f9c5db2013-10-23 00:32:58 +00001682 */
1683 if( pParse->addrCrTab ){
drhc6bd4e42013-11-02 14:37:18 +00001684 assert( v );
1685 sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
1686 }
1687
1688 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
1689 ** table entry.
1690 */
1691 if( pParse->addrSkipPK ){
1692 assert( v );
1693 sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
drh7f9c5db2013-10-23 00:32:58 +00001694 }
1695
1696 /* Locate the PRIMARY KEY index. Or, if this table was originally
1697 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
1698 */
1699 if( pTab->iPKey>=0 ){
1700 ExprList *pList;
1701 pList = sqlite3ExprListAppend(pParse, 0, 0);
1702 if( pList==0 ) return;
1703 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
1704 pTab->aCol[pTab->iPKey].zName);
1705 pList->a[0].sortOrder = pParse->iPkSortOrder;
1706 assert( pParse->pNewTable==pTab );
1707 pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
1708 if( pPk==0 ) return;
drh48dd1d82014-05-27 18:18:58 +00001709 pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
drh7f9c5db2013-10-23 00:32:58 +00001710 pTab->iPKey = -1;
drh44156282013-10-23 22:23:03 +00001711 }else{
1712 pPk = sqlite3PrimaryKeyIndex(pTab);
drhe385d882014-12-28 22:10:51 +00001713 /*
1714 ** Remove all redundant columns from the PRIMARY KEY. For example, change
1715 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
1716 ** code assumes the PRIMARY KEY contains no repeated columns.
1717 */
1718 for(i=j=1; i<pPk->nKeyCol; i++){
1719 if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
1720 pPk->nColumn--;
1721 }else{
1722 pPk->aiColumn[j++] = pPk->aiColumn[i];
1723 }
1724 }
1725 pPk->nKeyCol = j;
drh7f9c5db2013-10-23 00:32:58 +00001726 }
drh12826092013-11-05 22:39:17 +00001727 pPk->isCovering = 1;
drh7f9c5db2013-10-23 00:32:58 +00001728 assert( pPk!=0 );
1729 nPk = pPk->nKeyCol;
1730
drh1ffede82015-01-30 20:59:27 +00001731 /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
1732 ** do not enforce this for imposter tables.) */
1733 if( !db->init.imposterTable ){
1734 for(i=0; i<nPk; i++){
1735 pTab->aCol[pPk->aiColumn[i]].notNull = 1;
1736 }
1737 pPk->uniqNotNull = 1;
drhec95c442013-10-23 01:57:32 +00001738 }
1739
drhc6bd4e42013-11-02 14:37:18 +00001740 /* The root page of the PRIMARY KEY is the table root page */
1741 pPk->tnum = pTab->tnum;
1742
drh7f9c5db2013-10-23 00:32:58 +00001743 /* Update the in-memory representation of all UNIQUE indices by converting
1744 ** the final rowid column into one or more columns of the PRIMARY KEY.
1745 */
1746 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1747 int n;
drh48dd1d82014-05-27 18:18:58 +00001748 if( IsPrimaryKeyIndex(pIdx) ) continue;
drh7f9c5db2013-10-23 00:32:58 +00001749 for(i=n=0; i<nPk; i++){
1750 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
1751 }
drh5a9a37b2013-11-05 17:30:04 +00001752 if( n==0 ){
1753 /* This index is a superset of the primary key */
1754 pIdx->nColumn = pIdx->nKeyCol;
1755 continue;
1756 }
drh7f9c5db2013-10-23 00:32:58 +00001757 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
1758 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
drh7913e412013-11-01 20:30:36 +00001759 if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
drh7f9c5db2013-10-23 00:32:58 +00001760 pIdx->aiColumn[j] = pPk->aiColumn[i];
1761 pIdx->azColl[j] = pPk->azColl[i];
1762 j++;
1763 }
1764 }
drh00012df2013-11-05 01:59:07 +00001765 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
1766 assert( pIdx->nColumn>=j );
drh7f9c5db2013-10-23 00:32:58 +00001767 }
1768
1769 /* Add all table columns to the PRIMARY KEY index
1770 */
1771 if( nPk<pTab->nCol ){
1772 if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
1773 for(i=0, j=nPk; i<pTab->nCol; i++){
1774 if( !hasColumn(pPk->aiColumn, j, i) ){
1775 assert( j<pPk->nColumn );
1776 pPk->aiColumn[j] = i;
1777 pPk->azColl[j] = "BINARY";
1778 j++;
1779 }
1780 }
1781 assert( pPk->nColumn==j );
1782 assert( pTab->nCol==j );
drhc3e356f2013-11-04 18:34:46 +00001783 }else{
1784 pPk->nColumn = pTab->nCol;
drh7f9c5db2013-10-23 00:32:58 +00001785 }
1786}
1787
drhfdaac672013-10-04 15:30:21 +00001788/*
drh75897232000-05-29 14:26:00 +00001789** This routine is called to report the final ")" that terminates
1790** a CREATE TABLE statement.
1791**
drhf57b3392001-10-08 13:22:32 +00001792** The table structure that other action routines have been building
1793** is added to the internal hash tables, assuming no errors have
1794** occurred.
drh75897232000-05-29 14:26:00 +00001795**
drh1d85d932004-02-14 23:05:52 +00001796** An entry for the table is made in the master table on disk, unless
1797** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001798** it means we are reading the sqlite_master table because we just
1799** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001800** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001801** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001802**
1803** If the pSelect argument is not NULL, it means that this routine
1804** was called to create a table generated from a
1805** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1806** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001807*/
danielk197719a8e7e2005-03-17 05:03:38 +00001808void sqlite3EndTable(
1809 Parse *pParse, /* Parse context */
1810 Token *pCons, /* The ',' token after the last column defn. */
drh5969da42013-10-21 02:14:45 +00001811 Token *pEnd, /* The ')' before options in the CREATE TABLE */
1812 u8 tabOpts, /* Extra table options. Usually 0. */
danielk197719a8e7e2005-03-17 05:03:38 +00001813 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1814){
drhfdaac672013-10-04 15:30:21 +00001815 Table *p; /* The new table */
1816 sqlite3 *db = pParse->db; /* The database connection */
1817 int iDb; /* Database in which the table lives */
1818 Index *pIdx; /* An implied index of the table */
drh75897232000-05-29 14:26:00 +00001819
drh5969da42013-10-21 02:14:45 +00001820 if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
1821 return;
danielk1977261919c2005-12-06 12:52:59 +00001822 }
drh28037572000-08-02 13:47:41 +00001823 p = pParse->pNewTable;
drh5969da42013-10-21 02:14:45 +00001824 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001825
danielk1977517eb642004-06-07 10:00:31 +00001826 assert( !db->init.busy || !pSelect );
1827
drhc6bd4e42013-11-02 14:37:18 +00001828 /* If the db->init.busy is 1 it means we are reading the SQL off the
1829 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1830 ** So do not write to the disk again. Extract the root page number
1831 ** for the table from the db->init.newTnum field. (The page number
1832 ** should have been put there by the sqliteOpenCb routine.)
1833 */
1834 if( db->init.busy ){
1835 p->tnum = db->init.newTnum;
1836 }
1837
1838 /* Special processing for WITHOUT ROWID Tables */
drh5969da42013-10-21 02:14:45 +00001839 if( tabOpts & TF_WithoutRowid ){
drhd2fe3352013-11-09 18:15:35 +00001840 if( (p->tabFlags & TF_Autoincrement) ){
1841 sqlite3ErrorMsg(pParse,
1842 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
1843 return;
1844 }
drh5969da42013-10-21 02:14:45 +00001845 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
drhd2fe3352013-11-09 18:15:35 +00001846 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
drh7f9c5db2013-10-23 00:32:58 +00001847 }else{
1848 p->tabFlags |= TF_WithoutRowid;
1849 convertToWithoutRowidTable(pParse, p);
drh81eba732013-10-19 23:31:56 +00001850 }
1851 }
1852
drhb9bb7c12006-06-11 23:41:55 +00001853 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001854
drhffe07b22005-11-03 00:41:17 +00001855#ifndef SQLITE_OMIT_CHECK
1856 /* Resolve names in all CHECK constraint expressions.
1857 */
1858 if( p->pCheck ){
drh3780be12013-07-31 19:05:22 +00001859 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
drhffe07b22005-11-03 00:41:17 +00001860 }
1861#endif /* !defined(SQLITE_OMIT_CHECK) */
1862
drhe13e9f52013-10-05 19:18:00 +00001863 /* Estimate the average row size for the table and for all implied indices */
1864 estimateTableWidth(p);
drhfdaac672013-10-04 15:30:21 +00001865 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
drhe13e9f52013-10-05 19:18:00 +00001866 estimateIndexWidth(pIdx);
drhfdaac672013-10-04 15:30:21 +00001867 }
1868
drhe3c41372001-09-17 20:25:58 +00001869 /* If not initializing, then create a record for the new table
drh0fa991b2009-03-21 16:19:26 +00001870 ** in the SQLITE_MASTER table of the database.
drhf57b3392001-10-08 13:22:32 +00001871 **
drhe0bc4042002-06-25 01:09:11 +00001872 ** If this is a TEMPORARY table, write the entry into the auxiliary
1873 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001874 */
drh1d85d932004-02-14 23:05:52 +00001875 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001876 int n;
drhd8bc7082000-06-07 23:51:50 +00001877 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001878 char *zType; /* "view" or "table" */
1879 char *zType2; /* "VIEW" or "TABLE" */
1880 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001881
danielk19774adee202004-05-08 08:23:19 +00001882 v = sqlite3GetVdbe(pParse);
drh5969da42013-10-21 02:14:45 +00001883 if( NEVER(v==0) ) return;
danielk1977517eb642004-06-07 10:00:31 +00001884
drh66a51672008-01-03 00:01:23 +00001885 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001886
drh0fa991b2009-03-21 16:19:26 +00001887 /*
1888 ** Initialize zType for the new view or table.
drh4794f732004-11-05 17:17:50 +00001889 */
drh4ff6dfa2002-03-03 23:06:00 +00001890 if( p->pSelect==0 ){
1891 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001892 zType = "table";
1893 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001894#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001895 }else{
1896 /* A view */
drh4794f732004-11-05 17:17:50 +00001897 zType = "view";
1898 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001899#endif
drh4ff6dfa2002-03-03 23:06:00 +00001900 }
danielk1977517eb642004-06-07 10:00:31 +00001901
danielk1977517eb642004-06-07 10:00:31 +00001902 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1903 ** statement to populate the new table. The root-page number for the
drh0fa991b2009-03-21 16:19:26 +00001904 ** new table is in register pParse->regRoot.
danielk1977517eb642004-06-07 10:00:31 +00001905 **
1906 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1907 ** suitable state to query for the column names and types to be used
1908 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001909 **
1910 ** A shared-cache write-lock is not required to write to the new table,
1911 ** as a schema-lock must have already been obtained to create it. Since
1912 ** a schema-lock excludes all other database users, the write-lock would
1913 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001914 */
1915 if( pSelect ){
drh92632202015-05-20 17:18:29 +00001916 SelectDest dest; /* Where the SELECT should store results */
drh9df25c42015-05-20 15:51:09 +00001917 int regYield; /* Register holding co-routine entry-point */
1918 int addrTop; /* Top of the co-routine */
drh92632202015-05-20 17:18:29 +00001919 int regRec; /* A record to be insert into the new table */
1920 int regRowid; /* Rowid of the next row to insert */
1921 int addrInsLoop; /* Top of the loop for inserting rows */
1922 Table *pSelTab; /* A table that describes the SELECT results */
drh1013c932008-01-06 00:25:21 +00001923
drh9df25c42015-05-20 15:51:09 +00001924 regYield = ++pParse->nMem;
drh92632202015-05-20 17:18:29 +00001925 regRec = ++pParse->nMem;
1926 regRowid = ++pParse->nMem;
danielk19776ab3a2e2009-02-19 14:39:25 +00001927 assert(pParse->nTab==1);
drhb7654112008-01-12 12:48:07 +00001928 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
dan428c2182012-08-06 18:50:11 +00001929 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
danielk1977517eb642004-06-07 10:00:31 +00001930 pParse->nTab = 2;
drh9df25c42015-05-20 15:51:09 +00001931 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
1932 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
1933 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
drh7d10d5a2008-08-20 16:35:10 +00001934 sqlite3Select(pParse, pSelect, &dest);
drh9df25c42015-05-20 15:51:09 +00001935 sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
1936 sqlite3VdbeJumpHere(v, addrTop - 1);
drh92632202015-05-20 17:18:29 +00001937 if( pParse->nErr ) return;
1938 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
1939 if( pSelTab==0 ) return;
1940 assert( p->aCol==0 );
1941 p->nCol = pSelTab->nCol;
1942 p->aCol = pSelTab->aCol;
1943 pSelTab->nCol = 0;
1944 pSelTab->aCol = 0;
1945 sqlite3DeleteTable(db, pSelTab);
1946 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
1947 VdbeCoverage(v);
1948 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
1949 sqlite3TableAffinity(v, p, 0);
1950 sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
1951 sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
1952 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrInsLoop);
1953 sqlite3VdbeJumpHere(v, addrInsLoop);
1954 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001955 }
drh4794f732004-11-05 17:17:50 +00001956
drh4794f732004-11-05 17:17:50 +00001957 /* Compute the complete text of the CREATE statement */
1958 if( pSelect ){
drh1d34fde2009-02-03 15:50:33 +00001959 zStmt = createTableStmt(db, p);
drh4794f732004-11-05 17:17:50 +00001960 }else{
drh8ea30bf2013-10-22 01:18:17 +00001961 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
1962 n = (int)(pEnd2->z - pParse->sNameToken.z);
1963 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
danielk19771e536952007-08-16 10:09:01 +00001964 zStmt = sqlite3MPrintf(db,
1965 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1966 );
drh4794f732004-11-05 17:17:50 +00001967 }
1968
1969 /* A slot for the record has already been allocated in the
1970 ** SQLITE_MASTER table. We just need to update that slot with all
drh0fa991b2009-03-21 16:19:26 +00001971 ** the information we've collected.
drh4794f732004-11-05 17:17:50 +00001972 */
1973 sqlite3NestedParse(pParse,
1974 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001975 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1976 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001977 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001978 zType,
1979 p->zName,
1980 p->zName,
drhb7654112008-01-12 12:48:07 +00001981 pParse->regRoot,
1982 zStmt,
1983 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001984 );
drh633e6d52008-07-28 19:34:53 +00001985 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001986 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001987
1988#ifndef SQLITE_OMIT_AUTOINCREMENT
1989 /* Check to see if we need to create an sqlite_sequence table for
1990 ** keeping track of autoincrement keys.
1991 */
drh7d10d5a2008-08-20 16:35:10 +00001992 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001993 Db *pDb = &db->aDb[iDb];
drh21206082011-04-04 18:22:02 +00001994 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001995 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001996 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001997 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1998 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001999 );
2000 }
2001 }
2002#endif
drh4794f732004-11-05 17:17:50 +00002003
2004 /* Reparse everything to update our internal data structures */
drh5d9c9da2011-06-03 20:11:17 +00002005 sqlite3VdbeAddParseSchemaOp(v, iDb,
dan197bc202013-10-19 15:07:49 +00002006 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
drh75897232000-05-29 14:26:00 +00002007 }
drh17e9e292003-02-01 13:53:28 +00002008
drh2958a4e2004-11-12 03:56:15 +00002009
drh17e9e292003-02-01 13:53:28 +00002010 /* Add the table to the in-memory representation of the database.
2011 */
drh8af73d42009-05-13 22:58:28 +00002012 if( db->init.busy ){
drh17e9e292003-02-01 13:53:28 +00002013 Table *pOld;
danielk1977e501b892006-01-09 06:29:47 +00002014 Schema *pSchema = p->pSchema;
drh21206082011-04-04 18:22:02 +00002015 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhacbcb7e2014-08-21 20:26:37 +00002016 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
drh17e9e292003-02-01 13:53:28 +00002017 if( pOld ){
2018 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00002019 db->mallocFailed = 1;
drh5969da42013-10-21 02:14:45 +00002020 return;
drh17e9e292003-02-01 13:53:28 +00002021 }
drh17e9e292003-02-01 13:53:28 +00002022 pParse->pNewTable = 0;
drh17e9e292003-02-01 13:53:28 +00002023 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00002024
2025#ifndef SQLITE_OMIT_ALTERTABLE
2026 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00002027 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00002028 int nName;
drh5969da42013-10-21 02:14:45 +00002029 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00002030 if( pCons->z==0 ){
drh5969da42013-10-21 02:14:45 +00002031 pCons = pEnd;
danielk1977bab45c62006-01-16 15:14:27 +00002032 }
drh1bd10f82008-12-10 21:19:56 +00002033 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00002034 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00002035 }
2036#endif
drh17e9e292003-02-01 13:53:28 +00002037 }
drh75897232000-05-29 14:26:00 +00002038}
2039
drhb7f91642004-10-31 02:22:47 +00002040#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00002041/*
drha76b5df2002-02-23 02:32:10 +00002042** The parser calls this routine in order to create a new VIEW
2043*/
danielk19774adee202004-05-08 08:23:19 +00002044void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00002045 Parse *pParse, /* The parsing context */
2046 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00002047 Token *pName1, /* The token that holds the name of the view */
2048 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00002049 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00002050 int isTemp, /* TRUE for a TEMPORARY view */
2051 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00002052){
drha76b5df2002-02-23 02:32:10 +00002053 Table *p;
drh4b59ab52002-08-24 18:24:51 +00002054 int n;
drhb7916a72009-05-27 10:31:29 +00002055 const char *z;
drh4b59ab52002-08-24 18:24:51 +00002056 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00002057 DbFixer sFix;
drh88caeac2011-08-24 15:12:08 +00002058 Token *pName = 0;
danielk1977da184232006-01-05 11:34:32 +00002059 int iDb;
drh17435752007-08-16 04:30:38 +00002060 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00002061
drh7c3d64f2005-06-06 15:32:08 +00002062 if( pParse->nVar>0 ){
2063 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00002064 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00002065 return;
2066 }
drhfdd48a72006-09-11 23:45:48 +00002067 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00002068 p = pParse->pNewTable;
drh50d1b5f2010-08-27 12:21:06 +00002069 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00002070 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00002071 return;
2072 }
danielk1977ef2cb632004-05-29 02:37:19 +00002073 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00002074 iDb = sqlite3SchemaToIndex(db, p->pSchema);
drhd100f692013-10-03 15:39:44 +00002075 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
2076 if( sqlite3FixSelect(&sFix, pSelect) ){
drh633e6d52008-07-28 19:34:53 +00002077 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00002078 return;
2079 }
drh174b6192002-12-03 02:22:52 +00002080
drh4b59ab52002-08-24 18:24:51 +00002081 /* Make a copy of the entire SELECT statement that defines the view.
2082 ** This will force all the Expr.token.z values to be dynamically
2083 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00002084 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00002085 */
danielk19776ab3a2e2009-02-19 14:39:25 +00002086 p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
drh633e6d52008-07-28 19:34:53 +00002087 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00002088 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00002089 return;
2090 }
drh17435752007-08-16 04:30:38 +00002091 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00002092 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00002093 }
drh4b59ab52002-08-24 18:24:51 +00002094
2095 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
2096 ** the end.
2097 */
drha76b5df2002-02-23 02:32:10 +00002098 sEnd = pParse->sLastToken;
drh768578e2009-05-12 00:40:12 +00002099 if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
drha76b5df2002-02-23 02:32:10 +00002100 sEnd.z += sEnd.n;
2101 }
2102 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00002103 n = (int)(sEnd.z - pBegin->z);
drhb7916a72009-05-27 10:31:29 +00002104 z = pBegin->z;
drh768578e2009-05-12 00:40:12 +00002105 while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00002106 sEnd.z = &z[n-1];
2107 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00002108
danielk19774adee202004-05-08 08:23:19 +00002109 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
drh5969da42013-10-21 02:14:45 +00002110 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
drha76b5df2002-02-23 02:32:10 +00002111 return;
drh417be792002-03-03 18:59:40 +00002112}
drhb7f91642004-10-31 02:22:47 +00002113#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002114
danielk1977fe3fcbe22006-06-12 12:08:45 +00002115#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00002116/*
2117** The Table structure pTable is really a VIEW. Fill in the names of
2118** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00002119** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00002120*/
danielk19774adee202004-05-08 08:23:19 +00002121int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00002122 Table *pSelTab; /* A fake table from which we get the result set */
2123 Select *pSel; /* Copy of the SELECT that implements the view */
2124 int nErr = 0; /* Number of errors encountered */
2125 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00002126 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drh32c6a482014-09-11 13:44:52 +00002127 sqlite3_xauth xAuth; /* Saved xAuth pointer */
drh417be792002-03-03 18:59:40 +00002128
2129 assert( pTable );
2130
danielk1977fe3fcbe22006-06-12 12:08:45 +00002131#ifndef SQLITE_OMIT_VIRTUALTABLE
2132 if( sqlite3VtabCallConnect(pParse, pTable) ){
2133 return SQLITE_ERROR;
2134 }
drh4cbdda92006-06-14 19:00:20 +00002135 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002136#endif
2137
2138#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002139 /* A positive nCol means the columns names for this view are
2140 ** already known.
2141 */
2142 if( pTable->nCol>0 ) return 0;
2143
2144 /* A negative nCol is a special marker meaning that we are currently
2145 ** trying to compute the column names. If we enter this routine with
2146 ** a negative nCol, it means two or more views form a loop, like this:
2147 **
2148 ** CREATE VIEW one AS SELECT * FROM two;
2149 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00002150 **
drh768578e2009-05-12 00:40:12 +00002151 ** Actually, the error above is now caught prior to reaching this point.
2152 ** But the following test is still important as it does come up
2153 ** in the following:
2154 **
2155 ** CREATE TABLE main.ex1(a);
2156 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
2157 ** SELECT * FROM temp.ex1;
drh417be792002-03-03 18:59:40 +00002158 */
2159 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00002160 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00002161 return 1;
2162 }
drh85c23c62005-08-20 03:03:04 +00002163 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00002164
2165 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00002166 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
2167 ** "*" elements in the results set of the view and will assign cursors
2168 ** to the elements of the FROM clause. But we do not want these changes
2169 ** to be permanent. So the computation is done on a copy of the SELECT
2170 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00002171 */
drh9b3187e2005-01-18 14:45:47 +00002172 assert( pTable->pSelect );
danielk19776ab3a2e2009-02-19 14:39:25 +00002173 pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
danielk1977261919c2005-12-06 12:52:59 +00002174 if( pSel ){
shaneb08a67a2009-03-31 03:41:56 +00002175 u8 enableLookaside = db->lookaside.bEnabled;
danielk1977261919c2005-12-06 12:52:59 +00002176 n = pParse->nTab;
2177 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
2178 pTable->nCol = -1;
drhd9da78a2009-03-24 15:08:09 +00002179 db->lookaside.bEnabled = 0;
danielk1977db2d2862007-10-15 07:08:44 +00002180#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00002181 xAuth = db->xAuth;
2182 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00002183 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00002184 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00002185#else
drh7d10d5a2008-08-20 16:35:10 +00002186 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00002187#endif
drhd9da78a2009-03-24 15:08:09 +00002188 db->lookaside.bEnabled = enableLookaside;
danielk1977261919c2005-12-06 12:52:59 +00002189 pParse->nTab = n;
2190 if( pSelTab ){
2191 assert( pTable->aCol==0 );
2192 pTable->nCol = pSelTab->nCol;
2193 pTable->aCol = pSelTab->aCol;
2194 pSelTab->nCol = 0;
2195 pSelTab->aCol = 0;
dan1feeaed2010-07-23 15:41:47 +00002196 sqlite3DeleteTable(db, pSelTab);
drh21206082011-04-04 18:22:02 +00002197 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
drh2c5e35f2014-08-05 11:04:21 +00002198 pTable->pSchema->schemaFlags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00002199 }else{
2200 pTable->nCol = 0;
2201 nErr++;
2202 }
drh633e6d52008-07-28 19:34:53 +00002203 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00002204 } else {
drh417be792002-03-03 18:59:40 +00002205 nErr++;
2206 }
drhb7f91642004-10-31 02:22:47 +00002207#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00002208 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00002209}
2210#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00002211
drhb7f91642004-10-31 02:22:47 +00002212#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00002213/*
drh8bf8dc92003-05-17 17:35:10 +00002214** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00002215*/
drh9bb575f2004-09-06 17:24:11 +00002216static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00002217 HashElem *i;
drh21206082011-04-04 18:22:02 +00002218 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
drh8bf8dc92003-05-17 17:35:10 +00002219 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00002220 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00002221 Table *pTab = sqliteHashData(i);
2222 if( pTab->pSelect ){
dand46def72010-07-24 11:28:28 +00002223 sqliteDeleteColumnNames(db, pTab);
2224 pTab->aCol = 0;
2225 pTab->nCol = 0;
drh417be792002-03-03 18:59:40 +00002226 }
2227 }
drh8bf8dc92003-05-17 17:35:10 +00002228 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00002229}
drhb7f91642004-10-31 02:22:47 +00002230#else
2231# define sqliteViewResetAll(A,B)
2232#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00002233
drh75897232000-05-29 14:26:00 +00002234/*
danielk1977a0bf2652004-11-04 14:30:04 +00002235** This function is called by the VDBE to adjust the internal schema
2236** used by SQLite when the btree layer moves a table root page. The
2237** root-page of a table or index in database iDb has changed from iFrom
2238** to iTo.
drh6205d4a2006-03-24 03:36:26 +00002239**
2240** Ticket #1728: The symbol table might still contain information
2241** on tables and/or indices that are the process of being deleted.
2242** If you are unlucky, one of those deleted indices or tables might
2243** have the same rootpage number as the real table or index that is
2244** being moved. So we cannot stop searching after the first match
2245** because the first match might be for one of the deleted indices
2246** or tables and not the table/index that is actually being moved.
2247** We must continue looping until all tables and indices with
2248** rootpage==iFrom have been converted to have a rootpage of iTo
2249** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00002250*/
2251#ifndef SQLITE_OMIT_AUTOVACUUM
drhcdf011d2011-04-04 21:25:28 +00002252void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
danielk1977a0bf2652004-11-04 14:30:04 +00002253 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00002254 Hash *pHash;
drhcdf011d2011-04-04 21:25:28 +00002255 Db *pDb;
danielk1977da184232006-01-05 11:34:32 +00002256
drhcdf011d2011-04-04 21:25:28 +00002257 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2258 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +00002259 pHash = &pDb->pSchema->tblHash;
2260 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002261 Table *pTab = sqliteHashData(pElem);
2262 if( pTab->tnum==iFrom ){
2263 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002264 }
2265 }
danielk1977da184232006-01-05 11:34:32 +00002266 pHash = &pDb->pSchema->idxHash;
2267 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00002268 Index *pIdx = sqliteHashData(pElem);
2269 if( pIdx->tnum==iFrom ){
2270 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00002271 }
2272 }
danielk1977a0bf2652004-11-04 14:30:04 +00002273}
2274#endif
2275
2276/*
2277** Write code to erase the table with root-page iTable from database iDb.
2278** Also write code to modify the sqlite_master table and internal schema
2279** if a root-page of another table is moved by the btree-layer whilst
2280** erasing iTable (this can happen with an auto-vacuum database).
2281*/
drh4e0cff62004-11-05 05:10:28 +00002282static void destroyRootPage(Parse *pParse, int iTable, int iDb){
2283 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00002284 int r1 = sqlite3GetTempReg(pParse);
2285 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
dane0af83a2009-09-08 19:15:01 +00002286 sqlite3MayAbort(pParse);
drh40e016e2004-11-04 14:47:11 +00002287#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00002288 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00002289 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00002290 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00002291 ** reflect this.
2292 **
drh0fa991b2009-03-21 16:19:26 +00002293 ** The "#NNN" in the SQL is a special constant that means whatever value
drhb74b1012009-05-28 21:04:37 +00002294 ** is in register NNN. See grammar rules associated with the TK_REGISTER
2295 ** token for additional information.
drh4e0cff62004-11-05 05:10:28 +00002296 */
danielk197763e3e9f2004-11-05 09:19:27 +00002297 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002298 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
2299 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002300#endif
drhb7654112008-01-12 12:48:07 +00002301 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00002302}
2303
2304/*
2305** Write VDBE code to erase table pTab and all associated indices on disk.
2306** Code to update the sqlite_master tables and internal schema definitions
2307** in case a root-page belonging to another table is moved by the btree layer
2308** is also added (this can happen with an auto-vacuum database).
2309*/
drh4e0cff62004-11-05 05:10:28 +00002310static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00002311#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00002312 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00002313 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
2314 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002315 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00002316 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00002317 }
2318#else
2319 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
2320 ** is not defined), then it is important to call OP_Destroy on the
2321 ** table and index root-pages in order, starting with the numerically
2322 ** largest root-page number. This guarantees that none of the root-pages
2323 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
2324 ** following were coded:
2325 **
2326 ** OP_Destroy 4 0
2327 ** ...
2328 ** OP_Destroy 5 0
2329 **
2330 ** and root page 5 happened to be the largest root-page number in the
2331 ** database, then root page 5 would be moved to page 4 by the
2332 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
2333 ** a free-list page.
2334 */
2335 int iTab = pTab->tnum;
2336 int iDestroyed = 0;
2337
2338 while( 1 ){
2339 Index *pIdx;
2340 int iLargest = 0;
2341
2342 if( iDestroyed==0 || iTab<iDestroyed ){
2343 iLargest = iTab;
2344 }
2345 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2346 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00002347 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00002348 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
2349 iLargest = iIdx;
2350 }
2351 }
danielk1977da184232006-01-05 11:34:32 +00002352 if( iLargest==0 ){
2353 return;
2354 }else{
2355 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh5a05be12012-10-09 18:51:44 +00002356 assert( iDb>=0 && iDb<pParse->db->nDb );
danielk1977da184232006-01-05 11:34:32 +00002357 destroyRootPage(pParse, iLargest, iDb);
2358 iDestroyed = iLargest;
2359 }
danielk1977a0bf2652004-11-04 14:30:04 +00002360 }
2361#endif
2362}
2363
2364/*
drh74e7c8f2011-10-21 19:06:32 +00002365** Remove entries from the sqlite_statN tables (for N in (1,2,3))
drha5ae4c32011-08-07 01:31:52 +00002366** after a DROP INDEX or DROP TABLE command.
2367*/
2368static void sqlite3ClearStatTables(
2369 Parse *pParse, /* The parsing context */
2370 int iDb, /* The database number */
2371 const char *zType, /* "idx" or "tbl" */
2372 const char *zName /* Name of index or table */
2373){
drha5ae4c32011-08-07 01:31:52 +00002374 int i;
2375 const char *zDbName = pParse->db->aDb[iDb].zName;
danf52bb8d2013-08-03 20:24:58 +00002376 for(i=1; i<=4; i++){
drh74e7c8f2011-10-21 19:06:32 +00002377 char zTab[24];
2378 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
2379 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
drha5ae4c32011-08-07 01:31:52 +00002380 sqlite3NestedParse(pParse,
2381 "DELETE FROM %Q.%s WHERE %s=%Q",
drh74e7c8f2011-10-21 19:06:32 +00002382 zDbName, zTab, zType, zName
drha5ae4c32011-08-07 01:31:52 +00002383 );
2384 }
2385 }
2386}
2387
2388/*
drhfaacf172011-08-12 01:51:45 +00002389** Generate code to drop a table.
2390*/
2391void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
2392 Vdbe *v;
2393 sqlite3 *db = pParse->db;
2394 Trigger *pTrigger;
2395 Db *pDb = &db->aDb[iDb];
2396
2397 v = sqlite3GetVdbe(pParse);
2398 assert( v!=0 );
2399 sqlite3BeginWriteOperation(pParse, 1, iDb);
2400
2401#ifndef SQLITE_OMIT_VIRTUALTABLE
2402 if( IsVirtual(pTab) ){
2403 sqlite3VdbeAddOp0(v, OP_VBegin);
2404 }
2405#endif
2406
2407 /* Drop all triggers associated with the table being dropped. Code
2408 ** is generated to remove entries from sqlite_master and/or
2409 ** sqlite_temp_master if required.
2410 */
2411 pTrigger = sqlite3TriggerList(pParse, pTab);
2412 while( pTrigger ){
2413 assert( pTrigger->pSchema==pTab->pSchema ||
2414 pTrigger->pSchema==db->aDb[1].pSchema );
2415 sqlite3DropTriggerPtr(pParse, pTrigger);
2416 pTrigger = pTrigger->pNext;
2417 }
2418
2419#ifndef SQLITE_OMIT_AUTOINCREMENT
2420 /* Remove any entries of the sqlite_sequence table associated with
2421 ** the table being dropped. This is done before the table is dropped
2422 ** at the btree level, in case the sqlite_sequence table needs to
2423 ** move as a result of the drop (can happen in auto-vacuum mode).
2424 */
2425 if( pTab->tabFlags & TF_Autoincrement ){
2426 sqlite3NestedParse(pParse,
2427 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
2428 pDb->zName, pTab->zName
2429 );
2430 }
2431#endif
2432
2433 /* Drop all SQLITE_MASTER table and index entries that refer to the
2434 ** table. The program name loops through the master table and deletes
2435 ** every row that refers to a table of the same name as the one being
mistachkin48864df2013-03-21 21:20:32 +00002436 ** dropped. Triggers are handled separately because a trigger can be
drhfaacf172011-08-12 01:51:45 +00002437 ** created in the temp database that refers to a table in another
2438 ** database.
2439 */
2440 sqlite3NestedParse(pParse,
2441 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
2442 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drhfaacf172011-08-12 01:51:45 +00002443 if( !isView && !IsVirtual(pTab) ){
2444 destroyTable(pParse, pTab);
2445 }
2446
2447 /* Remove the table entry from SQLite's internal schema and modify
2448 ** the schema cookie.
2449 */
2450 if( IsVirtual(pTab) ){
2451 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
2452 }
2453 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
2454 sqlite3ChangeCookie(pParse, iDb);
2455 sqliteViewResetAll(db, iDb);
drhfaacf172011-08-12 01:51:45 +00002456}
2457
2458/*
drh75897232000-05-29 14:26:00 +00002459** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00002460** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00002461*/
drha0733842005-12-29 01:11:36 +00002462void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00002463 Table *pTab;
drh75897232000-05-29 14:26:00 +00002464 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002465 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00002466 int iDb;
drh75897232000-05-29 14:26:00 +00002467
drh8af73d42009-05-13 22:58:28 +00002468 if( db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00002469 goto exit_drop_table;
2470 }
drh8af73d42009-05-13 22:58:28 +00002471 assert( pParse->nErr==0 );
danielk1977a8858102004-05-28 12:11:21 +00002472 assert( pName->nSrc==1 );
drh75209962015-04-19 22:31:45 +00002473 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
drha7564662010-02-22 19:32:31 +00002474 if( noErr ) db->suppressErr++;
dan41fb5cd2012-10-04 19:33:00 +00002475 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
drha7564662010-02-22 19:32:31 +00002476 if( noErr ) db->suppressErr--;
danielk1977a8858102004-05-28 12:11:21 +00002477
drha0733842005-12-29 01:11:36 +00002478 if( pTab==0 ){
dan57966752011-04-09 17:32:58 +00002479 if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drha0733842005-12-29 01:11:36 +00002480 goto exit_drop_table;
2481 }
danielk1977da184232006-01-05 11:34:32 +00002482 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00002483 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00002484
2485 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
2486 ** it is initialized.
2487 */
2488 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
2489 goto exit_drop_table;
2490 }
drhe5f9c642003-01-13 23:27:31 +00002491#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00002492 {
2493 int code;
danielk1977da184232006-01-05 11:34:32 +00002494 const char *zTab = SCHEMA_TABLE(iDb);
2495 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00002496 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00002497 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00002498 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00002499 }
drhe5f9c642003-01-13 23:27:31 +00002500 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00002501 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002502 code = SQLITE_DROP_TEMP_VIEW;
2503 }else{
2504 code = SQLITE_DROP_VIEW;
2505 }
danielk19774b2688a2006-06-20 11:01:07 +00002506#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002507 }else if( IsVirtual(pTab) ){
2508 code = SQLITE_DROP_VTABLE;
danielk1977595a5232009-07-24 17:58:53 +00002509 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002510#endif
drhe5f9c642003-01-13 23:27:31 +00002511 }else{
danielk197753c0f742005-03-29 03:10:59 +00002512 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002513 code = SQLITE_DROP_TEMP_TABLE;
2514 }else{
2515 code = SQLITE_DROP_TABLE;
2516 }
2517 }
danielk1977f1a381e2006-06-16 08:01:02 +00002518 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002519 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002520 }
danielk1977a8858102004-05-28 12:11:21 +00002521 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2522 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002523 }
drhe5f9c642003-01-13 23:27:31 +00002524 }
2525#endif
drh08ccfaa2011-10-07 23:52:25 +00002526 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
2527 && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
danielk1977a8858102004-05-28 12:11:21 +00002528 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002529 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002530 }
danielk1977576ec6b2005-01-21 11:55:25 +00002531
2532#ifndef SQLITE_OMIT_VIEW
2533 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2534 ** on a table.
2535 */
danielk1977a8858102004-05-28 12:11:21 +00002536 if( isView && pTab->pSelect==0 ){
2537 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2538 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002539 }
danielk1977a8858102004-05-28 12:11:21 +00002540 if( !isView && pTab->pSelect ){
2541 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2542 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002543 }
danielk1977576ec6b2005-01-21 11:55:25 +00002544#endif
drh75897232000-05-29 14:26:00 +00002545
drh1ccde152000-06-17 13:12:39 +00002546 /* Generate code to remove the table from the master table
2547 ** on disk.
2548 */
danielk19774adee202004-05-08 08:23:19 +00002549 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002550 if( v ){
drh77658e22007-12-04 16:54:52 +00002551 sqlite3BeginWriteOperation(pParse, 1, iDb);
drha5ae4c32011-08-07 01:31:52 +00002552 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
drhe0bc4042002-06-25 01:09:11 +00002553 sqlite3FkDropTable(pParse, pName, pTab);
drhfaacf172011-08-12 01:51:45 +00002554 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
drh75897232000-05-29 14:26:00 +00002555 }
danielk1977a8858102004-05-28 12:11:21 +00002556
2557exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002558 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002559}
2560
2561/*
drhc2eef3b2002-08-31 18:53:06 +00002562** This routine is called to create a new foreign key on the table
2563** currently under construction. pFromCol determines which columns
2564** in the current table point to the foreign key. If pFromCol==0 then
2565** connect the key to the last column inserted. pTo is the name of
drhbd50a922013-11-03 02:27:58 +00002566** the table referred to (a.k.a the "parent" table). pToCol is a list
2567** of tables in the parent pTo table. flags contains all
drhc2eef3b2002-08-31 18:53:06 +00002568** information about the conflict resolution algorithms specified
2569** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2570**
2571** An FKey structure is created and added to the table currently
drhe61922a2009-05-02 13:29:37 +00002572** under construction in the pParse->pNewTable field.
drhc2eef3b2002-08-31 18:53:06 +00002573**
2574** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002575** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002576*/
danielk19774adee202004-05-08 08:23:19 +00002577void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002578 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002579 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002580 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002581 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002582 int flags /* Conflict resolution algorithms. */
2583){
danielk197718576932008-08-06 13:47:40 +00002584 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002585#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002586 FKey *pFKey = 0;
dan1da40a32009-09-19 17:00:31 +00002587 FKey *pNextTo;
drhc2eef3b2002-08-31 18:53:06 +00002588 Table *p = pParse->pNewTable;
2589 int nByte;
2590 int i;
2591 int nCol;
2592 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002593
2594 assert( pTo!=0 );
drh8af73d42009-05-13 22:58:28 +00002595 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002596 if( pFromCol==0 ){
2597 int iCol = p->nCol-1;
drhd3001712009-05-12 17:46:53 +00002598 if( NEVER(iCol<0) ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002599 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002600 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002601 " should reference only one column of table %T",
2602 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002603 goto fk_end;
2604 }
2605 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002606 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002607 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002608 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002609 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002610 goto fk_end;
2611 }else{
danielk19770202b292004-06-09 09:55:16 +00002612 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002613 }
drhe61922a2009-05-02 13:29:37 +00002614 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
drhc2eef3b2002-08-31 18:53:06 +00002615 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002616 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002617 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002618 }
2619 }
drh633e6d52008-07-28 19:34:53 +00002620 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002621 if( pFKey==0 ){
2622 goto fk_end;
2623 }
drhc2eef3b2002-08-31 18:53:06 +00002624 pFKey->pFrom = p;
2625 pFKey->pNextFrom = p->pFKey;
drhe61922a2009-05-02 13:29:37 +00002626 z = (char*)&pFKey->aCol[nCol];
drhdf68f6b2002-09-21 15:57:57 +00002627 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002628 memcpy(z, pTo->z, pTo->n);
2629 z[pTo->n] = 0;
danielk197770d9e9c2009-04-24 18:06:09 +00002630 sqlite3Dequote(z);
drhc2eef3b2002-08-31 18:53:06 +00002631 z += pTo->n+1;
drhc2eef3b2002-08-31 18:53:06 +00002632 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002633 if( pFromCol==0 ){
2634 pFKey->aCol[0].iFrom = p->nCol-1;
2635 }else{
2636 for(i=0; i<nCol; i++){
2637 int j;
2638 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002639 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002640 pFKey->aCol[i].iFrom = j;
2641 break;
2642 }
2643 }
2644 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002645 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002646 "unknown column \"%s\" in foreign key definition",
2647 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002648 goto fk_end;
2649 }
2650 }
2651 }
2652 if( pToCol ){
2653 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002654 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002655 pFKey->aCol[i].zCol = z;
2656 memcpy(z, pToCol->a[i].zName, n);
2657 z[n] = 0;
2658 z += n+1;
2659 }
2660 }
2661 pFKey->isDeferred = 0;
dan8099ce62009-09-23 08:43:35 +00002662 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
2663 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
drhc2eef3b2002-08-31 18:53:06 +00002664
drh21206082011-04-04 18:22:02 +00002665 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
dan1da40a32009-09-19 17:00:31 +00002666 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
drhacbcb7e2014-08-21 20:26:37 +00002667 pFKey->zTo, (void *)pFKey
dan1da40a32009-09-19 17:00:31 +00002668 );
danf59c5ca2009-09-22 16:55:38 +00002669 if( pNextTo==pFKey ){
2670 db->mallocFailed = 1;
2671 goto fk_end;
2672 }
dan1da40a32009-09-19 17:00:31 +00002673 if( pNextTo ){
2674 assert( pNextTo->pPrevTo==0 );
2675 pFKey->pNextTo = pNextTo;
2676 pNextTo->pPrevTo = pFKey;
2677 }
2678
drhc2eef3b2002-08-31 18:53:06 +00002679 /* Link the foreign key to the table as the last step.
2680 */
2681 p->pFKey = pFKey;
2682 pFKey = 0;
2683
2684fk_end:
drh633e6d52008-07-28 19:34:53 +00002685 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002686#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002687 sqlite3ExprListDelete(db, pFromCol);
2688 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002689}
2690
2691/*
2692** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2693** clause is seen as part of a foreign key definition. The isDeferred
2694** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2695** The behavior of the most recently created foreign key is adjusted
2696** accordingly.
2697*/
danielk19774adee202004-05-08 08:23:19 +00002698void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002699#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002700 Table *pTab;
2701 FKey *pFKey;
2702 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh4c429832009-10-12 22:30:49 +00002703 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
drh1bd10f82008-12-10 21:19:56 +00002704 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002705#endif
drhc2eef3b2002-08-31 18:53:06 +00002706}
2707
2708/*
drh063336a2004-11-05 20:58:39 +00002709** Generate code that will erase and refill index *pIdx. This is
2710** used to initialize a newly created index or to recompute the
2711** content of an index in response to a REINDEX command.
2712**
2713** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002714** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002715** root page number of the index. If memRootPage is negative, then
2716** the index already exists and must be cleared before being refilled and
2717** the root page number of the index is taken from pIndex->tnum.
2718*/
2719static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2720 Table *pTab = pIndex->pTable; /* The table that is indexed */
danielk19776ab3a2e2009-02-19 14:39:25 +00002721 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
2722 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
drhb07028f2011-10-14 21:49:18 +00002723 int iSorter; /* Cursor opened by OpenSorter (if in use) */
drh063336a2004-11-05 20:58:39 +00002724 int addr1; /* Address of top of loop */
dan5134d132011-09-02 10:31:11 +00002725 int addr2; /* Address to jump to for next iteration */
drh063336a2004-11-05 20:58:39 +00002726 int tnum; /* Root page of index */
drhb2b9d3d2013-08-01 01:14:43 +00002727 int iPartIdxLabel; /* Jump to this label to skip a row */
drh063336a2004-11-05 20:58:39 +00002728 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002729 KeyInfo *pKey; /* KeyInfo for index */
peter.d.reid60ec9142014-09-06 16:39:46 +00002730 int regRecord; /* Register holding assembled index record */
drh17435752007-08-16 04:30:38 +00002731 sqlite3 *db = pParse->db; /* The database connection */
2732 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002733
danielk19771d54df82004-11-23 15:41:16 +00002734#ifndef SQLITE_OMIT_AUTHORIZATION
2735 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002736 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002737 return;
2738 }
2739#endif
2740
danielk1977c00da102006-01-07 13:21:04 +00002741 /* Require a write-lock on the table to perform this operation */
2742 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2743
drh063336a2004-11-05 20:58:39 +00002744 v = sqlite3GetVdbe(pParse);
2745 if( v==0 ) return;
2746 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002747 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002748 }else{
2749 tnum = pIndex->tnum;
drh063336a2004-11-05 20:58:39 +00002750 }
drh2ec2fb22013-11-06 19:59:23 +00002751 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
dana20fde62011-07-12 14:28:05 +00002752
dan689ab892011-08-12 15:02:00 +00002753 /* Open the sorter cursor if we are to use one. */
drhca892a72011-09-03 00:17:51 +00002754 iSorter = pParse->nTab++;
danfad9f9a2014-04-01 18:41:51 +00002755 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
drh2ec2fb22013-11-06 19:59:23 +00002756 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
dana20fde62011-07-12 14:28:05 +00002757
2758 /* Open the table. Loop through all rows of the table, inserting index
2759 ** records into the sorter. */
drhdd9930e2013-10-23 23:37:02 +00002760 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh688852a2014-02-17 22:40:43 +00002761 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
drh2d401ab2008-01-10 23:50:11 +00002762 regRecord = sqlite3GetTempReg(pParse);
dana20fde62011-07-12 14:28:05 +00002763
drh1c2c0b72014-01-04 19:27:05 +00002764 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
drhca892a72011-09-03 00:17:51 +00002765 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
drh87744512014-04-13 19:15:49 +00002766 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
drh688852a2014-02-17 22:40:43 +00002767 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
drhca892a72011-09-03 00:17:51 +00002768 sqlite3VdbeJumpHere(v, addr1);
drh44156282013-10-23 22:23:03 +00002769 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
2770 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh2ec2fb22013-11-06 19:59:23 +00002771 (char *)pKey, P4_KEYINFO);
drh44156282013-10-23 22:23:03 +00002772 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
2773
drh688852a2014-02-17 22:40:43 +00002774 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
drh1153c7b2013-11-01 22:02:56 +00002775 assert( pKey!=0 || db->mallocFailed || pParse->nErr );
drh5f1d1d92014-07-31 22:59:04 +00002776 if( IsUniqueIndex(pIndex) && pKey!=0 ){
drhca892a72011-09-03 00:17:51 +00002777 int j2 = sqlite3VdbeCurrentAddr(v) + 3;
2778 sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
2779 addr2 = sqlite3VdbeCurrentAddr(v);
drh1153c7b2013-11-01 22:02:56 +00002780 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
drhac502322014-07-30 13:56:48 +00002781 pIndex->nKeyCol); VdbeCoverage(v);
drhf9c8ce32013-11-05 13:33:55 +00002782 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
drhca892a72011-09-03 00:17:51 +00002783 }else{
2784 addr2 = sqlite3VdbeCurrentAddr(v);
dan689ab892011-08-12 15:02:00 +00002785 }
drh6cf4a7d2014-10-13 13:00:58 +00002786 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
danb18e60b2015-04-01 16:18:00 +00002787 sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
2788 sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
drhca892a72011-09-03 00:17:51 +00002789 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
drh2d401ab2008-01-10 23:50:11 +00002790 sqlite3ReleaseTempReg(pParse, regRecord);
drh688852a2014-02-17 22:40:43 +00002791 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
drhd654be82005-09-20 17:42:23 +00002792 sqlite3VdbeJumpHere(v, addr1);
dana20fde62011-07-12 14:28:05 +00002793
drh66a51672008-01-03 00:01:23 +00002794 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2795 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
dan689ab892011-08-12 15:02:00 +00002796 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
drh063336a2004-11-05 20:58:39 +00002797}
2798
2799/*
drh77e57df2013-10-22 14:28:02 +00002800** Allocate heap space to hold an Index object with nCol columns.
2801**
2802** Increase the allocation size to provide an extra nExtra bytes
2803** of 8-byte aligned space after the Index object and return a
2804** pointer to this extra space in *ppExtra.
2805*/
2806Index *sqlite3AllocateIndexObject(
2807 sqlite3 *db, /* Database connection */
drhbbbdc832013-10-22 18:01:40 +00002808 i16 nCol, /* Total number of columns in the index */
drh77e57df2013-10-22 14:28:02 +00002809 int nExtra, /* Number of bytes of extra space to alloc */
2810 char **ppExtra /* Pointer to the "extra" space */
2811){
2812 Index *p; /* Allocated index object */
2813 int nByte; /* Bytes of space for Index object + arrays */
2814
2815 nByte = ROUND8(sizeof(Index)) + /* Index structure */
2816 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
dancfc9df72014-04-25 15:01:01 +00002817 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
drhbbbdc832013-10-22 18:01:40 +00002818 sizeof(i16)*nCol + /* Index.aiColumn */
drh77e57df2013-10-22 14:28:02 +00002819 sizeof(u8)*nCol); /* Index.aSortOrder */
2820 p = sqlite3DbMallocZero(db, nByte + nExtra);
2821 if( p ){
2822 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
dancfc9df72014-04-25 15:01:01 +00002823 p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
2824 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
2825 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
drh77e57df2013-10-22 14:28:02 +00002826 p->aSortOrder = (u8*)pExtra;
2827 p->nColumn = nCol;
drhbbbdc832013-10-22 18:01:40 +00002828 p->nKeyCol = nCol - 1;
drh77e57df2013-10-22 14:28:02 +00002829 *ppExtra = ((char*)p) + nByte;
2830 }
2831 return p;
2832}
2833
2834/*
drh23bf66d2004-12-14 03:34:34 +00002835** Create a new index for an SQL table. pName1.pName2 is the name of the index
2836** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002837** be NULL for a primary key or an index that is created to satisfy a
2838** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002839** as the table to be indexed. pParse->pNewTable is a table that is
2840** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002841**
drh382c0242001-10-06 16:33:02 +00002842** pList is a list of columns to be indexed. pList will be NULL if this
2843** is a primary key or unique-constraint on the most recent column added
2844** to the table currently under construction.
dan1da40a32009-09-19 17:00:31 +00002845**
2846** If the index is created successfully, return a pointer to the new Index
2847** structure. This is used by sqlite3AddPrimaryKey() to mark the index
drh48dd1d82014-05-27 18:18:58 +00002848** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
drh75897232000-05-29 14:26:00 +00002849*/
dan1da40a32009-09-19 17:00:31 +00002850Index *sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002851 Parse *pParse, /* All information about this parse */
2852 Token *pName1, /* First part of index name. May be NULL */
2853 Token *pName2, /* Second part of index name. May be NULL */
2854 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002855 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002856 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002857 Token *pStart, /* The CREATE token that begins this statement */
drh1fe05372013-07-31 18:12:26 +00002858 Expr *pPIWhere, /* WHERE clause for partial indices */
drh4d91a702006-01-04 15:54:36 +00002859 int sortOrder, /* Sort order of primary key when pList==NULL */
2860 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002861){
dan1da40a32009-09-19 17:00:31 +00002862 Index *pRet = 0; /* Pointer to return */
drhfdd6e852005-12-16 01:06:16 +00002863 Table *pTab = 0; /* Table to be indexed */
2864 Index *pIndex = 0; /* The index to be created */
2865 char *zName = 0; /* Name of the index */
2866 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002867 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002868 DbFixer sFix; /* For assigning database names to pTable */
2869 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002870 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002871 Db *pDb; /* The specific table containing the indexed database */
2872 int iDb; /* Index of the database that is being written */
2873 Token *pName = 0; /* Unqualified name of the index to create */
2874 struct ExprList_item *pListItem; /* For looping over pList */
drhc28c4e52013-10-03 19:21:41 +00002875 const Column *pTabCol; /* A column in the table */
drhc28c4e52013-10-03 19:21:41 +00002876 int nExtra = 0; /* Space allocated for zExtra[] */
drh44156282013-10-23 22:23:03 +00002877 int nExtraCol; /* Number of extra columns needed */
drh47b927d2013-12-03 00:11:40 +00002878 char *zExtra = 0; /* Extra space after the Index object */
drh44156282013-10-23 22:23:03 +00002879 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
danielk1977cbb18d22004-05-28 11:37:27 +00002880
drh7088d502015-04-18 17:43:29 +00002881 if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
drhd3001712009-05-12 17:46:53 +00002882 goto exit_create_index;
2883 }
2884 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e501b892006-01-09 06:29:47 +00002885 goto exit_create_index;
2886 }
drhdaffd0e2001-04-11 14:28:42 +00002887
drh75897232000-05-29 14:26:00 +00002888 /*
2889 ** Find the table that is to be indexed. Return early if not found.
2890 */
danielk1977cbb18d22004-05-28 11:37:27 +00002891 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002892
2893 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002894 ** to search for the table. 'Fix' the table name to this db
2895 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002896 */
2897 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002898 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002899 if( iDb<0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002900 assert( pName && pName->z );
danielk1977cbb18d22004-05-28 11:37:27 +00002901
danielk197753c0f742005-03-29 03:10:59 +00002902#ifndef SQLITE_OMIT_TEMPDB
mistachkind5578432012-08-25 10:01:29 +00002903 /* If the index name was unqualified, check if the table
danielk1977fe910332007-12-02 11:46:34 +00002904 ** is a temp table. If so, set the database to 1. Do not do this
2905 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002906 */
danielk1977fe910332007-12-02 11:46:34 +00002907 if( !db->init.busy ){
2908 pTab = sqlite3SrcListLookup(pParse, pTblName);
drhd3001712009-05-12 17:46:53 +00002909 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977fe910332007-12-02 11:46:34 +00002910 iDb = 1;
2911 }
danielk1977ef2cb632004-05-29 02:37:19 +00002912 }
danielk197753c0f742005-03-29 03:10:59 +00002913#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002914
drhd100f692013-10-03 15:39:44 +00002915 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
2916 if( sqlite3FixSrcList(&sFix, pTblName) ){
drh85c23c62005-08-20 03:03:04 +00002917 /* Because the parser constructs pTblName from a single identifier,
2918 ** sqlite3FixSrcList can never fail. */
2919 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002920 }
dan41fb5cd2012-10-04 19:33:00 +00002921 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
drhc31c7c12012-10-08 23:25:07 +00002922 assert( db->mallocFailed==0 || pTab==0 );
2923 if( pTab==0 ) goto exit_create_index;
drh989b1162013-08-01 22:27:26 +00002924 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
2925 sqlite3ErrorMsg(pParse,
2926 "cannot create a TEMP index on non-TEMP table \"%s\"",
2927 pTab->zName);
2928 goto exit_create_index;
2929 }
drh44156282013-10-23 22:23:03 +00002930 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
drh75897232000-05-29 14:26:00 +00002931 }else{
drhe3c41372001-09-17 20:25:58 +00002932 assert( pName==0 );
drhb07028f2011-10-14 21:49:18 +00002933 assert( pStart==0 );
danielk1977da184232006-01-05 11:34:32 +00002934 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002935 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002936 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002937 }
drhfdd6e852005-12-16 01:06:16 +00002938 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002939
drhd3001712009-05-12 17:46:53 +00002940 assert( pTab!=0 );
2941 assert( pParse->nErr==0 );
drh03881232009-02-13 03:43:31 +00002942 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
drh3a3a03f2014-09-11 16:36:43 +00002943 && db->init.busy==0
drhd4530972014-09-09 14:47:53 +00002944#if SQLITE_USER_AUTHENTICATION
2945 && sqlite3UserAuthTable(pTab->zName)==0
2946#endif
drh503a6862013-03-01 01:07:17 +00002947 && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
danielk19774adee202004-05-08 08:23:19 +00002948 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002949 goto exit_create_index;
2950 }
danielk1977576ec6b2005-01-21 11:55:25 +00002951#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002952 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002953 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002954 goto exit_create_index;
2955 }
danielk1977576ec6b2005-01-21 11:55:25 +00002956#endif
danielk19775ee9d692006-06-21 12:36:25 +00002957#ifndef SQLITE_OMIT_VIRTUALTABLE
2958 if( IsVirtual(pTab) ){
2959 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2960 goto exit_create_index;
2961 }
2962#endif
drh75897232000-05-29 14:26:00 +00002963
2964 /*
2965 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002966 ** index or table with the same name.
2967 **
2968 ** Exception: If we are reading the names of permanent indices from the
2969 ** sqlite_master table (because some other process changed the schema) and
2970 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002971 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002972 **
2973 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002974 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2975 ** own name.
drh75897232000-05-29 14:26:00 +00002976 */
danielk1977d8123362004-06-12 09:25:12 +00002977 if( pName ){
drh17435752007-08-16 04:30:38 +00002978 zName = sqlite3NameFromToken(db, pName);
drhe3c41372001-09-17 20:25:58 +00002979 if( zName==0 ) goto exit_create_index;
drhb07028f2011-10-14 21:49:18 +00002980 assert( pName->z!=0 );
danielk1977d8123362004-06-12 09:25:12 +00002981 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002982 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002983 }
danielk1977d8123362004-06-12 09:25:12 +00002984 if( !db->init.busy ){
danielk1977d45a0312007-03-13 16:32:25 +00002985 if( sqlite3FindTable(db, zName, 0)!=0 ){
2986 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2987 goto exit_create_index;
2988 }
2989 }
danielk197759a33f92007-03-17 10:26:59 +00002990 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2991 if( !ifNotExist ){
2992 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
dan7687c832011-04-09 15:39:02 +00002993 }else{
2994 assert( !db->init.busy );
2995 sqlite3CodeVerifySchema(pParse, iDb);
danielk1977d8123362004-06-12 09:25:12 +00002996 }
danielk197759a33f92007-03-17 10:26:59 +00002997 goto exit_create_index;
2998 }
danielk1977a21c6b62005-01-24 10:25:59 +00002999 }else{
drhadbca9c2001-09-27 15:11:53 +00003000 int n;
3001 Index *pLoop;
3002 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00003003 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00003004 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00003005 goto exit_create_index;
3006 }
drh75897232000-05-29 14:26:00 +00003007 }
3008
drhe5f9c642003-01-13 23:27:31 +00003009 /* Check for authorization to create an index.
3010 */
3011#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00003012 {
drhfdd6e852005-12-16 01:06:16 +00003013 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00003014 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003015 goto exit_create_index;
3016 }
3017 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00003018 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003019 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00003020 goto exit_create_index;
3021 }
drhe5f9c642003-01-13 23:27:31 +00003022 }
3023#endif
3024
drh75897232000-05-29 14:26:00 +00003025 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00003026 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00003027 ** So create a fake list to simulate this.
3028 */
3029 if( pList==0 ){
drhb7916a72009-05-27 10:31:29 +00003030 pList = sqlite3ExprListAppend(pParse, 0, 0);
drh75897232000-05-29 14:26:00 +00003031 if( pList==0 ) goto exit_create_index;
drh7f9c5db2013-10-23 00:32:58 +00003032 pList->a[0].zName = sqlite3DbStrDup(pParse->db,
3033 pTab->aCol[pTab->nCol-1].zName);
drh1bd10f82008-12-10 21:19:56 +00003034 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00003035 }
3036
danielk1977b3bf5562006-01-10 17:58:23 +00003037 /* Figure out how many bytes of space are required to store explicitly
3038 ** specified collation sequence names.
3039 */
3040 for(i=0; i<pList->nExpr; i++){
drhd3001712009-05-12 17:46:53 +00003041 Expr *pExpr = pList->a[i].pExpr;
3042 if( pExpr ){
dan911ce412013-05-15 15:16:50 +00003043 assert( pExpr->op==TK_COLLATE );
3044 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
danielk1977b3bf5562006-01-10 17:58:23 +00003045 }
3046 }
3047
drh75897232000-05-29 14:26:00 +00003048 /*
3049 ** Allocate the index structure.
3050 */
drhea678832008-12-10 19:26:22 +00003051 nName = sqlite3Strlen30(zName);
drh44156282013-10-23 22:23:03 +00003052 nExtraCol = pPk ? pPk->nKeyCol : 1;
3053 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
drh77e57df2013-10-22 14:28:02 +00003054 nName + nExtra + 1, &zExtra);
drh17435752007-08-16 04:30:38 +00003055 if( db->mallocFailed ){
3056 goto exit_create_index;
3057 }
dancfc9df72014-04-25 15:01:01 +00003058 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
drhe09b84c2011-11-14 02:53:54 +00003059 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
drh77e57df2013-10-22 14:28:02 +00003060 pIndex->zName = zExtra;
3061 zExtra += nName + 1;
drh5bb3eb92007-05-04 13:15:55 +00003062 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00003063 pIndex->pTable = pTab;
drh1bd10f82008-12-10 21:19:56 +00003064 pIndex->onError = (u8)onError;
drh9eade082013-10-24 14:16:10 +00003065 pIndex->uniqNotNull = onError!=OE_None;
drh48dd1d82014-05-27 18:18:58 +00003066 pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
danielk1977da184232006-01-05 11:34:32 +00003067 pIndex->pSchema = db->aDb[iDb].pSchema;
drh72ffd092013-10-30 15:52:32 +00003068 pIndex->nKeyCol = pList->nExpr;
drh3780be12013-07-31 19:05:22 +00003069 if( pPIWhere ){
3070 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
3071 pIndex->pPartIdxWhere = pPIWhere;
3072 pPIWhere = 0;
3073 }
drh21206082011-04-04 18:22:02 +00003074 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh75897232000-05-29 14:26:00 +00003075
drhfdd6e852005-12-16 01:06:16 +00003076 /* Check to see if we should honor DESC requests on index columns
3077 */
danielk1977da184232006-01-05 11:34:32 +00003078 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00003079 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00003080 }else{
3081 sortOrderMask = 0; /* Ignore DESC */
3082 }
3083
drh1ccde152000-06-17 13:12:39 +00003084 /* Scan the names of the columns of the table to be indexed and
3085 ** load the column indices into the Index structure. Report an error
3086 ** if any column is not found.
drhd3001712009-05-12 17:46:53 +00003087 **
3088 ** TODO: Add a test to make sure that the same column is not named
3089 ** more than once within the same index. Only the first instance of
3090 ** the column will ever be used by the optimizer. Note that using the
3091 ** same column more than once cannot be an error because that would
3092 ** break backwards compatibility - it needs to be a warning.
drh75897232000-05-29 14:26:00 +00003093 */
drhfdd6e852005-12-16 01:06:16 +00003094 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
3095 const char *zColName = pListItem->zName;
drh85eeb692005-12-21 03:16:42 +00003096 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00003097 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00003098
drhfdd6e852005-12-16 01:06:16 +00003099 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
3100 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00003101 }
3102 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00003103 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00003104 pTab->zName, zColName);
dan1db95102010-06-28 10:15:19 +00003105 pParse->checkSchema = 1;
drh75897232000-05-29 14:26:00 +00003106 goto exit_create_index;
3107 }
drhbf20a352014-04-04 22:44:59 +00003108 assert( j<=0x7fff );
drhbbbdc832013-10-22 18:01:40 +00003109 pIndex->aiColumn[i] = (i16)j;
dan911ce412013-05-15 15:16:50 +00003110 if( pListItem->pExpr ){
drhd3001712009-05-12 17:46:53 +00003111 int nColl;
dan911ce412013-05-15 15:16:50 +00003112 assert( pListItem->pExpr->op==TK_COLLATE );
3113 zColl = pListItem->pExpr->u.zToken;
drhd3001712009-05-12 17:46:53 +00003114 nColl = sqlite3Strlen30(zColl) + 1;
3115 assert( nExtra>=nColl );
3116 memcpy(zExtra, zColl, nColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003117 zColl = zExtra;
drhd3001712009-05-12 17:46:53 +00003118 zExtra += nColl;
3119 nExtra -= nColl;
danielk19770202b292004-06-09 09:55:16 +00003120 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00003121 zColl = pTab->aCol[j].zColl;
dan911ce412013-05-15 15:16:50 +00003122 if( !zColl ) zColl = "BINARY";
danielk19770202b292004-06-09 09:55:16 +00003123 }
drhb7f24de2009-05-13 17:35:23 +00003124 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
danielk19777cedc8d2004-06-10 10:50:08 +00003125 goto exit_create_index;
3126 }
danielk1977b3bf5562006-01-10 17:58:23 +00003127 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00003128 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00003129 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh7699d1c2013-06-04 12:42:29 +00003130 if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
drh75897232000-05-29 14:26:00 +00003131 }
drh44156282013-10-23 22:23:03 +00003132 if( pPk ){
drh7913e412013-11-01 20:30:36 +00003133 for(j=0; j<pPk->nKeyCol; j++){
3134 int x = pPk->aiColumn[j];
3135 if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
3136 pIndex->nColumn--;
3137 }else{
3138 pIndex->aiColumn[i] = x;
3139 pIndex->azColl[i] = pPk->azColl[j];
3140 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
3141 i++;
3142 }
drh44156282013-10-23 22:23:03 +00003143 }
drh7913e412013-11-01 20:30:36 +00003144 assert( i==pIndex->nColumn );
drh44156282013-10-23 22:23:03 +00003145 }else{
3146 pIndex->aiColumn[i] = -1;
3147 pIndex->azColl[i] = "BINARY";
3148 }
drh51147ba2005-07-23 22:59:55 +00003149 sqlite3DefaultRowEst(pIndex);
drhe13e9f52013-10-05 19:18:00 +00003150 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
drh75897232000-05-29 14:26:00 +00003151
danielk1977d8123362004-06-12 09:25:12 +00003152 if( pTab==pParse->pNewTable ){
3153 /* This routine has been called to create an automatic index as a
3154 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
3155 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
3156 ** i.e. one of:
3157 **
3158 ** CREATE TABLE t(x PRIMARY KEY, y);
3159 ** CREATE TABLE t(x, y, UNIQUE(x, y));
3160 **
3161 ** Either way, check to see if the table already has such an index. If
3162 ** so, don't bother creating this one. This only applies to
3163 ** automatically created indices. Users can do as they wish with
3164 ** explicit indices.
drhd3001712009-05-12 17:46:53 +00003165 **
3166 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
3167 ** (and thus suppressing the second one) even if they have different
3168 ** sort orders.
3169 **
3170 ** If there are different collating sequences or if the columns of
3171 ** the constraint occur in different orders, then the constraints are
3172 ** considered distinct and both result in separate indices.
danielk1977d8123362004-06-12 09:25:12 +00003173 */
3174 Index *pIdx;
3175 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3176 int k;
drh5f1d1d92014-07-31 22:59:04 +00003177 assert( IsUniqueIndex(pIdx) );
drh48dd1d82014-05-27 18:18:58 +00003178 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
drh5f1d1d92014-07-31 22:59:04 +00003179 assert( IsUniqueIndex(pIndex) );
danielk1977d8123362004-06-12 09:25:12 +00003180
drhbbbdc832013-10-22 18:01:40 +00003181 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
3182 for(k=0; k<pIdx->nKeyCol; k++){
drhd3001712009-05-12 17:46:53 +00003183 const char *z1;
3184 const char *z2;
danielk1977d8123362004-06-12 09:25:12 +00003185 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
drhd3001712009-05-12 17:46:53 +00003186 z1 = pIdx->azColl[k];
3187 z2 = pIndex->azColl[k];
danielk1977b3bf5562006-01-10 17:58:23 +00003188 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00003189 }
drhbbbdc832013-10-22 18:01:40 +00003190 if( k==pIdx->nKeyCol ){
danielk1977f736b772004-06-17 06:13:34 +00003191 if( pIdx->onError!=pIndex->onError ){
3192 /* This constraint creates the same index as a previous
3193 ** constraint specified somewhere in the CREATE TABLE statement.
3194 ** However the ON CONFLICT clauses are different. If both this
3195 ** constraint and the previous equivalent constraint have explicit
3196 ** ON CONFLICT clauses this is an error. Otherwise, use the
mistachkin48864df2013-03-21 21:20:32 +00003197 ** explicitly specified behavior for the index.
danielk1977f736b772004-06-17 06:13:34 +00003198 */
3199 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
3200 sqlite3ErrorMsg(pParse,
3201 "conflicting ON CONFLICT clauses specified", 0);
3202 }
3203 if( pIdx->onError==OE_Default ){
3204 pIdx->onError = pIndex->onError;
3205 }
3206 }
drhf0636852015-03-21 02:58:20 +00003207 pRet = pIdx;
danielk1977d8123362004-06-12 09:25:12 +00003208 goto exit_create_index;
3209 }
3210 }
3211 }
3212
drh75897232000-05-29 14:26:00 +00003213 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00003214 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00003215 */
drh234c39d2004-07-24 03:30:47 +00003216 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00003217 Index *p;
drh21206082011-04-04 18:22:02 +00003218 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
danielk1977da184232006-01-05 11:34:32 +00003219 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhacbcb7e2014-08-21 20:26:37 +00003220 pIndex->zName, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00003221 if( p ){
3222 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00003223 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00003224 goto exit_create_index;
3225 }
drh5e00f6c2001-09-13 13:46:56 +00003226 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00003227 if( pTblName!=0 ){
3228 pIndex->tnum = db->init.newTnum;
3229 }
drhd78eeee2001-09-13 16:18:53 +00003230 }
3231
drh58383402013-11-04 17:00:50 +00003232 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
3233 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
3234 ** emit code to allocate the index rootpage on disk and make an entry for
3235 ** the index in the sqlite_master table and populate the index with
3236 ** content. But, do not do this if we are simply reading the sqlite_master
3237 ** table to parse the schema, or if this index is the PRIMARY KEY index
3238 ** of a WITHOUT ROWID table.
drh75897232000-05-29 14:26:00 +00003239 **
drh58383402013-11-04 17:00:50 +00003240 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
3241 ** or UNIQUE index in a CREATE TABLE statement. Since the table
drh382c0242001-10-06 16:33:02 +00003242 ** has just been created, it contains no data and the index initialization
3243 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00003244 */
drh58383402013-11-04 17:00:50 +00003245 else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
drhadbca9c2001-09-27 15:11:53 +00003246 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00003247 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00003248 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00003249
danielk19774adee202004-05-08 08:23:19 +00003250 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003251 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00003252
drhfdd6e852005-12-16 01:06:16 +00003253
drh063336a2004-11-05 20:58:39 +00003254 /* Create the rootpage for the index
3255 */
drhaee128d2005-02-14 20:48:18 +00003256 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00003257 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00003258
3259 /* Gather the complete text of the CREATE INDEX statement into
3260 ** the zStmt variable
3261 */
drhd3001712009-05-12 17:46:53 +00003262 if( pStart ){
drh77dfd5b2013-08-19 11:15:48 +00003263 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
drh8a9789b2013-08-01 03:36:59 +00003264 if( pName->z[n-1]==';' ) n--;
drh063336a2004-11-05 20:58:39 +00003265 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00003266 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh8a9789b2013-08-01 03:36:59 +00003267 onError==OE_None ? "" : " UNIQUE", n, pName->z);
drh063336a2004-11-05 20:58:39 +00003268 }else{
3269 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00003270 /* zStmt = sqlite3MPrintf(""); */
3271 zStmt = 0;
drh75897232000-05-29 14:26:00 +00003272 }
drh063336a2004-11-05 20:58:39 +00003273
3274 /* Add an entry in sqlite_master for this index
3275 */
3276 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00003277 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00003278 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
3279 pIndex->zName,
3280 pTab->zName,
drhb7654112008-01-12 12:48:07 +00003281 iMem,
drh063336a2004-11-05 20:58:39 +00003282 zStmt
3283 );
drh633e6d52008-07-28 19:34:53 +00003284 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00003285
danielk1977a21c6b62005-01-24 10:25:59 +00003286 /* Fill the index with data and reparse the schema. Code an OP_Expire
3287 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00003288 */
danielk1977cbb18d22004-05-28 11:37:27 +00003289 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00003290 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00003291 sqlite3ChangeCookie(pParse, iDb);
drh5d9c9da2011-06-03 20:11:17 +00003292 sqlite3VdbeAddParseSchemaOp(v, iDb,
3293 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
drh66a51672008-01-03 00:01:23 +00003294 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00003295 }
drh75897232000-05-29 14:26:00 +00003296 }
3297
danielk1977d8123362004-06-12 09:25:12 +00003298 /* When adding an index to the list of indices for a table, make
3299 ** sure all indices labeled OE_Replace come after all those labeled
drhd3001712009-05-12 17:46:53 +00003300 ** OE_Ignore. This is necessary for the correct constraint check
3301 ** processing (in sqlite3GenerateConstraintChecks()) as part of
3302 ** UPDATE and INSERT statements.
danielk1977d8123362004-06-12 09:25:12 +00003303 */
drh234c39d2004-07-24 03:30:47 +00003304 if( db->init.busy || pTblName==0 ){
3305 if( onError!=OE_Replace || pTab->pIndex==0
3306 || pTab->pIndex->onError==OE_Replace){
3307 pIndex->pNext = pTab->pIndex;
3308 pTab->pIndex = pIndex;
3309 }else{
3310 Index *pOther = pTab->pIndex;
3311 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
3312 pOther = pOther->pNext;
3313 }
3314 pIndex->pNext = pOther->pNext;
3315 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00003316 }
dan1da40a32009-09-19 17:00:31 +00003317 pRet = pIndex;
drh234c39d2004-07-24 03:30:47 +00003318 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00003319 }
danielk1977d8123362004-06-12 09:25:12 +00003320
drh75897232000-05-29 14:26:00 +00003321 /* Clean up before exiting */
3322exit_create_index:
drh1fe05372013-07-31 18:12:26 +00003323 if( pIndex ) freeIndex(db, pIndex);
3324 sqlite3ExprDelete(db, pPIWhere);
drh633e6d52008-07-28 19:34:53 +00003325 sqlite3ExprListDelete(db, pList);
3326 sqlite3SrcListDelete(db, pTblName);
3327 sqlite3DbFree(db, zName);
dan1da40a32009-09-19 17:00:31 +00003328 return pRet;
drh75897232000-05-29 14:26:00 +00003329}
3330
3331/*
drh51147ba2005-07-23 22:59:55 +00003332** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00003333** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00003334**
peter.d.reid60ec9142014-09-06 16:39:46 +00003335** aiRowEst[0] is supposed to contain the number of elements in the index.
drh28c4cf42005-07-27 20:41:43 +00003336** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
3337** number of rows in the table that match any particular value of the
3338** first column of the index. aiRowEst[2] is an estimate of the number
dancfc9df72014-04-25 15:01:01 +00003339** of rows that match any particular combination of the first 2 columns
drh28c4cf42005-07-27 20:41:43 +00003340** of the index. And so forth. It must always be the case that
3341*
3342** aiRowEst[N]<=aiRowEst[N-1]
3343** aiRowEst[N]>=1
3344**
3345** Apart from that, we have little to go on besides intuition as to
3346** how aiRowEst[] should be initialized. The numbers generated here
3347** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00003348*/
3349void sqlite3DefaultRowEst(Index *pIdx){
dan264d2b92014-04-29 19:01:57 +00003350 /* 10, 9, 8, 7, 6 */
3351 LogEst aVal[] = { 33, 32, 30, 28, 26 };
dancfc9df72014-04-25 15:01:01 +00003352 LogEst *a = pIdx->aiRowLogEst;
3353 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
drh51147ba2005-07-23 22:59:55 +00003354 int i;
dancfc9df72014-04-25 15:01:01 +00003355
dan264d2b92014-04-29 19:01:57 +00003356 /* Set the first entry (number of rows in the index) to the estimated
3357 ** number of rows in the table. Or 10, if the estimated number of rows
3358 ** in the table is less than that. */
dancfc9df72014-04-25 15:01:01 +00003359 a[0] = pIdx->pTable->nRowLogEst;
dan264d2b92014-04-29 19:01:57 +00003360 if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
3361
3362 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
3363 ** 6 and each subsequent value (if any) is 5. */
dancfc9df72014-04-25 15:01:01 +00003364 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
dan264d2b92014-04-29 19:01:57 +00003365 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
3366 a[i] = 23; assert( 23==sqlite3LogEst(5) );
drh28c4cf42005-07-27 20:41:43 +00003367 }
dan264d2b92014-04-29 19:01:57 +00003368
3369 assert( 0==sqlite3LogEst(1) );
drh5f1d1d92014-07-31 22:59:04 +00003370 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
drh51147ba2005-07-23 22:59:55 +00003371}
3372
3373/*
drh74e24cd2002-01-09 03:19:59 +00003374** This routine will drop an existing named index. This routine
3375** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00003376*/
drh4d91a702006-01-04 15:54:36 +00003377void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00003378 Index *pIndex;
drh75897232000-05-29 14:26:00 +00003379 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00003380 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00003381 int iDb;
drh75897232000-05-29 14:26:00 +00003382
drh8af73d42009-05-13 22:58:28 +00003383 assert( pParse->nErr==0 ); /* Never called with prior errors */
3384 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00003385 goto exit_drop_index;
3386 }
drhd24cc422003-03-27 12:51:24 +00003387 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00003388 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
3389 goto exit_drop_index;
3390 }
danielk19774adee202004-05-08 08:23:19 +00003391 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00003392 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00003393 if( !ifExists ){
3394 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
dan57966752011-04-09 17:32:58 +00003395 }else{
3396 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
drh4d91a702006-01-04 15:54:36 +00003397 }
drha6ecd332004-06-10 00:29:09 +00003398 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00003399 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00003400 }
drh48dd1d82014-05-27 18:18:58 +00003401 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
danielk19774adee202004-05-08 08:23:19 +00003402 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00003403 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00003404 goto exit_drop_index;
3405 }
danielk1977da184232006-01-05 11:34:32 +00003406 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00003407#ifndef SQLITE_OMIT_AUTHORIZATION
3408 {
3409 int code = SQLITE_DROP_INDEX;
3410 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00003411 const char *zDb = db->aDb[iDb].zName;
3412 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00003413 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003414 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003415 }
danielk1977da184232006-01-05 11:34:32 +00003416 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00003417 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00003418 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00003419 }
drhed6c8672003-01-12 18:02:16 +00003420 }
drhe5f9c642003-01-13 23:27:31 +00003421#endif
drh75897232000-05-29 14:26:00 +00003422
3423 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00003424 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00003425 if( v ){
drh77658e22007-12-04 16:54:52 +00003426 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00003427 sqlite3NestedParse(pParse,
dan39f1bcb2010-09-29 07:16:46 +00003428 "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
drha5ae4c32011-08-07 01:31:52 +00003429 db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
drhb17131a2004-11-05 22:18:49 +00003430 );
drha5ae4c32011-08-07 01:31:52 +00003431 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
drh9cbf3422008-01-17 16:22:13 +00003432 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00003433 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00003434 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00003435 }
3436
drhd24cc422003-03-27 12:51:24 +00003437exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00003438 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00003439}
3440
3441/*
dan9ace1122012-03-29 07:51:45 +00003442** pArray is a pointer to an array of objects. Each object in the
3443** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
3444** to extend the array so that there is space for a new object at the end.
drh13449892005-09-07 21:22:45 +00003445**
dan9ace1122012-03-29 07:51:45 +00003446** When this function is called, *pnEntry contains the current size of
3447** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
3448** in total).
drh13449892005-09-07 21:22:45 +00003449**
dan9ace1122012-03-29 07:51:45 +00003450** If the realloc() is successful (i.e. if no OOM condition occurs), the
3451** space allocated for the new object is zeroed, *pnEntry updated to
3452** reflect the new size of the array and a pointer to the new allocation
3453** returned. *pIdx is set to the index of the new array entry in this case.
drh13449892005-09-07 21:22:45 +00003454**
dan9ace1122012-03-29 07:51:45 +00003455** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
3456** unchanged and a copy of pArray returned.
drh13449892005-09-07 21:22:45 +00003457*/
drhcf643722007-03-27 13:36:37 +00003458void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003459 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00003460 void *pArray, /* Array of objects. Might be reallocated */
3461 int szEntry, /* Size of each object in the array */
drhcf643722007-03-27 13:36:37 +00003462 int *pnEntry, /* Number of objects currently in use */
drhcf643722007-03-27 13:36:37 +00003463 int *pIdx /* Write the index of a new slot here */
3464){
3465 char *z;
drh6c535152012-02-02 03:38:30 +00003466 int n = *pnEntry;
3467 if( (n & (n-1))==0 ){
3468 int sz = (n==0) ? 1 : 2*n;
3469 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
drh13449892005-09-07 21:22:45 +00003470 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00003471 *pIdx = -1;
3472 return pArray;
drh13449892005-09-07 21:22:45 +00003473 }
drhcf643722007-03-27 13:36:37 +00003474 pArray = pNew;
drh13449892005-09-07 21:22:45 +00003475 }
drhcf643722007-03-27 13:36:37 +00003476 z = (char*)pArray;
drh6c535152012-02-02 03:38:30 +00003477 memset(&z[n * szEntry], 0, szEntry);
3478 *pIdx = n;
drhcf643722007-03-27 13:36:37 +00003479 ++*pnEntry;
3480 return pArray;
drh13449892005-09-07 21:22:45 +00003481}
3482
3483/*
drh75897232000-05-29 14:26:00 +00003484** Append a new element to the given IdList. Create a new IdList if
3485** need be.
drhdaffd0e2001-04-11 14:28:42 +00003486**
3487** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00003488*/
drh17435752007-08-16 04:30:38 +00003489IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00003490 int i;
drh75897232000-05-29 14:26:00 +00003491 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003492 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00003493 if( pList==0 ) return 0;
3494 }
drhcf643722007-03-27 13:36:37 +00003495 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003496 db,
drhcf643722007-03-27 13:36:37 +00003497 pList->a,
3498 sizeof(pList->a[0]),
drhcf643722007-03-27 13:36:37 +00003499 &pList->nId,
drhcf643722007-03-27 13:36:37 +00003500 &i
3501 );
drh13449892005-09-07 21:22:45 +00003502 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00003503 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00003504 return 0;
drh75897232000-05-29 14:26:00 +00003505 }
drh17435752007-08-16 04:30:38 +00003506 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00003507 return pList;
3508}
3509
3510/*
drhfe05af82005-07-21 03:14:59 +00003511** Delete an IdList.
3512*/
drh633e6d52008-07-28 19:34:53 +00003513void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00003514 int i;
3515 if( pList==0 ) return;
3516 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00003517 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00003518 }
drh633e6d52008-07-28 19:34:53 +00003519 sqlite3DbFree(db, pList->a);
3520 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00003521}
3522
3523/*
3524** Return the index in pList of the identifier named zId. Return -1
3525** if not found.
3526*/
3527int sqlite3IdListIndex(IdList *pList, const char *zName){
3528 int i;
3529 if( pList==0 ) return -1;
3530 for(i=0; i<pList->nId; i++){
3531 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
3532 }
3533 return -1;
3534}
3535
3536/*
drha78c22c2008-11-11 18:28:58 +00003537** Expand the space allocated for the given SrcList object by
3538** creating nExtra new slots beginning at iStart. iStart is zero based.
3539** New slots are zeroed.
3540**
3541** For example, suppose a SrcList initially contains two entries: A,B.
3542** To append 3 new entries onto the end, do this:
3543**
3544** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3545**
3546** After the call above it would contain: A, B, nil, nil, nil.
3547** If the iStart argument had been 1 instead of 2, then the result
3548** would have been: A, nil, nil, nil, B. To prepend the new slots,
3549** the iStart value would be 0. The result then would
3550** be: nil, nil, nil, A, B.
3551**
3552** If a memory allocation fails the SrcList is unchanged. The
3553** db->mallocFailed flag will be set to true.
3554*/
3555SrcList *sqlite3SrcListEnlarge(
3556 sqlite3 *db, /* Database connection to notify of OOM errors */
3557 SrcList *pSrc, /* The SrcList to be enlarged */
3558 int nExtra, /* Number of new slots to add to pSrc->a[] */
3559 int iStart /* Index in pSrc->a[] of first new slot */
3560){
3561 int i;
3562
3563 /* Sanity checking on calling parameters */
3564 assert( iStart>=0 );
3565 assert( nExtra>=1 );
drh8af73d42009-05-13 22:58:28 +00003566 assert( pSrc!=0 );
3567 assert( iStart<=pSrc->nSrc );
drha78c22c2008-11-11 18:28:58 +00003568
3569 /* Allocate additional space if needed */
drhfc5717c2014-03-05 19:04:46 +00003570 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
drha78c22c2008-11-11 18:28:58 +00003571 SrcList *pNew;
3572 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003573 int nGot;
drha78c22c2008-11-11 18:28:58 +00003574 pNew = sqlite3DbRealloc(db, pSrc,
3575 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3576 if( pNew==0 ){
3577 assert( db->mallocFailed );
3578 return pSrc;
3579 }
3580 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003581 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh6d1626e2014-03-05 15:52:43 +00003582 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003583 }
3584
3585 /* Move existing slots that come after the newly inserted slots
3586 ** out of the way */
3587 for(i=pSrc->nSrc-1; i>=iStart; i--){
3588 pSrc->a[i+nExtra] = pSrc->a[i];
3589 }
drh6d1626e2014-03-05 15:52:43 +00003590 pSrc->nSrc += nExtra;
drha78c22c2008-11-11 18:28:58 +00003591
3592 /* Zero the newly allocated slots */
3593 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3594 for(i=iStart; i<iStart+nExtra; i++){
3595 pSrc->a[i].iCursor = -1;
3596 }
3597
3598 /* Return a pointer to the enlarged SrcList */
3599 return pSrc;
3600}
3601
3602
3603/*
drhad3cab52002-05-24 02:04:32 +00003604** Append a new table name to the given SrcList. Create a new SrcList if
drhb7916a72009-05-27 10:31:29 +00003605** need be. A new entry is created in the SrcList even if pTable is NULL.
drhad3cab52002-05-24 02:04:32 +00003606**
drha78c22c2008-11-11 18:28:58 +00003607** A SrcList is returned, or NULL if there is an OOM error. The returned
3608** SrcList might be the same as the SrcList that was input or it might be
3609** a new one. If an OOM error does occurs, then the prior value of pList
3610** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003611**
3612** If pDatabase is not null, it means that the table has an optional
3613** database name prefix. Like this: "database.table". The pDatabase
3614** points to the table name and the pTable points to the database name.
3615** The SrcList.a[].zName field is filled with the table name which might
3616** come from pTable (if pDatabase is NULL) or from pDatabase.
3617** SrcList.a[].zDatabase is filled with the database name from pTable,
3618** or with NULL if no database is specified.
3619**
3620** In other words, if call like this:
3621**
drh17435752007-08-16 04:30:38 +00003622** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003623**
3624** Then B is a table name and the database name is unspecified. If called
3625** like this:
3626**
drh17435752007-08-16 04:30:38 +00003627** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003628**
drhd3001712009-05-12 17:46:53 +00003629** Then C is the table name and B is the database name. If C is defined
3630** then so is B. In other words, we never have a case where:
3631**
3632** sqlite3SrcListAppend(D,A,0,C);
drhb7916a72009-05-27 10:31:29 +00003633**
3634** Both pTable and pDatabase are assumed to be quoted. They are dequoted
3635** before being added to the SrcList.
drhad3cab52002-05-24 02:04:32 +00003636*/
drh17435752007-08-16 04:30:38 +00003637SrcList *sqlite3SrcListAppend(
3638 sqlite3 *db, /* Connection to notify of malloc failures */
3639 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3640 Token *pTable, /* Table to append */
3641 Token *pDatabase /* Database of the table */
3642){
drha99db3b2004-06-19 14:49:12 +00003643 struct SrcList_item *pItem;
drhd3001712009-05-12 17:46:53 +00003644 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
drhad3cab52002-05-24 02:04:32 +00003645 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003646 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003647 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003648 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003649 }
drha78c22c2008-11-11 18:28:58 +00003650 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3651 if( db->mallocFailed ){
3652 sqlite3SrcListDelete(db, pList);
3653 return 0;
drhad3cab52002-05-24 02:04:32 +00003654 }
drha78c22c2008-11-11 18:28:58 +00003655 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003656 if( pDatabase && pDatabase->z==0 ){
3657 pDatabase = 0;
3658 }
drhd3001712009-05-12 17:46:53 +00003659 if( pDatabase ){
drh113088e2003-03-20 01:16:58 +00003660 Token *pTemp = pDatabase;
3661 pDatabase = pTable;
3662 pTable = pTemp;
3663 }
drh17435752007-08-16 04:30:38 +00003664 pItem->zName = sqlite3NameFromToken(db, pTable);
3665 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003666 return pList;
3667}
3668
3669/*
drhdfe88ec2008-11-03 20:55:06 +00003670** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003671*/
danielk19774adee202004-05-08 08:23:19 +00003672void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003673 int i;
drh9b3187e2005-01-18 14:45:47 +00003674 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003675 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003676 if( pList ){
3677 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3678 if( pItem->iCursor>=0 ) break;
3679 pItem->iCursor = pParse->nTab++;
3680 if( pItem->pSelect ){
3681 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3682 }
drh63eb5f22003-04-29 16:20:44 +00003683 }
3684 }
3685}
3686
3687/*
drhad3cab52002-05-24 02:04:32 +00003688** Delete an entire SrcList including all its substructure.
3689*/
drh633e6d52008-07-28 19:34:53 +00003690void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003691 int i;
drhbe5c89a2004-07-26 00:31:09 +00003692 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003693 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003694 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003695 sqlite3DbFree(db, pItem->zDatabase);
3696 sqlite3DbFree(db, pItem->zName);
3697 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003698 sqlite3DbFree(db, pItem->zIndex);
dan1feeaed2010-07-23 15:41:47 +00003699 sqlite3DeleteTable(db, pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003700 sqlite3SelectDelete(db, pItem->pSelect);
3701 sqlite3ExprDelete(db, pItem->pOn);
3702 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003703 }
drh633e6d52008-07-28 19:34:53 +00003704 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003705}
3706
drh982cef72000-05-30 16:27:03 +00003707/*
drh61dfc312006-12-16 16:25:15 +00003708** This routine is called by the parser to add a new term to the
3709** end of a growing FROM clause. The "p" parameter is the part of
3710** the FROM clause that has already been constructed. "p" is NULL
3711** if this is the first term of the FROM clause. pTable and pDatabase
3712** are the name of the table and database named in the FROM clause term.
3713** pDatabase is NULL if the database name qualifier is missing - the
peter.d.reid60ec9142014-09-06 16:39:46 +00003714** usual case. If the term has an alias, then pAlias points to the
drh61dfc312006-12-16 16:25:15 +00003715** alias token. If the term is a subquery, then pSubquery is the
3716** SELECT statement that the subquery encodes. The pTable and
3717** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3718** parameters are the content of the ON and USING clauses.
3719**
3720** Return a new SrcList which encodes is the FROM with the new
3721** term added.
3722*/
3723SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003724 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003725 SrcList *p, /* The left part of the FROM clause already seen */
3726 Token *pTable, /* Name of the table to add to the FROM clause */
3727 Token *pDatabase, /* Name of the database containing pTable */
3728 Token *pAlias, /* The right-hand side of the AS subexpression */
3729 Select *pSubquery, /* A subquery used in place of a table name */
3730 Expr *pOn, /* The ON clause of a join */
3731 IdList *pUsing /* The USING clause of a join */
3732){
3733 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003734 sqlite3 *db = pParse->db;
danielk1977bd1a0a42009-07-01 16:12:07 +00003735 if( !p && (pOn || pUsing) ){
3736 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
3737 (pOn ? "ON" : "USING")
3738 );
3739 goto append_from_error;
3740 }
drh17435752007-08-16 04:30:38 +00003741 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh8af73d42009-05-13 22:58:28 +00003742 if( p==0 || NEVER(p->nSrc==0) ){
danielk1977bd1a0a42009-07-01 16:12:07 +00003743 goto append_from_error;
drh61dfc312006-12-16 16:25:15 +00003744 }
3745 pItem = &p->a[p->nSrc-1];
drh8af73d42009-05-13 22:58:28 +00003746 assert( pAlias!=0 );
3747 if( pAlias->n ){
drh17435752007-08-16 04:30:38 +00003748 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003749 }
3750 pItem->pSelect = pSubquery;
danielk1977bd1a0a42009-07-01 16:12:07 +00003751 pItem->pOn = pOn;
3752 pItem->pUsing = pUsing;
drh61dfc312006-12-16 16:25:15 +00003753 return p;
danielk1977bd1a0a42009-07-01 16:12:07 +00003754
3755 append_from_error:
3756 assert( p==0 );
3757 sqlite3ExprDelete(db, pOn);
3758 sqlite3IdListDelete(db, pUsing);
3759 sqlite3SelectDelete(db, pSubquery);
3760 return 0;
drh61dfc312006-12-16 16:25:15 +00003761}
3762
3763/*
danielk1977b1c685b2008-10-06 16:18:39 +00003764** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3765** element of the source-list passed as the second argument.
3766*/
3767void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
drh8af73d42009-05-13 22:58:28 +00003768 assert( pIndexedBy!=0 );
3769 if( p && ALWAYS(p->nSrc>0) ){
danielk1977b1c685b2008-10-06 16:18:39 +00003770 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3771 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3772 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3773 /* A "NOT INDEXED" clause was supplied. See parse.y
3774 ** construct "indexed_opt" for details. */
3775 pItem->notIndexed = 1;
3776 }else{
3777 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3778 }
3779 }
3780}
3781
3782/*
drh61dfc312006-12-16 16:25:15 +00003783** When building up a FROM clause in the parser, the join operator
3784** is initially attached to the left operand. But the code generator
3785** expects the join operator to be on the right operand. This routine
3786** Shifts all join operators from left to right for an entire FROM
3787** clause.
3788**
3789** Example: Suppose the join is like this:
3790**
3791** A natural cross join B
3792**
3793** The operator is "natural cross join". The A and B operands are stored
3794** in p->a[0] and p->a[1], respectively. The parser initially stores the
3795** operator with A. This routine shifts that operator over to B.
3796*/
3797void sqlite3SrcListShiftJoinType(SrcList *p){
drhd017ab92011-08-23 00:01:58 +00003798 if( p ){
drh61dfc312006-12-16 16:25:15 +00003799 int i;
3800 for(i=p->nSrc-1; i>0; i--){
3801 p->a[i].jointype = p->a[i-1].jointype;
3802 }
3803 p->a[0].jointype = 0;
3804 }
3805}
3806
3807/*
drhc4a3c772001-04-04 11:48:57 +00003808** Begin a transaction
3809*/
drh684917c2004-10-05 02:41:42 +00003810void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003811 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003812 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003813 int i;
drh5e00f6c2001-09-13 13:46:56 +00003814
drhd3001712009-05-12 17:46:53 +00003815 assert( pParse!=0 );
3816 db = pParse->db;
3817 assert( db!=0 );
drh04491712009-05-13 17:21:13 +00003818/* if( db->aDb[0].pBt==0 ) return; */
drhd3001712009-05-12 17:46:53 +00003819 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
3820 return;
3821 }
danielk19771d850a72004-05-31 08:26:49 +00003822 v = sqlite3GetVdbe(pParse);
3823 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003824 if( type!=TK_DEFERRED ){
3825 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003826 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003827 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003828 }
3829 }
drh66a51672008-01-03 00:01:23 +00003830 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003831}
3832
3833/*
3834** Commit a transaction
3835*/
danielk19774adee202004-05-08 08:23:19 +00003836void sqlite3CommitTransaction(Parse *pParse){
danielk19771d850a72004-05-31 08:26:49 +00003837 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003838
drhd3001712009-05-12 17:46:53 +00003839 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003840 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003841 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
3842 return;
3843 }
danielk19771d850a72004-05-31 08:26:49 +00003844 v = sqlite3GetVdbe(pParse);
3845 if( v ){
drh66a51672008-01-03 00:01:23 +00003846 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003847 }
drhc4a3c772001-04-04 11:48:57 +00003848}
3849
3850/*
3851** Rollback a transaction
3852*/
danielk19774adee202004-05-08 08:23:19 +00003853void sqlite3RollbackTransaction(Parse *pParse){
drh5e00f6c2001-09-13 13:46:56 +00003854 Vdbe *v;
3855
drhd3001712009-05-12 17:46:53 +00003856 assert( pParse!=0 );
drhb07028f2011-10-14 21:49:18 +00003857 assert( pParse->db!=0 );
drhd3001712009-05-12 17:46:53 +00003858 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
3859 return;
3860 }
danielk19774adee202004-05-08 08:23:19 +00003861 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003862 if( v ){
drh66a51672008-01-03 00:01:23 +00003863 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003864 }
drhc4a3c772001-04-04 11:48:57 +00003865}
drhf57b14a2001-09-14 18:54:08 +00003866
3867/*
danielk1977fd7f0452008-12-17 17:30:26 +00003868** This function is called by the parser when it parses a command to create,
3869** release or rollback an SQL savepoint.
3870*/
3871void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003872 char *zName = sqlite3NameFromToken(pParse->db, pName);
3873 if( zName ){
3874 Vdbe *v = sqlite3GetVdbe(pParse);
3875#ifndef SQLITE_OMIT_AUTHORIZATION
dan558814f2010-06-02 05:53:53 +00003876 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
danielk1977ab9b7032008-12-30 06:24:58 +00003877 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3878#endif
3879 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3880 sqlite3DbFree(pParse->db, zName);
3881 return;
3882 }
3883 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003884 }
3885}
3886
3887/*
drhdc3ff9c2004-08-18 02:10:15 +00003888** Make sure the TEMP database is open and available for use. Return
3889** the number of errors. Leave any error messages in the pParse structure.
3890*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003891int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003892 sqlite3 *db = pParse->db;
3893 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003894 int rc;
drh10a76c92010-01-26 01:25:26 +00003895 Btree *pBt;
drh33f4e022007-09-03 15:19:34 +00003896 static const int flags =
3897 SQLITE_OPEN_READWRITE |
3898 SQLITE_OPEN_CREATE |
3899 SQLITE_OPEN_EXCLUSIVE |
3900 SQLITE_OPEN_DELETEONCLOSE |
3901 SQLITE_OPEN_TEMP_DB;
3902
dan3a6d8ae2011-04-23 15:54:54 +00003903 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
drhdc3ff9c2004-08-18 02:10:15 +00003904 if( rc!=SQLITE_OK ){
3905 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3906 "file for storing temporary tables");
3907 pParse->rc = rc;
3908 return 1;
3909 }
drh10a76c92010-01-26 01:25:26 +00003910 db->aDb[1].pBt = pBt;
danielk197714db2662006-01-09 16:12:04 +00003911 assert( db->aDb[1].pSchema );
drh10a76c92010-01-26 01:25:26 +00003912 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
3913 db->mallocFailed = 1;
drh7c9c9862010-01-31 14:18:21 +00003914 return 1;
drh10a76c92010-01-26 01:25:26 +00003915 }
drhdc3ff9c2004-08-18 02:10:15 +00003916 }
3917 return 0;
3918}
3919
3920/*
drhaceb31b2014-02-08 01:40:27 +00003921** Record the fact that the schema cookie will need to be verified
3922** for database iDb. The code to actually verify the schema cookie
3923** will occur at the end of the top-level VDBE and will be generated
3924** later, by sqlite3FinishCoding().
drh001bbcb2003-03-19 03:14:00 +00003925*/
danielk19774adee202004-05-08 08:23:19 +00003926void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003927 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drhaceb31b2014-02-08 01:40:27 +00003928 sqlite3 *db = pToplevel->db;
drh80242052004-06-09 00:48:12 +00003929
drhaceb31b2014-02-08 01:40:27 +00003930 assert( iDb>=0 && iDb<db->nDb );
3931 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3932 assert( iDb<SQLITE_MAX_ATTACHED+2 );
3933 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drha7ab6d82014-07-21 15:44:39 +00003934 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
3935 DbMaskSet(pToplevel->cookieMask, iDb);
drhaceb31b2014-02-08 01:40:27 +00003936 pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
3937 if( !OMIT_TEMPDB && iDb==1 ){
3938 sqlite3OpenTempDatabase(pToplevel);
3939 }
drh001bbcb2003-03-19 03:14:00 +00003940 }
drh001bbcb2003-03-19 03:14:00 +00003941}
3942
3943/*
dan57966752011-04-09 17:32:58 +00003944** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
3945** attached database. Otherwise, invoke it for the database named zDb only.
3946*/
3947void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
3948 sqlite3 *db = pParse->db;
3949 int i;
3950 for(i=0; i<db->nDb; i++){
3951 Db *pDb = &db->aDb[i];
3952 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
3953 sqlite3CodeVerifySchema(pParse, i);
3954 }
3955 }
3956}
3957
3958/*
drh1c928532002-01-31 15:54:21 +00003959** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003960** might change the database.
3961**
3962** This routine starts a new transaction if we are not already within
3963** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003964** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003965** be set for operations that might fail (due to a constraint) part of
3966** the way through and which will need to undo some writes without having to
3967** rollback the whole transaction. For operations where all constraints
3968** can be checked before any changes are made to the database, it is never
3969** necessary to undo a write and the checkpoint should not be set.
drh1c928532002-01-31 15:54:21 +00003970*/
drh7f0f12e2004-05-21 13:39:50 +00003971void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
dan65a7cd12009-09-01 12:16:01 +00003972 Parse *pToplevel = sqlite3ParseToplevel(pParse);
drh80242052004-06-09 00:48:12 +00003973 sqlite3CodeVerifySchema(pParse, iDb);
drha7ab6d82014-07-21 15:44:39 +00003974 DbMaskSet(pToplevel->writeMask, iDb);
dane0af83a2009-09-08 19:15:01 +00003975 pToplevel->isMultiWrite |= setStatement;
3976}
3977
drhff738bc2009-09-24 00:09:58 +00003978/*
3979** Indicate that the statement currently under construction might write
3980** more than one entry (example: deleting one row then inserting another,
3981** inserting multiple rows in a table, or inserting a row and index entries.)
3982** If an abort occurs after some of these writes have completed, then it will
3983** be necessary to undo the completed writes.
3984*/
3985void sqlite3MultiWrite(Parse *pParse){
3986 Parse *pToplevel = sqlite3ParseToplevel(pParse);
3987 pToplevel->isMultiWrite = 1;
3988}
3989
dane0af83a2009-09-08 19:15:01 +00003990/*
drhff738bc2009-09-24 00:09:58 +00003991** The code generator calls this routine if is discovers that it is
3992** possible to abort a statement prior to completion. In order to
3993** perform this abort without corrupting the database, we need to make
3994** sure that the statement is protected by a statement transaction.
3995**
3996** Technically, we only need to set the mayAbort flag if the
3997** isMultiWrite flag was previously set. There is a time dependency
3998** such that the abort must occur after the multiwrite. This makes
3999** some statements involving the REPLACE conflict resolution algorithm
4000** go a little faster. But taking advantage of this time dependency
4001** makes it more difficult to prove that the code is correct (in
4002** particular, it prevents us from writing an effective
4003** implementation of sqlite3AssertMayAbort()) and so we have chosen
4004** to take the safe route and skip the optimization.
dane0af83a2009-09-08 19:15:01 +00004005*/
4006void sqlite3MayAbort(Parse *pParse){
4007 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4008 pToplevel->mayAbort = 1;
4009}
4010
4011/*
4012** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
4013** error. The onError parameter determines which (if any) of the statement
4014** and/or current transaction is rolled back.
4015*/
drhd91c1a12013-02-09 13:58:25 +00004016void sqlite3HaltConstraint(
4017 Parse *pParse, /* Parsing context */
4018 int errCode, /* extended error code */
4019 int onError, /* Constraint type */
4020 char *p4, /* Error message */
drhf9c8ce32013-11-05 13:33:55 +00004021 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
4022 u8 p5Errmsg /* P5_ErrMsg type */
drhd91c1a12013-02-09 13:58:25 +00004023){
dane0af83a2009-09-08 19:15:01 +00004024 Vdbe *v = sqlite3GetVdbe(pParse);
drhd91c1a12013-02-09 13:58:25 +00004025 assert( (errCode&0xff)==SQLITE_CONSTRAINT );
dane0af83a2009-09-08 19:15:01 +00004026 if( onError==OE_Abort ){
4027 sqlite3MayAbort(pParse);
danielk19771d850a72004-05-31 08:26:49 +00004028 }
drhd91c1a12013-02-09 13:58:25 +00004029 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
drhf9c8ce32013-11-05 13:33:55 +00004030 if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
4031}
4032
4033/*
4034** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
4035*/
4036void sqlite3UniqueConstraint(
4037 Parse *pParse, /* Parsing context */
4038 int onError, /* Constraint type */
4039 Index *pIdx /* The index that triggers the constraint */
4040){
4041 char *zErr;
4042 int j;
4043 StrAccum errMsg;
4044 Table *pTab = pIdx->pTable;
4045
drhc0490572015-05-02 11:45:53 +00004046 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
drhf9c8ce32013-11-05 13:33:55 +00004047 for(j=0; j<pIdx->nKeyCol; j++){
4048 char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
4049 if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
drha6353a32013-12-09 19:03:26 +00004050 sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
drhf9c8ce32013-11-05 13:33:55 +00004051 sqlite3StrAccumAppend(&errMsg, ".", 1);
drha6353a32013-12-09 19:03:26 +00004052 sqlite3StrAccumAppendAll(&errMsg, zCol);
drhf9c8ce32013-11-05 13:33:55 +00004053 }
4054 zErr = sqlite3StrAccumFinish(&errMsg);
4055 sqlite3HaltConstraint(pParse,
drh48dd1d82014-05-27 18:18:58 +00004056 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
4057 : SQLITE_CONSTRAINT_UNIQUE,
dan93889d92013-11-06 16:28:59 +00004058 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
drhf9c8ce32013-11-05 13:33:55 +00004059}
4060
4061
4062/*
4063** Code an OP_Halt due to non-unique rowid.
4064*/
4065void sqlite3RowidConstraint(
4066 Parse *pParse, /* Parsing context */
4067 int onError, /* Conflict resolution algorithm */
4068 Table *pTab /* The table with the non-unique rowid */
4069){
4070 char *zMsg;
4071 int rc;
4072 if( pTab->iPKey>=0 ){
4073 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
4074 pTab->aCol[pTab->iPKey].zName);
4075 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
4076 }else{
4077 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
4078 rc = SQLITE_CONSTRAINT_ROWID;
4079 }
4080 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
4081 P5_ConstraintUnique);
drh663fc632002-02-02 18:49:19 +00004082}
4083
drh4343fea2004-11-05 23:46:15 +00004084/*
4085** Check to see if pIndex uses the collating sequence pColl. Return
4086** true if it does and false if it does not.
4087*/
4088#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004089static int collationMatch(const char *zColl, Index *pIndex){
4090 int i;
drh04491712009-05-13 17:21:13 +00004091 assert( zColl!=0 );
danielk1977b3bf5562006-01-10 17:58:23 +00004092 for(i=0; i<pIndex->nColumn; i++){
4093 const char *z = pIndex->azColl[i];
drhbbbdc832013-10-22 18:01:40 +00004094 assert( z!=0 || pIndex->aiColumn[i]<0 );
4095 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
danielk1977b3bf5562006-01-10 17:58:23 +00004096 return 1;
4097 }
drh4343fea2004-11-05 23:46:15 +00004098 }
4099 return 0;
4100}
4101#endif
4102
4103/*
4104** Recompute all indices of pTab that use the collating sequence pColl.
4105** If pColl==0 then recompute all indices of pTab.
4106*/
4107#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004108static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004109 Index *pIndex; /* An index associated with pTab */
4110
4111 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00004112 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00004113 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
4114 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00004115 sqlite3RefillIndex(pParse, pIndex, -1);
4116 }
4117 }
4118}
4119#endif
4120
4121/*
4122** Recompute all indices of all tables in all databases where the
4123** indices use the collating sequence pColl. If pColl==0 then recompute
4124** all indices everywhere.
4125*/
4126#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00004127static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00004128 Db *pDb; /* A single database */
4129 int iDb; /* The database index number */
4130 sqlite3 *db = pParse->db; /* The database connection */
4131 HashElem *k; /* For looping over tables in pDb */
4132 Table *pTab; /* A table in the database */
4133
drh21206082011-04-04 18:22:02 +00004134 assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
drh4343fea2004-11-05 23:46:15 +00004135 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00004136 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00004137 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00004138 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00004139 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00004140 }
4141 }
4142}
4143#endif
4144
4145/*
drheee46cf2004-11-06 00:02:48 +00004146** Generate code for the REINDEX command.
4147**
4148** REINDEX -- 1
4149** REINDEX <collation> -- 2
4150** REINDEX ?<database>.?<tablename> -- 3
4151** REINDEX ?<database>.?<indexname> -- 4
4152**
4153** Form 1 causes all indices in all attached databases to be rebuilt.
4154** Form 2 rebuilds all indices in all databases that use the named
4155** collating function. Forms 3 and 4 rebuild the named index or all
4156** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00004157*/
4158#ifndef SQLITE_OMIT_REINDEX
4159void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
4160 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
4161 char *z; /* Name of a table or index */
4162 const char *zDb; /* Name of the database */
4163 Table *pTab; /* A table in the database */
4164 Index *pIndex; /* An index associated with pTab */
4165 int iDb; /* The database index number */
4166 sqlite3 *db = pParse->db; /* The database connection */
4167 Token *pObjName; /* Name of the table or index to be reindexed */
4168
danielk197733a5edc2005-01-27 00:22:02 +00004169 /* Read the database schema. If an error occurs, leave an error message
4170 ** and code in pParse and return NULL. */
4171 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00004172 return;
danielk197733a5edc2005-01-27 00:22:02 +00004173 }
4174
drh8af73d42009-05-13 22:58:28 +00004175 if( pName1==0 ){
drh4343fea2004-11-05 23:46:15 +00004176 reindexDatabases(pParse, 0);
4177 return;
drhd3001712009-05-12 17:46:53 +00004178 }else if( NEVER(pName2==0) || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00004179 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00004180 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00004181 zColl = sqlite3NameFromToken(pParse->db, pName1);
4182 if( !zColl ) return;
drhc4a64fa2009-05-11 20:53:28 +00004183 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh4343fea2004-11-05 23:46:15 +00004184 if( pColl ){
drhd3001712009-05-12 17:46:53 +00004185 reindexDatabases(pParse, zColl);
4186 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004187 return;
4188 }
drh633e6d52008-07-28 19:34:53 +00004189 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00004190 }
4191 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
4192 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00004193 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00004194 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00004195 zDb = db->aDb[iDb].zName;
4196 pTab = sqlite3FindTable(db, z, zDb);
4197 if( pTab ){
4198 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00004199 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004200 return;
4201 }
4202 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00004203 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00004204 if( pIndex ){
4205 sqlite3BeginWriteOperation(pParse, 0, iDb);
4206 sqlite3RefillIndex(pParse, pIndex, -1);
4207 return;
4208 }
4209 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
4210}
4211#endif
danielk1977b3bf5562006-01-10 17:58:23 +00004212
4213/*
drh2ec2fb22013-11-06 19:59:23 +00004214** Return a KeyInfo structure that is appropriate for the given Index.
danielk1977b3bf5562006-01-10 17:58:23 +00004215**
drh2ec2fb22013-11-06 19:59:23 +00004216** The KeyInfo structure for an index is cached in the Index object.
4217** So there might be multiple references to the returned pointer. The
4218** caller should not try to modify the KeyInfo object.
4219**
4220** The caller should invoke sqlite3KeyInfoUnref() on the returned object
4221** when it has finished using it.
danielk1977b3bf5562006-01-10 17:58:23 +00004222*/
drh2ec2fb22013-11-06 19:59:23 +00004223KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
drh18b67f32014-12-12 00:20:37 +00004224 int i;
4225 int nCol = pIdx->nColumn;
4226 int nKey = pIdx->nKeyCol;
4227 KeyInfo *pKey;
drh2ec2fb22013-11-06 19:59:23 +00004228 if( pParse->nErr ) return 0;
drh18b67f32014-12-12 00:20:37 +00004229 if( pIdx->uniqNotNull ){
4230 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
4231 }else{
4232 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
drh41e13e12013-11-07 14:09:39 +00004233 }
drh18b67f32014-12-12 00:20:37 +00004234 if( pKey ){
4235 assert( sqlite3KeyInfoIsWriteable(pKey) );
4236 for(i=0; i<nCol; i++){
4237 char *zColl = pIdx->azColl[i];
4238 assert( zColl!=0 );
4239 pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
4240 sqlite3LocateCollSeq(pParse, zColl);
4241 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
drh2ec2fb22013-11-06 19:59:23 +00004242 }
drh18b67f32014-12-12 00:20:37 +00004243 if( pParse->nErr ){
4244 sqlite3KeyInfoUnref(pKey);
4245 pKey = 0;
danielk1977b3bf5562006-01-10 17:58:23 +00004246 }
danielk1977b3bf5562006-01-10 17:58:23 +00004247 }
drh18b67f32014-12-12 00:20:37 +00004248 return pKey;
danielk1977b3bf5562006-01-10 17:58:23 +00004249}
drh8b471862014-01-11 13:22:17 +00004250
4251#ifndef SQLITE_OMIT_CTE
dan7d562db2014-01-11 19:19:36 +00004252/*
4253** This routine is invoked once per CTE by the parser while parsing a
4254** WITH clause.
drh8b471862014-01-11 13:22:17 +00004255*/
dan7d562db2014-01-11 19:19:36 +00004256With *sqlite3WithAdd(
drh8b471862014-01-11 13:22:17 +00004257 Parse *pParse, /* Parsing context */
dan7d562db2014-01-11 19:19:36 +00004258 With *pWith, /* Existing WITH clause, or NULL */
drh8b471862014-01-11 13:22:17 +00004259 Token *pName, /* Name of the common-table */
dan4e9119d2014-01-13 15:12:23 +00004260 ExprList *pArglist, /* Optional column name list for the table */
drh8b471862014-01-11 13:22:17 +00004261 Select *pQuery /* Query used to initialize the table */
4262){
dan4e9119d2014-01-13 15:12:23 +00004263 sqlite3 *db = pParse->db;
4264 With *pNew;
4265 char *zName;
4266
4267 /* Check that the CTE name is unique within this WITH clause. If
4268 ** not, store an error in the Parse structure. */
4269 zName = sqlite3NameFromToken(pParse->db, pName);
4270 if( zName && pWith ){
4271 int i;
4272 for(i=0; i<pWith->nCte; i++){
4273 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
drh727a99f2014-01-16 21:59:51 +00004274 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
dan4e9119d2014-01-13 15:12:23 +00004275 }
4276 }
4277 }
4278
4279 if( pWith ){
4280 int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
4281 pNew = sqlite3DbRealloc(db, pWith, nByte);
4282 }else{
4283 pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
4284 }
4285 assert( zName!=0 || pNew==0 );
dana9f5c132014-01-13 16:36:40 +00004286 assert( db->mallocFailed==0 || pNew==0 );
dan4e9119d2014-01-13 15:12:23 +00004287
4288 if( pNew==0 ){
dan4e9119d2014-01-13 15:12:23 +00004289 sqlite3ExprListDelete(db, pArglist);
4290 sqlite3SelectDelete(db, pQuery);
4291 sqlite3DbFree(db, zName);
dana9f5c132014-01-13 16:36:40 +00004292 pNew = pWith;
dan4e9119d2014-01-13 15:12:23 +00004293 }else{
4294 pNew->a[pNew->nCte].pSelect = pQuery;
4295 pNew->a[pNew->nCte].pCols = pArglist;
4296 pNew->a[pNew->nCte].zName = zName;
danf2655fe2014-01-16 21:02:02 +00004297 pNew->a[pNew->nCte].zErr = 0;
dan4e9119d2014-01-13 15:12:23 +00004298 pNew->nCte++;
4299 }
4300
4301 return pNew;
drh8b471862014-01-11 13:22:17 +00004302}
4303
dan7d562db2014-01-11 19:19:36 +00004304/*
4305** Free the contents of the With object passed as the second argument.
drh8b471862014-01-11 13:22:17 +00004306*/
dan7d562db2014-01-11 19:19:36 +00004307void sqlite3WithDelete(sqlite3 *db, With *pWith){
dan4e9119d2014-01-13 15:12:23 +00004308 if( pWith ){
4309 int i;
4310 for(i=0; i<pWith->nCte; i++){
4311 struct Cte *pCte = &pWith->a[i];
4312 sqlite3ExprListDelete(db, pCte->pCols);
4313 sqlite3SelectDelete(db, pCte->pSelect);
4314 sqlite3DbFree(db, pCte->zName);
4315 }
4316 sqlite3DbFree(db, pWith);
4317 }
drh8b471862014-01-11 13:22:17 +00004318}
4319#endif /* !defined(SQLITE_OMIT_CTE) */