blob: 27ded7ebb08293822798f926294e9f8b415c0342 [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
drhbed86902000-06-02 13:27:59 +000024**
danielk197778ca0e72009-01-20 16:53:39 +000025** $Id: build.c,v 1.512 2009/01/20 16:53:40 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
28
29/*
drhe0bc4042002-06-25 01:09:11 +000030** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000031** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000032*/
danielk19774adee202004-05-08 08:23:19 +000033void sqlite3BeginParse(Parse *pParse, int explainFlag){
drh1bd10f82008-12-10 21:19:56 +000034 pParse->explain = (u8)explainFlag;
drh7c972de2003-09-06 22:18:07 +000035 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000036}
37
danielk1977c00da102006-01-07 13:21:04 +000038#ifndef SQLITE_OMIT_SHARED_CACHE
39/*
40** The TableLock structure is only used by the sqlite3TableLock() and
41** codeTableLocks() functions.
42*/
43struct TableLock {
drhd698bc12006-03-23 23:33:26 +000044 int iDb; /* The database containing the table to be locked */
45 int iTab; /* The root page of the table to be locked */
46 u8 isWriteLock; /* True for write lock. False for a read lock */
47 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000048};
49
50/*
drhd698bc12006-03-23 23:33:26 +000051** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000052**
drhd698bc12006-03-23 23:33:26 +000053** The table to be locked has root page iTab and is found in database iDb.
54** A read or a write lock can be taken depending on isWritelock.
55**
56** This routine just records the fact that the lock is desired. The
57** code to make the lock occur is generated by a later call to
58** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000059*/
60void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000061 Parse *pParse, /* Parsing context */
62 int iDb, /* Index of the database containing the table to lock */
63 int iTab, /* Root page number of the table to be locked */
64 u8 isWriteLock, /* True for a write lock */
65 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000066){
67 int i;
68 int nBytes;
69 TableLock *p;
danielk1977c00da102006-01-07 13:21:04 +000070
drhe53831d2007-08-17 01:14:38 +000071 if( iDb<0 ){
danielk1977c00da102006-01-07 13:21:04 +000072 return;
73 }
74
75 for(i=0; i<pParse->nTableLock; i++){
76 p = &pParse->aTableLock[i];
77 if( p->iDb==iDb && p->iTab==iTab ){
78 p->isWriteLock = (p->isWriteLock || isWriteLock);
79 return;
80 }
81 }
82
83 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
drh17435752007-08-16 04:30:38 +000084 pParse->aTableLock =
85 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
danielk1977c00da102006-01-07 13:21:04 +000086 if( pParse->aTableLock ){
87 p = &pParse->aTableLock[pParse->nTableLock++];
88 p->iDb = iDb;
89 p->iTab = iTab;
90 p->isWriteLock = isWriteLock;
91 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000092 }else{
93 pParse->nTableLock = 0;
94 pParse->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000095 }
96}
97
98/*
99** Code an OP_TableLock instruction for each table locked by the
100** statement (configured by calls to sqlite3TableLock()).
101*/
102static void codeTableLocks(Parse *pParse){
103 int i;
104 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000105
106 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
107 return;
108 }
109
110 for(i=0; i<pParse->nTableLock; i++){
111 TableLock *p = &pParse->aTableLock[i];
112 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000113 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
114 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000115 }
116}
117#else
118 #define codeTableLocks(x)
119#endif
120
drhe0bc4042002-06-25 01:09:11 +0000121/*
drh75897232000-05-29 14:26:00 +0000122** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000123** parsed and a VDBE program to execute that statement has been
124** prepared. This routine puts the finishing touches on the
125** VDBE program and resets the pParse structure for the next
126** parse.
drh75897232000-05-29 14:26:00 +0000127**
128** Note that if an error occurred, it might be the case that
129** no VDBE code was generated.
130*/
drh80242052004-06-09 00:48:12 +0000131void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000132 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000133 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000134
drh17435752007-08-16 04:30:38 +0000135 db = pParse->db;
136 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000137 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000138 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000139
drh80242052004-06-09 00:48:12 +0000140 /* Begin by generating some termination code at the end of the
141 ** vdbe program
142 */
drh80242052004-06-09 00:48:12 +0000143 v = sqlite3GetVdbe(pParse);
144 if( v ){
drh66a51672008-01-03 00:01:23 +0000145 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000146
147 /* The cookie mask contains one bit for each database file open.
148 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
149 ** set for each database that is used. Generate code to start a
150 ** transaction on each used database and to verify the schema cookie
151 ** on each used database.
152 */
drhc275b4e2004-07-19 17:25:24 +0000153 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000154 u32 mask;
drh26e4a8b2008-05-01 17:16:52 +0000155 int iDb;
drhd654be82005-09-20 17:42:23 +0000156 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000157 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
158 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000159 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000160 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
161 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +0000162 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000163#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000164 {
165 int i;
166 for(i=0; i<pParse->nVtabLock; i++){
167 char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
168 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
169 }
170 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000171 }
172#endif
danielk1977c00da102006-01-07 13:21:04 +0000173
174 /* Once all the cookies have been verified and transactions opened,
175 ** obtain the required table-locks. This is a no-op unless the
176 ** shared-cache feature is enabled.
177 */
178 codeTableLocks(pParse);
drh66a51672008-01-03 00:01:23 +0000179 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000180 }
drh80242052004-06-09 00:48:12 +0000181
drh19e2d372005-08-29 23:00:03 +0000182#ifndef SQLITE_OMIT_TRACE
drh949f9cd2008-01-12 21:35:57 +0000183 if( !db->init.busy ){
184 /* Change the P4 argument of the first opcode (which will always be
185 ** an OP_Trace) to be the complete text of the current SQL statement.
186 */
187 VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
188 if( pOp && pOp->opcode==OP_Trace ){
drh1bd10f82008-12-10 21:19:56 +0000189 sqlite3VdbeChangeP4(v, 0, pParse->zSql,
190 (int)(pParse->zTail - pParse->zSql));
drh949f9cd2008-01-12 21:35:57 +0000191 }
192 }
drh19e2d372005-08-29 23:00:03 +0000193#endif /* SQLITE_OMIT_TRACE */
drh71c697e2004-08-08 23:39:19 +0000194 }
195
drh3f7d4e42004-07-24 14:35:58 +0000196
drh80242052004-06-09 00:48:12 +0000197 /* Get the VDBE program ready for execution
198 */
drh17435752007-08-16 04:30:38 +0000199 if( v && pParse->nErr==0 && !db->mallocFailed ){
drhcf1023c2007-05-08 20:59:49 +0000200#ifdef SQLITE_DEBUG
drhb86ccfb2003-01-28 23:13:10 +0000201 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000202 sqlite3VdbeTrace(v, trace);
drhcf1023c2007-05-08 20:59:49 +0000203#endif
drh2f7794c2008-04-01 03:27:39 +0000204 assert( pParse->disableColCache==0 ); /* Disables and re-enables match */
drh290c1942004-08-21 17:54:45 +0000205 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
drh13449892005-09-07 21:22:45 +0000206 pParse->nTab+3, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000207 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000208 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000209 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000210 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000211 }
drha226d052002-09-25 19:04:07 +0000212 pParse->nTab = 0;
213 pParse->nMem = 0;
214 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000215 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000216 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000217 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000218}
219
220/*
drh205f48e2004-11-05 00:43:11 +0000221** Run the parser and code generator recursively in order to generate
222** code for the SQL statement given onto the end of the pParse context
223** currently under construction. When the parser is run recursively
224** this way, the final OP_Halt is not appended and other initialization
225** and finalization steps are omitted because those are handling by the
226** outermost parser.
227**
228** Not everything is nestable. This facility is designed to permit
229** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000230** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000231*/
232void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
233 va_list ap;
234 char *zSql;
drhfb45d8c2008-07-08 00:06:49 +0000235 char *zErrMsg = 0;
drh633e6d52008-07-28 19:34:53 +0000236 sqlite3 *db = pParse->db;
drhf1974842004-11-05 03:56:00 +0000237# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
238 char saveBuf[SAVE_SZ];
239
drh205f48e2004-11-05 00:43:11 +0000240 if( pParse->nErr ) return;
241 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
242 va_start(ap, zFormat);
drh633e6d52008-07-28 19:34:53 +0000243 zSql = sqlite3VMPrintf(db, zFormat, ap);
drh205f48e2004-11-05 00:43:11 +0000244 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000245 if( zSql==0 ){
246 return; /* A malloc must have failed */
247 }
drh205f48e2004-11-05 00:43:11 +0000248 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000249 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
250 memset(&pParse->nVar, 0, SAVE_SZ);
drhfb45d8c2008-07-08 00:06:49 +0000251 sqlite3RunParser(pParse, zSql, &zErrMsg);
drh633e6d52008-07-28 19:34:53 +0000252 sqlite3DbFree(db, zErrMsg);
253 sqlite3DbFree(db, zSql);
drhf1974842004-11-05 03:56:00 +0000254 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000255 pParse->nested--;
256}
257
258/*
danielk19778a414492004-06-29 08:59:35 +0000259** Locate the in-memory structure that describes a particular database
260** table given the name of that table and (optionally) the name of the
261** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000262**
danielk19778a414492004-06-29 08:59:35 +0000263** If zDatabase is 0, all databases are searched for the table and the
264** first matching table is returned. (No checking for duplicate table
265** names is done.) The search order is TEMP first, then MAIN, then any
266** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000267**
danielk19774adee202004-05-08 08:23:19 +0000268** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000269*/
drh9bb575f2004-09-06 17:24:11 +0000270Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000271 Table *p = 0;
272 int i;
drh0a687d12008-07-08 14:52:07 +0000273 int nName;
drh645f63e2004-06-22 13:22:40 +0000274 assert( zName!=0 );
drh0a687d12008-07-08 14:52:07 +0000275 nName = sqlite3Strlen(db, zName) + 1;
danielk197753c0f742005-03-29 03:10:59 +0000276 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000277 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000278 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
drh0a687d12008-07-08 14:52:07 +0000279 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
drhd24cc422003-03-27 12:51:24 +0000280 if( p ) break;
281 }
drh74e24cd2002-01-09 03:19:59 +0000282 return p;
drh75897232000-05-29 14:26:00 +0000283}
284
285/*
danielk19778a414492004-06-29 08:59:35 +0000286** Locate the in-memory structure that describes a particular database
287** table given the name of that table and (optionally) the name of the
288** database containing the table. Return NULL if not found. Also leave an
289** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000290**
danielk19778a414492004-06-29 08:59:35 +0000291** The difference between this routine and sqlite3FindTable() is that this
292** routine leaves an error message in pParse->zErrMsg where
293** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000294*/
drhca424112008-01-25 15:04:48 +0000295Table *sqlite3LocateTable(
296 Parse *pParse, /* context in which to report errors */
297 int isView, /* True if looking for a VIEW rather than a TABLE */
298 const char *zName, /* Name of the table we are looking for */
299 const char *zDbase /* Name of the database. Might be NULL */
300){
drha69d9162003-04-17 22:57:53 +0000301 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000302
danielk19778a414492004-06-29 08:59:35 +0000303 /* Read the database schema. If an error occurs, leave an error message
304 ** and code in pParse and return NULL. */
305 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
306 return 0;
307 }
308
danielk19774adee202004-05-08 08:23:19 +0000309 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000310 if( p==0 ){
drhca424112008-01-25 15:04:48 +0000311 const char *zMsg = isView ? "no such view" : "no such table";
danielk19778a414492004-06-29 08:59:35 +0000312 if( zDbase ){
drhca424112008-01-25 15:04:48 +0000313 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000314 }else{
drhca424112008-01-25 15:04:48 +0000315 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
drha69d9162003-04-17 22:57:53 +0000316 }
drha6ecd332004-06-10 00:29:09 +0000317 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000318 }
319 return p;
320}
321
322/*
323** Locate the in-memory structure that describes
324** a particular index given the name of that index
325** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000326** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000327**
328** If zDatabase is 0, all databases are searched for the
329** table and the first matching index is returned. (No checking
330** for duplicate index names is done.) The search order is
331** TEMP first, then MAIN, then any auxiliary databases added
332** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000333*/
drh9bb575f2004-09-06 17:24:11 +0000334Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000335 Index *p = 0;
336 int i;
drh0a687d12008-07-08 14:52:07 +0000337 int nName = sqlite3Strlen(db, zName)+1;
danielk197753c0f742005-03-29 03:10:59 +0000338 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000339 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000340 Schema *pSchema = db->aDb[j].pSchema;
danielk19774adee202004-05-08 08:23:19 +0000341 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000342 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
343 if( pSchema ){
drh0a687d12008-07-08 14:52:07 +0000344 p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
danielk1977da184232006-01-05 11:34:32 +0000345 }
drhd24cc422003-03-27 12:51:24 +0000346 if( p ) break;
347 }
drh74e24cd2002-01-09 03:19:59 +0000348 return p;
drh75897232000-05-29 14:26:00 +0000349}
350
351/*
drh956bc922004-07-24 17:38:29 +0000352** Reclaim the memory used by an index
353*/
354static void freeIndex(Index *p){
drh633e6d52008-07-28 19:34:53 +0000355 sqlite3 *db = p->pTable->db;
356 sqlite3DbFree(db, p->zColAff);
357 sqlite3DbFree(db, p);
drh956bc922004-07-24 17:38:29 +0000358}
359
360/*
drh75897232000-05-29 14:26:00 +0000361** Remove the given index from the index hash table, and free
362** its memory structures.
363**
drhd229ca92002-01-09 13:30:41 +0000364** The index is removed from the database hash tables but
365** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000366** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000367*/
drh74161702006-02-24 02:53:49 +0000368static void sqliteDeleteIndex(Index *p){
drhd229ca92002-01-09 13:30:41 +0000369 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000370 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000371
drhea678832008-12-10 19:26:22 +0000372 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
373 sqlite3Strlen30(zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000374 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000375 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000376}
377
378/*
drhc96d8532005-05-03 12:30:33 +0000379** For the index called zIdxName which is found in the database iDb,
380** unlike that index from its Table then remove the index from
381** the index hash table and free all memory structures associated
382** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000383*/
drh9bb575f2004-09-06 17:24:11 +0000384void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000385 Index *pIndex;
386 int len;
danielk1977da184232006-01-05 11:34:32 +0000387 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000388
drh0a687d12008-07-08 14:52:07 +0000389 len = sqlite3Strlen(db, zIdxName);
danielk1977da184232006-01-05 11:34:32 +0000390 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
drh956bc922004-07-24 17:38:29 +0000391 if( pIndex ){
392 if( pIndex->pTable->pIndex==pIndex ){
393 pIndex->pTable->pIndex = pIndex->pNext;
394 }else{
395 Index *p;
396 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
397 if( p && p->pNext==pIndex ){
398 p->pNext = pIndex->pNext;
399 }
drh5e00f6c2001-09-13 13:46:56 +0000400 }
drh956bc922004-07-24 17:38:29 +0000401 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000402 }
drh956bc922004-07-24 17:38:29 +0000403 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000404}
405
406/*
drhe0bc4042002-06-25 01:09:11 +0000407** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000408** a single database. This routine is called to reclaim memory
409** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000410** if there were schema changes during the transaction or if a
411** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000412**
413** If iDb<=0 then reset the internal schema tables for all database
414** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000415** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000416*/
drh9bb575f2004-09-06 17:24:11 +0000417void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000418 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000419 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000420
421 if( iDb==0 ){
422 sqlite3BtreeEnterAll(db);
423 }
drh1c2d8412003-03-31 00:30:47 +0000424 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000425 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000426 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000427 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000428 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000429 }
drh1c2d8412003-03-31 00:30:47 +0000430 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000431 }
drh1c2d8412003-03-31 00:30:47 +0000432 assert( iDb==0 );
433 db->flags &= ~SQLITE_InternChanges;
danielk19774eab8b72007-12-27 15:12:16 +0000434 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000435
436 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000437 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000438 ** opportunity to do this here since we have just deleted all of the
439 ** schema hash tables and therefore do not have to make any changes
440 ** to any of those tables.
441 */
drh4d189ca2004-02-12 18:46:38 +0000442 for(i=0; i<db->nDb; i++){
443 struct Db *pDb = &db->aDb[i];
444 if( pDb->pBt==0 ){
445 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
446 pDb->pAux = 0;
447 }
448 }
drh1c2d8412003-03-31 00:30:47 +0000449 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000450 struct Db *pDb = &db->aDb[i];
451 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000452 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000453 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000454 continue;
455 }
456 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000457 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000458 }
drh8bf8dc92003-05-17 17:35:10 +0000459 j++;
drh1c2d8412003-03-31 00:30:47 +0000460 }
461 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
462 db->nDb = j;
463 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
464 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000465 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000466 db->aDb = db->aDbStatic;
467 }
drhe0bc4042002-06-25 01:09:11 +0000468}
469
470/*
drhe0bc4042002-06-25 01:09:11 +0000471** This routine is called when a commit occurs.
472*/
drh9bb575f2004-09-06 17:24:11 +0000473void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000474 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000475}
476
477/*
drh956bc922004-07-24 17:38:29 +0000478** Clear the column names from a table or view.
479*/
480static void sqliteResetColumnNames(Table *pTable){
481 int i;
482 Column *pCol;
drh633e6d52008-07-28 19:34:53 +0000483 sqlite3 *db = pTable->db;
drh956bc922004-07-24 17:38:29 +0000484 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000485 if( (pCol = pTable->aCol)!=0 ){
486 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000487 sqlite3DbFree(db, pCol->zName);
488 sqlite3ExprDelete(db, pCol->pDflt);
489 sqlite3DbFree(db, pCol->zType);
490 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000491 }
drh633e6d52008-07-28 19:34:53 +0000492 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000493 }
drh956bc922004-07-24 17:38:29 +0000494 pTable->aCol = 0;
495 pTable->nCol = 0;
496}
497
498/*
drh75897232000-05-29 14:26:00 +0000499** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000500** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000501**
502** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000503** the table data structure from the hash table. Nor does it remove
504** foreign keys from the sqlite.aFKey hash table. But it does destroy
505** memory structures of the indices and foreign keys associated with
506** the table.
drh75897232000-05-29 14:26:00 +0000507*/
danielk1977a04a34f2007-04-16 15:06:25 +0000508void sqlite3DeleteTable(Table *pTable){
drh75897232000-05-29 14:26:00 +0000509 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000510 FKey *pFKey, *pNextFKey;
drh633e6d52008-07-28 19:34:53 +0000511 sqlite3 *db;
drhc2eef3b2002-08-31 18:53:06 +0000512
drh75897232000-05-29 14:26:00 +0000513 if( pTable==0 ) return;
drh633e6d52008-07-28 19:34:53 +0000514 db = pTable->db;
drhc2eef3b2002-08-31 18:53:06 +0000515
drhed8a3bb2005-06-06 21:19:56 +0000516 /* Do not delete the table until the reference count reaches zero. */
517 pTable->nRef--;
518 if( pTable->nRef>0 ){
519 return;
520 }
521 assert( pTable->nRef==0 );
522
drhc2eef3b2002-08-31 18:53:06 +0000523 /* Delete all indices associated with this table
524 */
525 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
526 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000527 assert( pIndex->pSchema==pTable->pSchema );
drh74161702006-02-24 02:53:49 +0000528 sqliteDeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000529 }
530
danielk1977576ec6b2005-01-21 11:55:25 +0000531#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000532 /* Delete all foreign keys associated with this table. The keys
danielk1977a04a34f2007-04-16 15:06:25 +0000533 ** should have already been unlinked from the pSchema->aFKey hash table
drhc2eef3b2002-08-31 18:53:06 +0000534 */
535 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
536 pNextFKey = pFKey->pNextFrom;
danielk1977da184232006-01-05 11:34:32 +0000537 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
drhea678832008-12-10 19:26:22 +0000538 pFKey->zTo, sqlite3Strlen30(pFKey->zTo)+1)!=pFKey );
drh633e6d52008-07-28 19:34:53 +0000539 sqlite3DbFree(db, pFKey);
drhc2eef3b2002-08-31 18:53:06 +0000540 }
danielk1977576ec6b2005-01-21 11:55:25 +0000541#endif
drhc2eef3b2002-08-31 18:53:06 +0000542
543 /* Delete the Table structure itself.
544 */
drh956bc922004-07-24 17:38:29 +0000545 sqliteResetColumnNames(pTable);
drh633e6d52008-07-28 19:34:53 +0000546 sqlite3DbFree(db, pTable->zName);
547 sqlite3DbFree(db, pTable->zColAff);
548 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000549#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000550 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000551#endif
drhb9bb7c12006-06-11 23:41:55 +0000552 sqlite3VtabClear(pTable);
drh633e6d52008-07-28 19:34:53 +0000553 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000554}
555
556/*
drh5edc3122001-09-13 21:53:09 +0000557** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000558** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000559*/
drh9bb575f2004-09-06 17:24:11 +0000560void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000561 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000562 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000563 Db *pDb;
564
drhd229ca92002-01-09 13:30:41 +0000565 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000566 assert( iDb>=0 && iDb<db->nDb );
567 assert( zTabName && zTabName[0] );
568 pDb = &db->aDb[iDb];
drhea678832008-12-10 19:26:22 +0000569 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
570 sqlite3Strlen30(zTabName)+1,0);
drh956bc922004-07-24 17:38:29 +0000571 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000572#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000573 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
drhea678832008-12-10 19:26:22 +0000574 int nTo = sqlite3Strlen30(pF1->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +0000575 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
drh956bc922004-07-24 17:38:29 +0000576 if( pF2==pF1 ){
danielk1977da184232006-01-05 11:34:32 +0000577 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
drh956bc922004-07-24 17:38:29 +0000578 }else{
579 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
580 if( pF2 ){
581 pF2->pNextTo = pF1->pNextTo;
582 }
drhc2eef3b2002-08-31 18:53:06 +0000583 }
584 }
danielk1977576ec6b2005-01-21 11:55:25 +0000585#endif
danielk1977a04a34f2007-04-16 15:06:25 +0000586 sqlite3DeleteTable(p);
drhc2eef3b2002-08-31 18:53:06 +0000587 }
drh956bc922004-07-24 17:38:29 +0000588 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000589}
590
591/*
drha99db3b2004-06-19 14:49:12 +0000592** Given a token, return a string that consists of the text of that
593** token with any quotations removed. Space to hold the returned string
594** is obtained from sqliteMalloc() and must be freed by the calling
595** function.
drh75897232000-05-29 14:26:00 +0000596**
drhc96d8532005-05-03 12:30:33 +0000597** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000598** are not \000 terminated and are not persistent. The returned string
599** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000600*/
drh17435752007-08-16 04:30:38 +0000601char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000602 char *zName;
603 if( pName ){
drh17435752007-08-16 04:30:38 +0000604 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drha99db3b2004-06-19 14:49:12 +0000605 sqlite3Dequote(zName);
606 }else{
607 zName = 0;
608 }
drh75897232000-05-29 14:26:00 +0000609 return zName;
610}
611
612/*
danielk1977cbb18d22004-05-28 11:37:27 +0000613** Open the sqlite_master table stored in database number iDb for
614** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000615*/
danielk1977c00da102006-01-07 13:21:04 +0000616void sqlite3OpenMasterTable(Parse *p, int iDb){
617 Vdbe *v = sqlite3GetVdbe(p);
618 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977cd3e8f72008-03-25 09:47:35 +0000619 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
danielk1977207872a2008-01-03 07:54:23 +0000620 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
drhe0bc4042002-06-25 01:09:11 +0000621}
622
623/*
danielk1977cbb18d22004-05-28 11:37:27 +0000624** The token *pName contains the name of a database (either "main" or
625** "temp" or the name of an attached db). This routine returns the
626** index of the named database in db->aDb[], or -1 if the named db
627** does not exist.
628*/
drhff2d5ea2005-07-23 00:41:48 +0000629int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000630 int i = -1; /* Database number */
drh1bd10f82008-12-10 21:19:56 +0000631 int n; /* Number of characters in the name */
drh73c42a12004-11-20 18:13:10 +0000632 Db *pDb; /* A database whose name space is being searched */
633 char *zName; /* Name we are searching for */
634
drh17435752007-08-16 04:30:38 +0000635 zName = sqlite3NameFromToken(db, pName);
drh73c42a12004-11-20 18:13:10 +0000636 if( zName ){
drhea678832008-12-10 19:26:22 +0000637 n = sqlite3Strlen30(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000638 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
drhea678832008-12-10 19:26:22 +0000639 if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
danielk197753c0f742005-03-29 03:10:59 +0000640 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000641 break;
drh73c42a12004-11-20 18:13:10 +0000642 }
danielk1977cbb18d22004-05-28 11:37:27 +0000643 }
drh633e6d52008-07-28 19:34:53 +0000644 sqlite3DbFree(db, zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000645 }
danielk1977576ec6b2005-01-21 11:55:25 +0000646 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000647}
648
drh0e3d7472004-06-19 17:33:07 +0000649/* The table or view or trigger name is passed to this routine via tokens
650** pName1 and pName2. If the table name was fully qualified, for example:
651**
652** CREATE TABLE xxx.yyy (...);
653**
654** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
655** the table name is not fully qualified, i.e.:
656**
657** CREATE TABLE yyy(...);
658**
659** Then pName1 is set to "yyy" and pName2 is "".
660**
661** This routine sets the *ppUnqual pointer to point at the token (pName1 or
662** pName2) that stores the unqualified table name. The index of the
663** database "xxx" is returned.
664*/
danielk1977ef2cb632004-05-29 02:37:19 +0000665int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000666 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000667 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000668 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
669 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000670){
drh0e3d7472004-06-19 17:33:07 +0000671 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000672 sqlite3 *db = pParse->db;
673
674 if( pName2 && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000675 if( db->init.busy ) {
676 sqlite3ErrorMsg(pParse, "corrupt database");
677 pParse->nErr++;
678 return -1;
679 }
danielk1977cbb18d22004-05-28 11:37:27 +0000680 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000681 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000682 if( iDb<0 ){
683 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
684 pParse->nErr++;
685 return -1;
686 }
687 }else{
688 assert( db->init.iDb==0 || db->init.busy );
689 iDb = db->init.iDb;
690 *pUnqual = pName1;
691 }
692 return iDb;
693}
694
695/*
danielk1977d8123362004-06-12 09:25:12 +0000696** This routine is used to check if the UTF-8 string zName is a legal
697** unqualified name for a new schema object (table, index, view or
698** trigger). All names are legal except those that begin with the string
699** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
700** is reserved for internal use.
701*/
702int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000703 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000704 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000705 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000706 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
707 return SQLITE_ERROR;
708 }
709 return SQLITE_OK;
710}
711
712/*
drh75897232000-05-29 14:26:00 +0000713** Begin constructing a new table representation in memory. This is
714** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000715** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000716** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000717** flag is true if the table should be stored in the auxiliary database
718** file instead of in the main database file. This is normally the case
719** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000720** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000721**
drhf57b3392001-10-08 13:22:32 +0000722** The new table record is initialized and put in pParse->pNewTable.
723** As more of the CREATE TABLE statement is parsed, additional action
724** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000725** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000726** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000727*/
danielk19774adee202004-05-08 08:23:19 +0000728void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000729 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000730 Token *pName1, /* First part of the name of the table or view */
731 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000732 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000733 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000734 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000735 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000736){
drh75897232000-05-29 14:26:00 +0000737 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000738 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000739 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000740 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000741 int iDb; /* Database number to create the table in */
742 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000743
danielk1977cbb18d22004-05-28 11:37:27 +0000744 /* The table or view name to create is passed to this routine via tokens
745 ** pName1 and pName2. If the table name was fully qualified, for example:
746 **
747 ** CREATE TABLE xxx.yyy (...);
748 **
749 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
750 ** the table name is not fully qualified, i.e.:
751 **
752 ** CREATE TABLE yyy(...);
753 **
754 ** Then pName1 is set to "yyy" and pName2 is "".
755 **
756 ** The call below sets the pName pointer to point at the token (pName1 or
757 ** pName2) that stores the unqualified table name. The variable iDb is
758 ** set to the index of the database that the table or view is to be
759 ** created in.
760 */
danielk1977ef2cb632004-05-29 02:37:19 +0000761 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000762 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000763 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000764 /* If creating a temp table, the name may not be qualified */
765 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000766 return;
767 }
danielk197753c0f742005-03-29 03:10:59 +0000768 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000769
770 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000771 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000772 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000773 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000774 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000775 }
drh1d85d932004-02-14 23:05:52 +0000776 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000777#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000778 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000779 {
780 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000781 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000782 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000783 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000784 }
drhe5f9c642003-01-13 23:27:31 +0000785 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000786 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000787 code = SQLITE_CREATE_TEMP_VIEW;
788 }else{
789 code = SQLITE_CREATE_VIEW;
790 }
791 }else{
danielk197753c0f742005-03-29 03:10:59 +0000792 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000793 code = SQLITE_CREATE_TEMP_TABLE;
794 }else{
795 code = SQLITE_CREATE_TABLE;
796 }
797 }
danielk1977f1a381e2006-06-16 08:01:02 +0000798 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000799 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000800 }
801 }
802#endif
drhf57b3392001-10-08 13:22:32 +0000803
drhf57b3392001-10-08 13:22:32 +0000804 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000805 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000806 ** it does. The exception is if the statement being parsed was passed
807 ** to an sqlite3_declare_vtab() call. In that case only the column names
808 ** and types will be used, so there is no need to test for namespace
809 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000810 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000811 if( !IN_DECLARE_VTAB ){
812 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
813 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000814 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000815 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
816 if( pTable ){
817 if( !noErr ){
818 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
819 }
820 goto begin_table_error;
821 }
822 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
823 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
824 goto begin_table_error;
825 }
drh75897232000-05-29 14:26:00 +0000826 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000827
danielk197726783a52007-08-29 14:06:22 +0000828 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000829 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000830 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000831 pParse->rc = SQLITE_NOMEM;
832 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000833 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000834 }
drh75897232000-05-29 14:26:00 +0000835 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000836 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000837 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000838 pTable->nRef = 1;
drh633e6d52008-07-28 19:34:53 +0000839 pTable->db = db;
danielk1977a04a34f2007-04-16 15:06:25 +0000840 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000841 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000842
drh4794f732004-11-05 17:17:50 +0000843 /* If this is the magic sqlite_sequence table used by autoincrement,
844 ** then record a pointer to this table in the main database structure
845 ** so that INSERT can find the table easily.
846 */
847#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000848 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000849 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000850 }
851#endif
852
drh17f71932002-02-21 12:01:27 +0000853 /* Begin generating the code that will insert the table record into
854 ** the SQLITE_MASTER table. Note in particular that we must go ahead
855 ** and allocate the record number for the table entry now. Before any
856 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
857 ** indices to be created and the table record must come before the
858 ** indices. Hence, the record number for the table must be allocated
859 ** now.
860 */
danielk19774adee202004-05-08 08:23:19 +0000861 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000862 int j1;
drhe321c292006-01-12 01:56:43 +0000863 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000864 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000865 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000866
danielk197720b1eaf2006-07-26 16:22:14 +0000867#ifndef SQLITE_OMIT_VIRTUALTABLE
868 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000869 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000870 }
871#endif
872
danielk197736963fd2005-02-19 08:18:05 +0000873 /* If the file format and encoding in the database have not been set,
874 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000875 */
drhb7654112008-01-12 12:48:07 +0000876 reg1 = pParse->regRowid = ++pParse->nMem;
877 reg2 = pParse->regRoot = ++pParse->nMem;
878 reg3 = ++pParse->nMem;
879 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */
drhfb982642007-08-30 01:19:59 +0000880 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000881 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000882 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000883 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000884 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
885 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
886 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
887 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
888 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000889
drh4794f732004-11-05 17:17:50 +0000890 /* This just creates a place-holder record in the sqlite_master table.
891 ** The record created does not contain anything yet. It will be replaced
892 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000893 **
894 ** The rowid for the new entry is left on the top of the stack.
895 ** The rowid value is needed by the code that sqlite3EndTable will
896 ** generate.
drh4794f732004-11-05 17:17:50 +0000897 */
danielk1977f1a381e2006-06-16 08:01:02 +0000898#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
899 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000900 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000901 }else
902#endif
903 {
drhb7654112008-01-12 12:48:07 +0000904 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000905 }
danielk1977c00da102006-01-07 13:21:04 +0000906 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000907 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
908 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
909 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
910 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000911 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000912 }
drh23bf66d2004-12-14 03:34:34 +0000913
914 /* Normal (non-error) return. */
915 return;
916
917 /* If an error occurs, we jump here */
918begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000919 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000920 return;
drh75897232000-05-29 14:26:00 +0000921}
922
923/*
danielk1977c60e9b82005-01-31 12:42:29 +0000924** This macro is used to compare two strings in a case-insensitive manner.
925** It is slightly faster than calling sqlite3StrICmp() directly, but
926** produces larger code.
927**
928** WARNING: This macro is not compatible with the strcmp() family. It
929** returns true if the two strings are equal, otherwise false.
930*/
931#define STRICMP(x, y) (\
932sqlite3UpperToLower[*(unsigned char *)(x)]== \
933sqlite3UpperToLower[*(unsigned char *)(y)] \
934&& sqlite3StrICmp((x)+1,(y)+1)==0 )
935
936/*
drh75897232000-05-29 14:26:00 +0000937** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000938**
939** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000940** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000941** first to get things going. Then this routine is called for each
942** column.
drh75897232000-05-29 14:26:00 +0000943*/
danielk19774adee202004-05-08 08:23:19 +0000944void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000945 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000946 int i;
drha99db3b2004-06-19 14:49:12 +0000947 char *z;
drhc9b84a12002-06-20 11:36:48 +0000948 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000949 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000950 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000951#if SQLITE_MAX_COLUMN
952 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000953 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
954 return;
955 }
drhbb4957f2008-03-20 14:03:29 +0000956#endif
danielk1977ae74e032008-12-23 11:11:51 +0000957 z = sqlite3NameFromToken(db, pName);
drh97fc3d02002-05-22 21:27:03 +0000958 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000959 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000960 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000961 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000962 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000963 return;
964 }
965 }
drh75897232000-05-29 14:26:00 +0000966 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000967 Column *aNew;
danielk1977ae74e032008-12-23 11:11:51 +0000968 aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000969 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000970 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000971 return;
972 }
drh6d4abfb2001-10-22 02:58:08 +0000973 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000974 }
drhc9b84a12002-06-20 11:36:48 +0000975 pCol = &p->aCol[p->nCol];
976 memset(pCol, 0, sizeof(p->aCol[0]));
977 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000978
979 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000980 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
981 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000982 */
danielk19774f057f92004-06-08 00:02:33 +0000983 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000984 p->nCol++;
drh75897232000-05-29 14:26:00 +0000985}
986
987/*
drh382c0242001-10-06 16:33:02 +0000988** This routine is called by the parser while in the middle of
989** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
990** been seen on a column. This routine sets the notNull flag on
991** the column currently under construction.
992*/
danielk19774adee202004-05-08 08:23:19 +0000993void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000994 Table *p;
995 int i;
996 if( (p = pParse->pNewTable)==0 ) return;
997 i = p->nCol-1;
drh1bd10f82008-12-10 21:19:56 +0000998 if( i>=0 ) p->aCol[i].notNull = (u8)onError;
drh382c0242001-10-06 16:33:02 +0000999}
1000
1001/*
danielk197752a83fb2005-01-31 12:56:44 +00001002** Scan the column type name zType (length nType) and return the
1003** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001004**
1005** This routine does a case-independent search of zType for the
1006** substrings in the following table. If one of the substrings is
1007** found, the corresponding affinity is returned. If zType contains
1008** more than one of the substrings, entries toward the top of
1009** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001010** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001011**
1012** Substring | Affinity
1013** --------------------------------
1014** 'INT' | SQLITE_AFF_INTEGER
1015** 'CHAR' | SQLITE_AFF_TEXT
1016** 'CLOB' | SQLITE_AFF_TEXT
1017** 'TEXT' | SQLITE_AFF_TEXT
1018** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001019** 'REAL' | SQLITE_AFF_REAL
1020** 'FLOA' | SQLITE_AFF_REAL
1021** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001022**
1023** If none of the substrings in the above table are found,
1024** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001025*/
drh8a512562005-11-14 22:29:05 +00001026char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +00001027 u32 h = 0;
1028 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +00001029 const unsigned char *zIn = pType->z;
1030 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +00001031
danielk1977b3dff962005-02-01 01:21:55 +00001032 while( zIn!=zEnd ){
1033 h = (h<<8) + sqlite3UpperToLower[*zIn];
1034 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001035 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1036 aff = SQLITE_AFF_TEXT;
1037 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1038 aff = SQLITE_AFF_TEXT;
1039 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1040 aff = SQLITE_AFF_TEXT;
1041 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001042 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001043 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001044#ifndef SQLITE_OMIT_FLOATING_POINT
1045 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1046 && aff==SQLITE_AFF_NUMERIC ){
1047 aff = SQLITE_AFF_REAL;
1048 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1049 && aff==SQLITE_AFF_NUMERIC ){
1050 aff = SQLITE_AFF_REAL;
1051 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1052 && aff==SQLITE_AFF_NUMERIC ){
1053 aff = SQLITE_AFF_REAL;
1054#endif
danielk1977201f7162005-02-01 02:13:29 +00001055 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001056 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001057 break;
danielk197752a83fb2005-01-31 12:56:44 +00001058 }
1059 }
danielk1977b3dff962005-02-01 01:21:55 +00001060
1061 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001062}
1063
1064/*
drh382c0242001-10-06 16:33:02 +00001065** This routine is called by the parser while in the middle of
1066** parsing a CREATE TABLE statement. The pFirst token is the first
1067** token in the sequence of tokens that describe the type of the
1068** column currently under construction. pLast is the last token
1069** in the sequence. Use this information to construct a string
1070** that contains the typename of the column and store that string
1071** in zType.
1072*/
drh487e2622005-06-25 18:42:14 +00001073void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001074 Table *p;
drh487e2622005-06-25 18:42:14 +00001075 int i;
drhc9b84a12002-06-20 11:36:48 +00001076 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001077 sqlite3 *db;
drh487e2622005-06-25 18:42:14 +00001078
drh382c0242001-10-06 16:33:02 +00001079 if( (p = pParse->pNewTable)==0 ) return;
1080 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001081 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001082 pCol = &p->aCol[i];
drh633e6d52008-07-28 19:34:53 +00001083 db = pParse->db;
1084 sqlite3DbFree(db, pCol->zType);
1085 pCol->zType = sqlite3NameFromToken(db, pType);
drh8a512562005-11-14 22:29:05 +00001086 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001087}
1088
1089/*
danielk19777977a172004-11-09 12:44:37 +00001090** The expression is the default value for the most recently added column
1091** of the table currently under construction.
1092**
1093** Default value expressions must be constant. Raise an exception if this
1094** is not the case.
drhd9b02572001-04-15 00:37:09 +00001095**
1096** This routine is called by the parser while in the middle of
1097** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001098*/
danielk19777977a172004-11-09 12:44:37 +00001099void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001100 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001101 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001102 sqlite3 *db = pParse->db;
drh42b9d7c2005-08-13 00:56:27 +00001103 if( (p = pParse->pNewTable)!=0 ){
1104 pCol = &(p->aCol[p->nCol-1]);
1105 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1106 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1107 pCol->zName);
1108 }else{
drh417ec632006-08-14 14:23:41 +00001109 Expr *pCopy;
drh633e6d52008-07-28 19:34:53 +00001110 sqlite3ExprDelete(db, pCol->pDflt);
drh17435752007-08-16 04:30:38 +00001111 pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
drh417ec632006-08-14 14:23:41 +00001112 if( pCopy ){
drh17435752007-08-16 04:30:38 +00001113 sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
drh417ec632006-08-14 14:23:41 +00001114 }
drh42b9d7c2005-08-13 00:56:27 +00001115 }
danielk19777977a172004-11-09 12:44:37 +00001116 }
drh633e6d52008-07-28 19:34:53 +00001117 sqlite3ExprDelete(db, pExpr);
drh7020f652000-06-03 18:06:52 +00001118}
1119
1120/*
drh4a324312001-12-21 14:30:42 +00001121** Designate the PRIMARY KEY for the table. pList is a list of names
1122** of columns that form the primary key. If pList is NULL, then the
1123** most recently added column of the table is the primary key.
1124**
1125** A table can have at most one primary key. If the table already has
1126** a primary key (and this is the second primary key) then create an
1127** error.
1128**
1129** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001130** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001131** field of the table under construction to be the index of the
1132** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1133** no INTEGER PRIMARY KEY.
1134**
1135** If the key is not an INTEGER PRIMARY KEY, then create a unique
1136** index for the key. No index is created for INTEGER PRIMARY KEYs.
1137*/
drh205f48e2004-11-05 00:43:11 +00001138void sqlite3AddPrimaryKey(
1139 Parse *pParse, /* Parsing context */
1140 ExprList *pList, /* List of field names to be indexed */
1141 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001142 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1143 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001144){
drh4a324312001-12-21 14:30:42 +00001145 Table *pTab = pParse->pNewTable;
1146 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001147 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001148 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001149 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001150 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001151 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001152 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001153 }
drh7d10d5a2008-08-20 16:35:10 +00001154 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001155 if( pList==0 ){
1156 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001157 pTab->aCol[iCol].isPrimKey = 1;
1158 }else{
danielk19770202b292004-06-09 09:55:16 +00001159 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001160 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001161 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1162 break;
1163 }
drh78100cc2003-08-23 22:40:53 +00001164 }
drh6e4fc2c2005-09-15 21:24:51 +00001165 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001166 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001167 }
drh4a324312001-12-21 14:30:42 +00001168 }
danielk19770202b292004-06-09 09:55:16 +00001169 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001170 }
1171 if( iCol>=0 && iCol<pTab->nCol ){
1172 zType = pTab->aCol[iCol].zType;
1173 }
drhfdd6e852005-12-16 01:06:16 +00001174 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1175 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001176 pTab->iPKey = iCol;
drh1bd10f82008-12-10 21:19:56 +00001177 pTab->keyConf = (u8)onError;
drh7d10d5a2008-08-20 16:35:10 +00001178 assert( autoInc==0 || autoInc==1 );
1179 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001180 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001181#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001182 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1183 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001184#endif
drh4a324312001-12-21 14:30:42 +00001185 }else{
drh4d91a702006-01-04 15:54:36 +00001186 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001187 pList = 0;
drh4a324312001-12-21 14:30:42 +00001188 }
drhe0194f22003-02-26 13:52:51 +00001189
1190primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001191 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001192 return;
drh4a324312001-12-21 14:30:42 +00001193}
1194
1195/*
drhffe07b22005-11-03 00:41:17 +00001196** Add a new CHECK constraint to the table currently under construction.
1197*/
1198void sqlite3AddCheckConstraint(
1199 Parse *pParse, /* Parsing context */
1200 Expr *pCheckExpr /* The check expression */
1201){
drh633e6d52008-07-28 19:34:53 +00001202 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001203#ifndef SQLITE_OMIT_CHECK
1204 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001205 if( pTab && !IN_DECLARE_VTAB ){
drhffe07b22005-11-03 00:41:17 +00001206 /* The CHECK expression must be duplicated so that tokens refer
1207 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1208 ** statement */
drh17435752007-08-16 04:30:38 +00001209 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
1210 sqlite3ExprDup(db, pCheckExpr));
drhffe07b22005-11-03 00:41:17 +00001211 }
1212#endif
drh633e6d52008-07-28 19:34:53 +00001213 sqlite3ExprDelete(db, pCheckExpr);
drhffe07b22005-11-03 00:41:17 +00001214}
1215
1216/*
drhd3d39e92004-05-20 22:16:29 +00001217** Set the collation function of the most recently parsed table column
1218** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001219*/
danielk197739002502007-11-12 09:50:26 +00001220void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001221 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001222 int i;
danielk197739002502007-11-12 09:50:26 +00001223 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001224 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001225
danielk1977b8cbb872006-06-19 05:33:45 +00001226 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001227 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001228 db = pParse->db;
1229 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001230 if( !zColl ) return;
1231
1232 if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001233 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001234 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001235
1236 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1237 ** then an index may have been created on this column before the
1238 ** collation type was added. Correct this if it is the case.
1239 */
1240 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1241 assert( pIdx->nColumn==1 );
1242 if( pIdx->aiColumn[0]==i ){
1243 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001244 }
1245 }
danielk197739002502007-11-12 09:50:26 +00001246 }else{
drh633e6d52008-07-28 19:34:53 +00001247 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001248 }
danielk19777cedc8d2004-06-10 10:50:08 +00001249}
1250
danielk1977466be562004-06-10 02:16:01 +00001251/*
1252** This function returns the collation sequence for database native text
1253** encoding identified by the string zName, length nName.
1254**
1255** If the requested collation sequence is not available, or not available
1256** in the database native encoding, the collation factory is invoked to
1257** request it. If the collation factory does not supply such a sequence,
1258** and the sequence is available in another text encoding, then that is
1259** returned instead.
1260**
1261** If no versions of the requested collations sequence are available, or
1262** another error occurs, NULL is returned and an error message written into
1263** pParse.
drha34001c2007-02-02 12:44:37 +00001264**
1265** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1266** invokes the collation factory if the named collation cannot be found
1267** and generates an error message.
danielk1977466be562004-06-10 02:16:01 +00001268*/
danielk19770202b292004-06-09 09:55:16 +00001269CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001270 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001271 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001272 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001273 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001274
danielk1977b3bf5562006-01-10 17:58:23 +00001275 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001276 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001277 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1278 if( !pColl ){
1279 if( nName<0 ){
drh0a687d12008-07-08 14:52:07 +00001280 nName = sqlite3Strlen(db, zName);
danielk1977466be562004-06-10 02:16:01 +00001281 }
danielk19774dade032005-05-25 10:45:10 +00001282 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1283 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001284 }
1285 }
1286
danielk19770202b292004-06-09 09:55:16 +00001287 return pColl;
1288}
1289
1290
drh8e2ca022002-06-17 17:07:19 +00001291/*
drh3f7d4e42004-07-24 14:35:58 +00001292** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001293**
1294** The schema cookie is used to determine when the schema for the
1295** database changes. After each schema change, the cookie value
1296** changes. When a process first reads the schema it records the
1297** cookie. Thereafter, whenever it goes to access the database,
1298** it checks the cookie to make sure the schema has not changed
1299** since it was last read.
1300**
1301** This plan is not completely bullet-proof. It is possible for
1302** the schema to change multiple times and for the cookie to be
1303** set back to prior value. But schema changes are infrequent
1304** and the probability of hitting the same cookie value is only
1305** 1 chance in 2^32. So we're safe enough.
1306*/
drh9cbf3422008-01-17 16:22:13 +00001307void sqlite3ChangeCookie(Parse *pParse, int iDb){
1308 int r1 = sqlite3GetTempReg(pParse);
1309 sqlite3 *db = pParse->db;
1310 Vdbe *v = pParse->pVdbe;
1311 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1312 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
1313 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001314}
1315
1316/*
drh969fa7c2002-02-18 18:30:32 +00001317** Measure the number of characters needed to output the given
1318** identifier. The number returned includes any quotes used
1319** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001320**
1321** The estimate is conservative. It might be larger that what is
1322** really needed.
drh969fa7c2002-02-18 18:30:32 +00001323*/
1324static int identLength(const char *z){
1325 int n;
drh17f71932002-02-21 12:01:27 +00001326 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001327 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001328 }
drh234c39d2004-07-24 03:30:47 +00001329 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001330}
1331
1332/*
1333** Write an identifier onto the end of the given string. Add
1334** quote characters as needed.
1335*/
drh4c755c02004-08-08 20:22:17 +00001336static void identPut(char *z, int *pIdx, char *zSignedIdent){
1337 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001338 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001339 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001340 for(j=0; zIdent[j]; j++){
danielk197778ca0e72009-01-20 16:53:39 +00001341 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
drh17f71932002-02-21 12:01:27 +00001342 }
danielk197778ca0e72009-01-20 16:53:39 +00001343 needQuote = zIdent[j]!=0 || sqlite3Isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001344 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001345 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001346 for(j=0; zIdent[j]; j++){
1347 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001348 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001349 }
drh234c39d2004-07-24 03:30:47 +00001350 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001351 z[i] = 0;
1352 *pIdx = i;
1353}
1354
1355/*
1356** Generate a CREATE TABLE statement appropriate for the given
1357** table. Memory to hold the text of the statement is obtained
1358** from sqliteMalloc() and must be freed by the calling function.
1359*/
drh820a9062008-01-31 13:35:48 +00001360static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001361 int i, k, n;
1362 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001363 char *zSep, *zSep2, *zEnd, *z;
1364 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001365 n = 0;
drh234c39d2004-07-24 03:30:47 +00001366 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1367 n += identLength(pCol->zName);
1368 z = pCol->zType;
1369 if( z ){
drhea678832008-12-10 19:26:22 +00001370 n += (sqlite3Strlen30(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001371 }
drh969fa7c2002-02-18 18:30:32 +00001372 }
1373 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001374 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001375 zSep = "";
1376 zSep2 = ",";
1377 zEnd = ")";
1378 }else{
1379 zSep = "\n ";
1380 zSep2 = ",\n ";
1381 zEnd = "\n)";
1382 }
drhe0bc4042002-06-25 01:09:11 +00001383 n += 35 + 6*p->nCol;
drhe5ae5732008-06-15 02:51:47 +00001384 zStmt = sqlite3Malloc( n );
drh820a9062008-01-31 13:35:48 +00001385 if( zStmt==0 ){
1386 db->mallocFailed = 1;
1387 return 0;
1388 }
drh5bb3eb92007-05-04 13:15:55 +00001389 sqlite3_snprintf(n, zStmt,
1390 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drhea678832008-12-10 19:26:22 +00001391 k = sqlite3Strlen30(zStmt);
drh969fa7c2002-02-18 18:30:32 +00001392 identPut(zStmt, &k, p->zName);
1393 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001394 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh5bb3eb92007-05-04 13:15:55 +00001395 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drhea678832008-12-10 19:26:22 +00001396 k += sqlite3Strlen30(&zStmt[k]);
drh969fa7c2002-02-18 18:30:32 +00001397 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001398 identPut(zStmt, &k, pCol->zName);
1399 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001400 zStmt[k++] = ' ';
drhea678832008-12-10 19:26:22 +00001401 assert( (int)(sqlite3Strlen30(z)+k+1)<=n );
drh5bb3eb92007-05-04 13:15:55 +00001402 sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
drhea678832008-12-10 19:26:22 +00001403 k += sqlite3Strlen30(z);
danielk1977517eb642004-06-07 10:00:31 +00001404 }
drh969fa7c2002-02-18 18:30:32 +00001405 }
drh5bb3eb92007-05-04 13:15:55 +00001406 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001407 return zStmt;
1408}
1409
1410/*
drh75897232000-05-29 14:26:00 +00001411** This routine is called to report the final ")" that terminates
1412** a CREATE TABLE statement.
1413**
drhf57b3392001-10-08 13:22:32 +00001414** The table structure that other action routines have been building
1415** is added to the internal hash tables, assuming no errors have
1416** occurred.
drh75897232000-05-29 14:26:00 +00001417**
drh1d85d932004-02-14 23:05:52 +00001418** An entry for the table is made in the master table on disk, unless
1419** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001420** it means we are reading the sqlite_master table because we just
1421** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001422** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001423** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001424**
1425** If the pSelect argument is not NULL, it means that this routine
1426** was called to create a table generated from a
1427** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1428** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001429*/
danielk197719a8e7e2005-03-17 05:03:38 +00001430void sqlite3EndTable(
1431 Parse *pParse, /* Parse context */
1432 Token *pCons, /* The ',' token after the last column defn. */
1433 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1434 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1435){
drh75897232000-05-29 14:26:00 +00001436 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001437 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001438 int iDb;
drh75897232000-05-29 14:26:00 +00001439
drh17435752007-08-16 04:30:38 +00001440 if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001441 return;
1442 }
drh28037572000-08-02 13:47:41 +00001443 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001444 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001445
danielk1977517eb642004-06-07 10:00:31 +00001446 assert( !db->init.busy || !pSelect );
1447
drhb9bb7c12006-06-11 23:41:55 +00001448 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001449
drhffe07b22005-11-03 00:41:17 +00001450#ifndef SQLITE_OMIT_CHECK
1451 /* Resolve names in all CHECK constraint expressions.
1452 */
1453 if( p->pCheck ){
1454 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1455 NameContext sNC; /* Name context for pParse->pNewTable */
1456
1457 memset(&sNC, 0, sizeof(sNC));
1458 memset(&sSrc, 0, sizeof(sSrc));
1459 sSrc.nSrc = 1;
1460 sSrc.a[0].zName = p->zName;
1461 sSrc.a[0].pTab = p;
1462 sSrc.a[0].iCursor = -1;
1463 sNC.pParse = pParse;
1464 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001465 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001466 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001467 return;
1468 }
1469 }
1470#endif /* !defined(SQLITE_OMIT_CHECK) */
1471
drh1d85d932004-02-14 23:05:52 +00001472 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001473 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1474 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001475 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001476 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001477 */
drh1d85d932004-02-14 23:05:52 +00001478 if( db->init.busy ){
1479 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001480 }
1481
drhe3c41372001-09-17 20:25:58 +00001482 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001483 ** in the SQLITE_MASTER table of the database. The record number
1484 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001485 **
drhe0bc4042002-06-25 01:09:11 +00001486 ** If this is a TEMPORARY table, write the entry into the auxiliary
1487 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001488 */
drh1d85d932004-02-14 23:05:52 +00001489 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001490 int n;
drhd8bc7082000-06-07 23:51:50 +00001491 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001492 char *zType; /* "view" or "table" */
1493 char *zType2; /* "VIEW" or "TABLE" */
1494 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001495
danielk19774adee202004-05-08 08:23:19 +00001496 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001497 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001498
drh66a51672008-01-03 00:01:23 +00001499 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001500
drh4794f732004-11-05 17:17:50 +00001501 /* Create the rootpage for the new table and push it onto the stack.
1502 ** A view has no rootpage, so just push a zero onto the stack for
1503 ** views. Initialize zType at the same time.
1504 */
drh4ff6dfa2002-03-03 23:06:00 +00001505 if( p->pSelect==0 ){
1506 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001507 zType = "table";
1508 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001509#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001510 }else{
1511 /* A view */
drh4794f732004-11-05 17:17:50 +00001512 zType = "view";
1513 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001514#endif
drh4ff6dfa2002-03-03 23:06:00 +00001515 }
danielk1977517eb642004-06-07 10:00:31 +00001516
danielk1977517eb642004-06-07 10:00:31 +00001517 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1518 ** statement to populate the new table. The root-page number for the
1519 ** new table is on the top of the vdbe stack.
1520 **
1521 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1522 ** suitable state to query for the column names and types to be used
1523 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001524 **
1525 ** A shared-cache write-lock is not required to write to the new table,
1526 ** as a schema-lock must have already been obtained to create it. Since
1527 ** a schema-lock excludes all other database users, the write-lock would
1528 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001529 */
1530 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001531 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001532 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001533
danielk1977df206b02008-08-04 04:39:48 +00001534 assert(pParse->nTab==0);
drhb7654112008-01-12 12:48:07 +00001535 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001536 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001537 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001538 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001539 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001540 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001541 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001542 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001543 if( pSelTab==0 ) return;
1544 assert( p->aCol==0 );
1545 p->nCol = pSelTab->nCol;
1546 p->aCol = pSelTab->aCol;
1547 pSelTab->nCol = 0;
1548 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001549 sqlite3DeleteTable(pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001550 }
1551 }
drh4794f732004-11-05 17:17:50 +00001552
drh4794f732004-11-05 17:17:50 +00001553 /* Compute the complete text of the CREATE statement */
1554 if( pSelect ){
drh820a9062008-01-31 13:35:48 +00001555 zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001556 }else{
drh1bd10f82008-12-10 21:19:56 +00001557 n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
danielk19771e536952007-08-16 10:09:01 +00001558 zStmt = sqlite3MPrintf(db,
1559 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1560 );
drh4794f732004-11-05 17:17:50 +00001561 }
1562
1563 /* A slot for the record has already been allocated in the
1564 ** SQLITE_MASTER table. We just need to update that slot with all
1565 ** the information we've collected. The rowid for the preallocated
1566 ** slot is the 2nd item on the stack. The top of the stack is the
1567 ** root page for the new table (or a 0 if this is a view).
1568 */
1569 sqlite3NestedParse(pParse,
1570 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001571 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1572 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001573 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001574 zType,
1575 p->zName,
1576 p->zName,
drhb7654112008-01-12 12:48:07 +00001577 pParse->regRoot,
1578 zStmt,
1579 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001580 );
drh633e6d52008-07-28 19:34:53 +00001581 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001582 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001583
1584#ifndef SQLITE_OMIT_AUTOINCREMENT
1585 /* Check to see if we need to create an sqlite_sequence table for
1586 ** keeping track of autoincrement keys.
1587 */
drh7d10d5a2008-08-20 16:35:10 +00001588 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001589 Db *pDb = &db->aDb[iDb];
1590 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001591 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001592 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1593 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001594 );
1595 }
1596 }
1597#endif
drh4794f732004-11-05 17:17:50 +00001598
1599 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001600 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1601 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001602 }
drh17e9e292003-02-01 13:53:28 +00001603
drh2958a4e2004-11-12 03:56:15 +00001604
drh17e9e292003-02-01 13:53:28 +00001605 /* Add the table to the in-memory representation of the database.
1606 */
drh234c39d2004-07-24 03:30:47 +00001607 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001608 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001609 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001610 Schema *pSchema = p->pSchema;
drhea678832008-12-10 19:26:22 +00001611 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
1612 sqlite3Strlen30(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001613 if( pOld ){
1614 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001615 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001616 return;
1617 }
danielk1977576ec6b2005-01-21 11:55:25 +00001618#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001619 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
danielk1977a1644fd2007-08-29 12:31:25 +00001620 void *data;
drhea678832008-12-10 19:26:22 +00001621 int nTo = sqlite3Strlen30(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001622 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
danielk1977a1644fd2007-08-29 12:31:25 +00001623 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
1624 if( data==(void *)pFKey ){
1625 db->mallocFailed = 1;
1626 }
drh17e9e292003-02-01 13:53:28 +00001627 }
danielk1977576ec6b2005-01-21 11:55:25 +00001628#endif
drh17e9e292003-02-01 13:53:28 +00001629 pParse->pNewTable = 0;
1630 db->nTable++;
1631 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001632
1633#ifndef SQLITE_OMIT_ALTERTABLE
1634 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001635 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001636 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001637 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001638 if( pCons->z==0 ){
1639 pCons = pEnd;
1640 }
drh1bd10f82008-12-10 21:19:56 +00001641 nName = (int)((const char *)pCons->z - zName);
drh9a087a92007-05-15 14:34:32 +00001642 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001643 }
1644#endif
drh17e9e292003-02-01 13:53:28 +00001645 }
drh75897232000-05-29 14:26:00 +00001646}
1647
drhb7f91642004-10-31 02:22:47 +00001648#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001649/*
drha76b5df2002-02-23 02:32:10 +00001650** The parser calls this routine in order to create a new VIEW
1651*/
danielk19774adee202004-05-08 08:23:19 +00001652void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001653 Parse *pParse, /* The parsing context */
1654 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001655 Token *pName1, /* The token that holds the name of the view */
1656 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001657 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001658 int isTemp, /* TRUE for a TEMPORARY view */
1659 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001660){
drha76b5df2002-02-23 02:32:10 +00001661 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001662 int n;
drh4c755c02004-08-08 20:22:17 +00001663 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001664 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001665 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001666 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001667 int iDb;
drh17435752007-08-16 04:30:38 +00001668 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001669
drh7c3d64f2005-06-06 15:32:08 +00001670 if( pParse->nVar>0 ){
1671 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001672 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001673 return;
1674 }
drhfdd48a72006-09-11 23:45:48 +00001675 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001676 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001677 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001678 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001679 return;
1680 }
danielk1977ef2cb632004-05-29 02:37:19 +00001681 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001682 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001683 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001684 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001685 ){
drh633e6d52008-07-28 19:34:53 +00001686 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001687 return;
1688 }
drh174b6192002-12-03 02:22:52 +00001689
drh4b59ab52002-08-24 18:24:51 +00001690 /* Make a copy of the entire SELECT statement that defines the view.
1691 ** This will force all the Expr.token.z values to be dynamically
1692 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001693 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001694 */
drh17435752007-08-16 04:30:38 +00001695 p->pSelect = sqlite3SelectDup(db, pSelect);
drh633e6d52008-07-28 19:34:53 +00001696 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001697 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001698 return;
1699 }
drh17435752007-08-16 04:30:38 +00001700 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001701 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001702 }
drh4b59ab52002-08-24 18:24:51 +00001703
1704 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1705 ** the end.
1706 */
drha76b5df2002-02-23 02:32:10 +00001707 sEnd = pParse->sLastToken;
1708 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1709 sEnd.z += sEnd.n;
1710 }
1711 sEnd.n = 0;
drh1bd10f82008-12-10 21:19:56 +00001712 n = (int)(sEnd.z - pBegin->z);
drh4c755c02004-08-08 20:22:17 +00001713 z = (const unsigned char*)pBegin->z;
danielk197778ca0e72009-01-20 16:53:39 +00001714 while( n>0 && (z[n-1]==';' || sqlite3Isspace(z[n-1])) ){ n--; }
drh4ff6dfa2002-03-03 23:06:00 +00001715 sEnd.z = &z[n-1];
1716 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001717
danielk19774adee202004-05-08 08:23:19 +00001718 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001719 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001720 return;
drh417be792002-03-03 18:59:40 +00001721}
drhb7f91642004-10-31 02:22:47 +00001722#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001723
danielk1977fe3fcbe22006-06-12 12:08:45 +00001724#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001725/*
1726** The Table structure pTable is really a VIEW. Fill in the names of
1727** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001728** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001729*/
danielk19774adee202004-05-08 08:23:19 +00001730int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001731 Table *pSelTab; /* A fake table from which we get the result set */
1732 Select *pSel; /* Copy of the SELECT that implements the view */
1733 int nErr = 0; /* Number of errors encountered */
1734 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001735 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001736 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001737
1738 assert( pTable );
1739
danielk1977fe3fcbe22006-06-12 12:08:45 +00001740#ifndef SQLITE_OMIT_VIRTUALTABLE
1741 if( sqlite3VtabCallConnect(pParse, pTable) ){
1742 return SQLITE_ERROR;
1743 }
drh4cbdda92006-06-14 19:00:20 +00001744 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001745#endif
1746
1747#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001748 /* A positive nCol means the columns names for this view are
1749 ** already known.
1750 */
1751 if( pTable->nCol>0 ) return 0;
1752
1753 /* A negative nCol is a special marker meaning that we are currently
1754 ** trying to compute the column names. If we enter this routine with
1755 ** a negative nCol, it means two or more views form a loop, like this:
1756 **
1757 ** CREATE VIEW one AS SELECT * FROM two;
1758 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001759 **
1760 ** Actually, this error is caught previously and so the following test
1761 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001762 */
1763 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001764 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001765 return 1;
1766 }
drh85c23c62005-08-20 03:03:04 +00001767 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001768
1769 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001770 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1771 ** "*" elements in the results set of the view and will assign cursors
1772 ** to the elements of the FROM clause. But we do not want these changes
1773 ** to be permanent. So the computation is done on a copy of the SELECT
1774 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001775 */
drh9b3187e2005-01-18 14:45:47 +00001776 assert( pTable->pSelect );
drh17435752007-08-16 04:30:38 +00001777 pSel = sqlite3SelectDup(db, pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001778 if( pSel ){
1779 n = pParse->nTab;
1780 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1781 pTable->nCol = -1;
danielk1977db2d2862007-10-15 07:08:44 +00001782#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001783 xAuth = db->xAuth;
1784 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001785 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001786 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001787#else
drh7d10d5a2008-08-20 16:35:10 +00001788 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001789#endif
danielk1977261919c2005-12-06 12:52:59 +00001790 pParse->nTab = n;
1791 if( pSelTab ){
1792 assert( pTable->aCol==0 );
1793 pTable->nCol = pSelTab->nCol;
1794 pTable->aCol = pSelTab->aCol;
1795 pSelTab->nCol = 0;
1796 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001797 sqlite3DeleteTable(pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001798 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001799 }else{
1800 pTable->nCol = 0;
1801 nErr++;
1802 }
drh633e6d52008-07-28 19:34:53 +00001803 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001804 } else {
drh417be792002-03-03 18:59:40 +00001805 nErr++;
1806 }
drhb7f91642004-10-31 02:22:47 +00001807#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001808 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001809}
1810#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001811
drhb7f91642004-10-31 02:22:47 +00001812#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001813/*
drh8bf8dc92003-05-17 17:35:10 +00001814** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001815*/
drh9bb575f2004-09-06 17:24:11 +00001816static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001817 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001818 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001819 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001820 Table *pTab = sqliteHashData(i);
1821 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001822 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001823 }
1824 }
drh8bf8dc92003-05-17 17:35:10 +00001825 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001826}
drhb7f91642004-10-31 02:22:47 +00001827#else
1828# define sqliteViewResetAll(A,B)
1829#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001830
drh75897232000-05-29 14:26:00 +00001831/*
danielk1977a0bf2652004-11-04 14:30:04 +00001832** This function is called by the VDBE to adjust the internal schema
1833** used by SQLite when the btree layer moves a table root page. The
1834** root-page of a table or index in database iDb has changed from iFrom
1835** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001836**
1837** Ticket #1728: The symbol table might still contain information
1838** on tables and/or indices that are the process of being deleted.
1839** If you are unlucky, one of those deleted indices or tables might
1840** have the same rootpage number as the real table or index that is
1841** being moved. So we cannot stop searching after the first match
1842** because the first match might be for one of the deleted indices
1843** or tables and not the table/index that is actually being moved.
1844** We must continue looping until all tables and indices with
1845** rootpage==iFrom have been converted to have a rootpage of iTo
1846** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001847*/
1848#ifndef SQLITE_OMIT_AUTOVACUUM
1849void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1850 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001851 Hash *pHash;
1852
1853 pHash = &pDb->pSchema->tblHash;
1854 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001855 Table *pTab = sqliteHashData(pElem);
1856 if( pTab->tnum==iFrom ){
1857 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001858 }
1859 }
danielk1977da184232006-01-05 11:34:32 +00001860 pHash = &pDb->pSchema->idxHash;
1861 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001862 Index *pIdx = sqliteHashData(pElem);
1863 if( pIdx->tnum==iFrom ){
1864 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001865 }
1866 }
danielk1977a0bf2652004-11-04 14:30:04 +00001867}
1868#endif
1869
1870/*
1871** Write code to erase the table with root-page iTable from database iDb.
1872** Also write code to modify the sqlite_master table and internal schema
1873** if a root-page of another table is moved by the btree-layer whilst
1874** erasing iTable (this can happen with an auto-vacuum database).
1875*/
drh4e0cff62004-11-05 05:10:28 +00001876static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1877 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001878 int r1 = sqlite3GetTempReg(pParse);
1879 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
drh40e016e2004-11-04 14:47:11 +00001880#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001881 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001882 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001883 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001884 ** reflect this.
1885 **
drhb7654112008-01-12 12:48:07 +00001886 ** The "#%d" in the SQL is a special constant that means whatever value
drh4e0cff62004-11-05 05:10:28 +00001887 ** is on the top of the stack. See sqlite3RegisterExpr().
1888 */
danielk197763e3e9f2004-11-05 09:19:27 +00001889 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001890 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1891 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001892#endif
drhb7654112008-01-12 12:48:07 +00001893 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001894}
1895
1896/*
1897** Write VDBE code to erase table pTab and all associated indices on disk.
1898** Code to update the sqlite_master tables and internal schema definitions
1899** in case a root-page belonging to another table is moved by the btree layer
1900** is also added (this can happen with an auto-vacuum database).
1901*/
drh4e0cff62004-11-05 05:10:28 +00001902static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001903#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001904 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001905 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1906 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001907 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001908 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001909 }
1910#else
1911 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1912 ** is not defined), then it is important to call OP_Destroy on the
1913 ** table and index root-pages in order, starting with the numerically
1914 ** largest root-page number. This guarantees that none of the root-pages
1915 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1916 ** following were coded:
1917 **
1918 ** OP_Destroy 4 0
1919 ** ...
1920 ** OP_Destroy 5 0
1921 **
1922 ** and root page 5 happened to be the largest root-page number in the
1923 ** database, then root page 5 would be moved to page 4 by the
1924 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1925 ** a free-list page.
1926 */
1927 int iTab = pTab->tnum;
1928 int iDestroyed = 0;
1929
1930 while( 1 ){
1931 Index *pIdx;
1932 int iLargest = 0;
1933
1934 if( iDestroyed==0 || iTab<iDestroyed ){
1935 iLargest = iTab;
1936 }
1937 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1938 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001939 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001940 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1941 iLargest = iIdx;
1942 }
1943 }
danielk1977da184232006-01-05 11:34:32 +00001944 if( iLargest==0 ){
1945 return;
1946 }else{
1947 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1948 destroyRootPage(pParse, iLargest, iDb);
1949 iDestroyed = iLargest;
1950 }
danielk1977a0bf2652004-11-04 14:30:04 +00001951 }
1952#endif
1953}
1954
1955/*
drh75897232000-05-29 14:26:00 +00001956** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001957** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001958*/
drha0733842005-12-29 01:11:36 +00001959void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001960 Table *pTab;
drh75897232000-05-29 14:26:00 +00001961 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001962 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001963 int iDb;
drh75897232000-05-29 14:26:00 +00001964
drh17435752007-08-16 04:30:38 +00001965 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001966 goto exit_drop_table;
1967 }
danielk1977a8858102004-05-28 12:11:21 +00001968 assert( pName->nSrc==1 );
drhca424112008-01-25 15:04:48 +00001969 pTab = sqlite3LocateTable(pParse, isView,
1970 pName->a[0].zName, pName->a[0].zDatabase);
danielk1977a8858102004-05-28 12:11:21 +00001971
drha0733842005-12-29 01:11:36 +00001972 if( pTab==0 ){
1973 if( noErr ){
1974 sqlite3ErrorClear(pParse);
1975 }
1976 goto exit_drop_table;
1977 }
danielk1977da184232006-01-05 11:34:32 +00001978 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001979 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001980
1981 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1982 ** it is initialized.
1983 */
1984 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1985 goto exit_drop_table;
1986 }
drhe5f9c642003-01-13 23:27:31 +00001987#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001988 {
1989 int code;
danielk1977da184232006-01-05 11:34:32 +00001990 const char *zTab = SCHEMA_TABLE(iDb);
1991 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001992 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001993 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001994 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001995 }
drhe5f9c642003-01-13 23:27:31 +00001996 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001997 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001998 code = SQLITE_DROP_TEMP_VIEW;
1999 }else{
2000 code = SQLITE_DROP_VIEW;
2001 }
danielk19774b2688a2006-06-20 11:01:07 +00002002#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002003 }else if( IsVirtual(pTab) ){
2004 code = SQLITE_DROP_VTABLE;
2005 zArg2 = pTab->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002006#endif
drhe5f9c642003-01-13 23:27:31 +00002007 }else{
danielk197753c0f742005-03-29 03:10:59 +00002008 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002009 code = SQLITE_DROP_TEMP_TABLE;
2010 }else{
2011 code = SQLITE_DROP_TABLE;
2012 }
2013 }
danielk1977f1a381e2006-06-16 08:01:02 +00002014 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002015 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002016 }
danielk1977a8858102004-05-28 12:11:21 +00002017 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2018 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002019 }
drhe5f9c642003-01-13 23:27:31 +00002020 }
2021#endif
drhc456e572008-08-11 18:44:58 +00002022 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002023 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002024 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002025 }
danielk1977576ec6b2005-01-21 11:55:25 +00002026
2027#ifndef SQLITE_OMIT_VIEW
2028 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2029 ** on a table.
2030 */
danielk1977a8858102004-05-28 12:11:21 +00002031 if( isView && pTab->pSelect==0 ){
2032 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2033 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002034 }
danielk1977a8858102004-05-28 12:11:21 +00002035 if( !isView && pTab->pSelect ){
2036 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2037 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002038 }
danielk1977576ec6b2005-01-21 11:55:25 +00002039#endif
drh75897232000-05-29 14:26:00 +00002040
drh1ccde152000-06-17 13:12:39 +00002041 /* Generate code to remove the table from the master table
2042 ** on disk.
2043 */
danielk19774adee202004-05-08 08:23:19 +00002044 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002045 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002046 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002047 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002048 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002049
danielk197720b1eaf2006-07-26 16:22:14 +00002050#ifndef SQLITE_OMIT_VIRTUALTABLE
2051 if( IsVirtual(pTab) ){
danielk197720b1eaf2006-07-26 16:22:14 +00002052 if( v ){
drh66a51672008-01-03 00:01:23 +00002053 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002054 }
2055 }
2056#endif
2057
danielk19778e227872004-06-07 07:52:17 +00002058 /* Drop all triggers associated with the table being dropped. Code
2059 ** is generated to remove entries from sqlite_master and/or
2060 ** sqlite_temp_master if required.
2061 */
danielk1977a8858102004-05-28 12:11:21 +00002062 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00002063 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002064 assert( pTrigger->pSchema==pTab->pSchema ||
2065 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002066 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002067 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002068 }
drh8bf8dc92003-05-17 17:35:10 +00002069
danielk19774d36b812004-11-19 07:07:30 +00002070#ifndef SQLITE_OMIT_AUTOINCREMENT
2071 /* Remove any entries of the sqlite_sequence table associated with
2072 ** the table being dropped. This is done before the table is dropped
2073 ** at the btree level, in case the sqlite_sequence table needs to
2074 ** move as a result of the drop (can happen in auto-vacuum mode).
2075 */
drh7d10d5a2008-08-20 16:35:10 +00002076 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002077 sqlite3NestedParse(pParse,
2078 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2079 pDb->zName, pTab->zName
2080 );
2081 }
2082#endif
2083
danielk19778e227872004-06-07 07:52:17 +00002084 /* Drop all SQLITE_MASTER table and index entries that refer to the
2085 ** table. The program name loops through the master table and deletes
2086 ** every row that refers to a table of the same name as the one being
2087 ** dropped. Triggers are handled seperately because a trigger can be
2088 ** created in the temp database that refers to a table in another
2089 ** database.
2090 */
drhf1974842004-11-05 03:56:00 +00002091 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002092 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002093 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002094
2095 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2096 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2097 sqlite3NestedParse(pParse,
2098 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2099 );
2100 }
2101
danielk19774b2688a2006-06-20 11:01:07 +00002102 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002103 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002104 }
drh2958a4e2004-11-12 03:56:15 +00002105
danielk1977a21c6b62005-01-24 10:25:59 +00002106 /* Remove the table entry from SQLite's internal schema and modify
2107 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002108 */
drh4cbdda92006-06-14 19:00:20 +00002109 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002110 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002111 }
drh66a51672008-01-03 00:01:23 +00002112 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002113 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002114 }
drhd24cc422003-03-27 12:51:24 +00002115 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002116
2117exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002118 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002119}
2120
2121/*
drhc2eef3b2002-08-31 18:53:06 +00002122** This routine is called to create a new foreign key on the table
2123** currently under construction. pFromCol determines which columns
2124** in the current table point to the foreign key. If pFromCol==0 then
2125** connect the key to the last column inserted. pTo is the name of
2126** the table referred to. pToCol is a list of tables in the other
2127** pTo table that the foreign key points to. flags contains all
2128** information about the conflict resolution algorithms specified
2129** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2130**
2131** An FKey structure is created and added to the table currently
2132** under construction in the pParse->pNewTable field. The new FKey
2133** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00002134** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00002135**
2136** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002137** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002138*/
danielk19774adee202004-05-08 08:23:19 +00002139void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002140 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002141 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002142 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002143 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002144 int flags /* Conflict resolution algorithms. */
2145){
danielk197718576932008-08-06 13:47:40 +00002146 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002147#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002148 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00002149 Table *p = pParse->pNewTable;
2150 int nByte;
2151 int i;
2152 int nCol;
2153 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002154
2155 assert( pTo!=0 );
danielk1977c7d54102006-06-15 07:29:00 +00002156 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002157 if( pFromCol==0 ){
2158 int iCol = p->nCol-1;
2159 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002160 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002161 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002162 " should reference only one column of table %T",
2163 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002164 goto fk_end;
2165 }
2166 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002167 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002168 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002169 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002170 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002171 goto fk_end;
2172 }else{
danielk19770202b292004-06-09 09:55:16 +00002173 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002174 }
2175 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2176 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002177 for(i=0; i<pToCol->nExpr; i++){
drhea678832008-12-10 19:26:22 +00002178 nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
drhc2eef3b2002-08-31 18:53:06 +00002179 }
2180 }
drh633e6d52008-07-28 19:34:53 +00002181 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002182 if( pFKey==0 ){
2183 goto fk_end;
2184 }
drhc2eef3b2002-08-31 18:53:06 +00002185 pFKey->pFrom = p;
2186 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002187 z = (char*)&pFKey[1];
2188 pFKey->aCol = (struct sColMap*)z;
2189 z += sizeof(struct sColMap)*nCol;
2190 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002191 memcpy(z, pTo->z, pTo->n);
2192 z[pTo->n] = 0;
2193 z += pTo->n+1;
2194 pFKey->pNextTo = 0;
2195 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002196 if( pFromCol==0 ){
2197 pFKey->aCol[0].iFrom = p->nCol-1;
2198 }else{
2199 for(i=0; i<nCol; i++){
2200 int j;
2201 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002202 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002203 pFKey->aCol[i].iFrom = j;
2204 break;
2205 }
2206 }
2207 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002208 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002209 "unknown column \"%s\" in foreign key definition",
2210 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002211 goto fk_end;
2212 }
2213 }
2214 }
2215 if( pToCol ){
2216 for(i=0; i<nCol; i++){
drhea678832008-12-10 19:26:22 +00002217 int n = sqlite3Strlen30(pToCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002218 pFKey->aCol[i].zCol = z;
2219 memcpy(z, pToCol->a[i].zName, n);
2220 z[n] = 0;
2221 z += n+1;
2222 }
2223 }
2224 pFKey->isDeferred = 0;
drh1bd10f82008-12-10 21:19:56 +00002225 pFKey->deleteConf = (u8)(flags & 0xff);
2226 pFKey->updateConf = (u8)((flags >> 8 ) & 0xff);
2227 pFKey->insertConf = (u8)((flags >> 16 ) & 0xff);
drhc2eef3b2002-08-31 18:53:06 +00002228
2229 /* Link the foreign key to the table as the last step.
2230 */
2231 p->pFKey = pFKey;
2232 pFKey = 0;
2233
2234fk_end:
drh633e6d52008-07-28 19:34:53 +00002235 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002236#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002237 sqlite3ExprListDelete(db, pFromCol);
2238 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002239}
2240
2241/*
2242** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2243** clause is seen as part of a foreign key definition. The isDeferred
2244** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2245** The behavior of the most recently created foreign key is adjusted
2246** accordingly.
2247*/
danielk19774adee202004-05-08 08:23:19 +00002248void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002249#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002250 Table *pTab;
2251 FKey *pFKey;
2252 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
drh1bd10f82008-12-10 21:19:56 +00002253 assert( isDeferred==0 || isDeferred==1 );
2254 pFKey->isDeferred = (u8)isDeferred;
drhb7f91642004-10-31 02:22:47 +00002255#endif
drhc2eef3b2002-08-31 18:53:06 +00002256}
2257
2258/*
drh063336a2004-11-05 20:58:39 +00002259** Generate code that will erase and refill index *pIdx. This is
2260** used to initialize a newly created index or to recompute the
2261** content of an index in response to a REINDEX command.
2262**
2263** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002264** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002265** root page number of the index. If memRootPage is negative, then
2266** the index already exists and must be cleared before being refilled and
2267** the root page number of the index is taken from pIndex->tnum.
2268*/
2269static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2270 Table *pTab = pIndex->pTable; /* The table that is indexed */
2271 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2272 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2273 int addr1; /* Address of top of loop */
2274 int tnum; /* Root page of index */
2275 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002276 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002277 int regIdxKey; /* Registers containing the index key */
2278 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002279 sqlite3 *db = pParse->db; /* The database connection */
2280 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002281
danielk19771d54df82004-11-23 15:41:16 +00002282#ifndef SQLITE_OMIT_AUTHORIZATION
2283 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002284 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002285 return;
2286 }
2287#endif
2288
danielk1977c00da102006-01-07 13:21:04 +00002289 /* Require a write-lock on the table to perform this operation */
2290 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2291
drh063336a2004-11-05 20:58:39 +00002292 v = sqlite3GetVdbe(pParse);
2293 if( v==0 ) return;
2294 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002295 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002296 }else{
2297 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002298 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002299 }
danielk1977b3bf5562006-01-10 17:58:23 +00002300 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002301 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002302 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002303 if( memRootPage>=0 ){
2304 sqlite3VdbeChangeP5(v, 1);
2305 }
danielk1977c00da102006-01-07 13:21:04 +00002306 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002307 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002308 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002309 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002310 if( pIndex->onError!=OE_None ){
drh2d401ab2008-01-10 23:50:11 +00002311 int j1, j2;
2312 int regRowid;
2313
2314 regRowid = regIdxKey + pIndex->nColumn;
2315 j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
2316 j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
shane1fc41292008-07-08 22:28:48 +00002317 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
drh66a51672008-01-03 00:01:23 +00002318 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
2319 "indexed columns are not unique", P4_STATIC);
drh2d401ab2008-01-10 23:50:11 +00002320 sqlite3VdbeJumpHere(v, j1);
2321 sqlite3VdbeJumpHere(v, j2);
drh4343fea2004-11-05 23:46:15 +00002322 }
drh2d401ab2008-01-10 23:50:11 +00002323 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
2324 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002325 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002326 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002327 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2328 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002329}
2330
2331/*
drh23bf66d2004-12-14 03:34:34 +00002332** Create a new index for an SQL table. pName1.pName2 is the name of the index
2333** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002334** be NULL for a primary key or an index that is created to satisfy a
2335** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002336** as the table to be indexed. pParse->pNewTable is a table that is
2337** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002338**
drh382c0242001-10-06 16:33:02 +00002339** pList is a list of columns to be indexed. pList will be NULL if this
2340** is a primary key or unique-constraint on the most recent column added
2341** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002342*/
danielk19774adee202004-05-08 08:23:19 +00002343void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002344 Parse *pParse, /* All information about this parse */
2345 Token *pName1, /* First part of index name. May be NULL */
2346 Token *pName2, /* Second part of index name. May be NULL */
2347 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002348 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002349 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002350 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002351 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002352 int sortOrder, /* Sort order of primary key when pList==NULL */
2353 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002354){
drhfdd6e852005-12-16 01:06:16 +00002355 Table *pTab = 0; /* Table to be indexed */
2356 Index *pIndex = 0; /* The index to be created */
2357 char *zName = 0; /* Name of the index */
2358 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002359 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002360 Token nullId; /* Fake token for an empty ID list */
2361 DbFixer sFix; /* For assigning database names to pTable */
2362 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002363 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002364 Db *pDb; /* The specific table containing the indexed database */
2365 int iDb; /* Index of the database that is being written */
2366 Token *pName = 0; /* Unqualified name of the index to create */
2367 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002368 int nCol;
2369 int nExtra = 0;
2370 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002371
drh17435752007-08-16 04:30:38 +00002372 if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
danielk1977e501b892006-01-09 06:29:47 +00002373 goto exit_create_index;
2374 }
drhdaffd0e2001-04-11 14:28:42 +00002375
drh75897232000-05-29 14:26:00 +00002376 /*
2377 ** Find the table that is to be indexed. Return early if not found.
2378 */
danielk1977cbb18d22004-05-28 11:37:27 +00002379 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002380
2381 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002382 ** to search for the table. 'Fix' the table name to this db
2383 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002384 */
2385 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002386 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002387 if( iDb<0 ) goto exit_create_index;
2388
danielk197753c0f742005-03-29 03:10:59 +00002389#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002390 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002391 ** is a temp table. If so, set the database to 1. Do not do this
2392 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002393 */
danielk1977fe910332007-12-02 11:46:34 +00002394 if( !db->init.busy ){
2395 pTab = sqlite3SrcListLookup(pParse, pTblName);
2396 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2397 iDb = 1;
2398 }
danielk1977ef2cb632004-05-29 02:37:19 +00002399 }
danielk197753c0f742005-03-29 03:10:59 +00002400#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002401
2402 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2403 sqlite3FixSrcList(&sFix, pTblName)
2404 ){
drh85c23c62005-08-20 03:03:04 +00002405 /* Because the parser constructs pTblName from a single identifier,
2406 ** sqlite3FixSrcList can never fail. */
2407 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002408 }
drhca424112008-01-25 15:04:48 +00002409 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002410 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002411 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002412 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002413 }else{
drhe3c41372001-09-17 20:25:58 +00002414 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002415 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002416 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002417 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002418 }
drhfdd6e852005-12-16 01:06:16 +00002419 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002420
drh75897232000-05-29 14:26:00 +00002421 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drhc456e572008-08-11 18:44:58 +00002422 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk19774adee202004-05-08 08:23:19 +00002423 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002424 goto exit_create_index;
2425 }
danielk1977576ec6b2005-01-21 11:55:25 +00002426#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002427 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002428 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002429 goto exit_create_index;
2430 }
danielk1977576ec6b2005-01-21 11:55:25 +00002431#endif
danielk19775ee9d692006-06-21 12:36:25 +00002432#ifndef SQLITE_OMIT_VIRTUALTABLE
2433 if( IsVirtual(pTab) ){
2434 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2435 goto exit_create_index;
2436 }
2437#endif
drh75897232000-05-29 14:26:00 +00002438
2439 /*
2440 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002441 ** index or table with the same name.
2442 **
2443 ** Exception: If we are reading the names of permanent indices from the
2444 ** sqlite_master table (because some other process changed the schema) and
2445 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002446 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002447 **
2448 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002449 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2450 ** own name.
drh75897232000-05-29 14:26:00 +00002451 */
danielk1977d8123362004-06-12 09:25:12 +00002452 if( pName ){
drh17435752007-08-16 04:30:38 +00002453 zName = sqlite3NameFromToken(db, pName);
danielk19778a414492004-06-29 08:59:35 +00002454 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002455 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002456 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002457 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002458 }
danielk1977d8123362004-06-12 09:25:12 +00002459 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002460 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
danielk1977d45a0312007-03-13 16:32:25 +00002461 if( sqlite3FindTable(db, zName, 0)!=0 ){
2462 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2463 goto exit_create_index;
2464 }
2465 }
danielk197759a33f92007-03-17 10:26:59 +00002466 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2467 if( !ifNotExist ){
2468 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002469 }
danielk197759a33f92007-03-17 10:26:59 +00002470 goto exit_create_index;
2471 }
danielk1977a21c6b62005-01-24 10:25:59 +00002472 }else{
drhadbca9c2001-09-27 15:11:53 +00002473 int n;
2474 Index *pLoop;
2475 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002476 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002477 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002478 goto exit_create_index;
2479 }
drh75897232000-05-29 14:26:00 +00002480 }
2481
drhe5f9c642003-01-13 23:27:31 +00002482 /* Check for authorization to create an index.
2483 */
2484#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002485 {
drhfdd6e852005-12-16 01:06:16 +00002486 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002487 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002488 goto exit_create_index;
2489 }
2490 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002491 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002492 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002493 goto exit_create_index;
2494 }
drhe5f9c642003-01-13 23:27:31 +00002495 }
2496#endif
2497
drh75897232000-05-29 14:26:00 +00002498 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002499 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002500 ** So create a fake list to simulate this.
2501 */
2502 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002503 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
drhea678832008-12-10 19:26:22 +00002504 nullId.n = sqlite3Strlen30((char*)nullId.z);
danielk19771e536952007-08-16 10:09:01 +00002505 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002506 if( pList==0 ) goto exit_create_index;
drh1bd10f82008-12-10 21:19:56 +00002507 pList->a[0].sortOrder = (u8)sortOrder;
drh75897232000-05-29 14:26:00 +00002508 }
2509
danielk1977b3bf5562006-01-10 17:58:23 +00002510 /* Figure out how many bytes of space are required to store explicitly
2511 ** specified collation sequence names.
2512 */
2513 for(i=0; i<pList->nExpr; i++){
drh7d10d5a2008-08-20 16:35:10 +00002514 Expr *pExpr;
2515 CollSeq *pColl;
2516 if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
drhea678832008-12-10 19:26:22 +00002517 nExtra += (1 + sqlite3Strlen30(pColl->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00002518 }
2519 }
2520
drh75897232000-05-29 14:26:00 +00002521 /*
2522 ** Allocate the index structure.
2523 */
drhea678832008-12-10 19:26:22 +00002524 nName = sqlite3Strlen30(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002525 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002526 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002527 sizeof(Index) + /* Index structure */
2528 sizeof(int)*nCol + /* Index.aiColumn */
2529 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2530 sizeof(char *)*nCol + /* Index.azColl */
2531 sizeof(u8)*nCol + /* Index.aSortOrder */
2532 nName + 1 + /* Index.zName */
2533 nExtra /* Collation sequence names */
2534 );
drh17435752007-08-16 04:30:38 +00002535 if( db->mallocFailed ){
2536 goto exit_create_index;
2537 }
drh78aecb72006-02-10 18:08:09 +00002538 pIndex->azColl = (char**)(&pIndex[1]);
2539 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002540 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002541 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002542 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2543 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002544 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002545 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002546 pIndex->nColumn = pList->nExpr;
drh1bd10f82008-12-10 21:19:56 +00002547 pIndex->onError = (u8)onError;
2548 pIndex->autoIndex = (u8)(pName==0);
danielk1977da184232006-01-05 11:34:32 +00002549 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002550
drhfdd6e852005-12-16 01:06:16 +00002551 /* Check to see if we should honor DESC requests on index columns
2552 */
danielk1977da184232006-01-05 11:34:32 +00002553 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002554 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002555 }else{
2556 sortOrderMask = 0; /* Ignore DESC */
2557 }
2558
drh1ccde152000-06-17 13:12:39 +00002559 /* Scan the names of the columns of the table to be indexed and
2560 ** load the column indices into the Index structure. Report an error
2561 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002562 */
drhfdd6e852005-12-16 01:06:16 +00002563 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2564 const char *zColName = pListItem->zName;
2565 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002566 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002567 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002568
drhfdd6e852005-12-16 01:06:16 +00002569 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2570 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002571 }
2572 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002573 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002574 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002575 goto exit_create_index;
2576 }
drha34001c2007-02-02 12:44:37 +00002577 /* TODO: Add a test to make sure that the same column is not named
2578 ** more than once within the same index. Only the first instance of
2579 ** the column will ever be used by the optimizer. Note that using the
2580 ** same column more than once cannot be an error because that would
2581 ** break backwards compatibility - it needs to be a warning.
2582 */
drh967e8b72000-06-21 13:59:10 +00002583 pIndex->aiColumn[i] = j;
drh7d10d5a2008-08-20 16:35:10 +00002584 if( pListItem->pExpr && pListItem->pExpr->pColl ){
drhfdd6e852005-12-16 01:06:16 +00002585 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002586 zColl = zExtra;
drh5bb3eb92007-05-04 13:15:55 +00002587 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
drhea678832008-12-10 19:26:22 +00002588 zExtra += (sqlite3Strlen30(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002589 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002590 zColl = pTab->aCol[j].zColl;
2591 if( !zColl ){
2592 zColl = db->pDfltColl->zName;
2593 }
danielk19770202b292004-06-09 09:55:16 +00002594 }
danielk1977b3bf5562006-01-10 17:58:23 +00002595 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002596 goto exit_create_index;
2597 }
danielk1977b3bf5562006-01-10 17:58:23 +00002598 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002599 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
drh1bd10f82008-12-10 21:19:56 +00002600 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002601 }
drh51147ba2005-07-23 22:59:55 +00002602 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002603
danielk1977d8123362004-06-12 09:25:12 +00002604 if( pTab==pParse->pNewTable ){
2605 /* This routine has been called to create an automatic index as a
2606 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2607 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2608 ** i.e. one of:
2609 **
2610 ** CREATE TABLE t(x PRIMARY KEY, y);
2611 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2612 **
2613 ** Either way, check to see if the table already has such an index. If
2614 ** so, don't bother creating this one. This only applies to
2615 ** automatically created indices. Users can do as they wish with
2616 ** explicit indices.
2617 */
2618 Index *pIdx;
2619 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2620 int k;
2621 assert( pIdx->onError!=OE_None );
2622 assert( pIdx->autoIndex );
2623 assert( pIndex->onError!=OE_None );
2624
2625 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2626 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002627 const char *z1 = pIdx->azColl[k];
2628 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002629 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002630 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2631 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002632 }
2633 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002634 if( pIdx->onError!=pIndex->onError ){
2635 /* This constraint creates the same index as a previous
2636 ** constraint specified somewhere in the CREATE TABLE statement.
2637 ** However the ON CONFLICT clauses are different. If both this
2638 ** constraint and the previous equivalent constraint have explicit
2639 ** ON CONFLICT clauses this is an error. Otherwise, use the
2640 ** explicitly specified behaviour for the index.
2641 */
2642 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2643 sqlite3ErrorMsg(pParse,
2644 "conflicting ON CONFLICT clauses specified", 0);
2645 }
2646 if( pIdx->onError==OE_Default ){
2647 pIdx->onError = pIndex->onError;
2648 }
2649 }
danielk1977d8123362004-06-12 09:25:12 +00002650 goto exit_create_index;
2651 }
2652 }
2653 }
2654
drh75897232000-05-29 14:26:00 +00002655 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002656 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002657 */
drh234c39d2004-07-24 03:30:47 +00002658 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002659 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002660 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drhea678832008-12-10 19:26:22 +00002661 pIndex->zName, sqlite3Strlen30(pIndex->zName)+1,
2662 pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002663 if( p ){
2664 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002665 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002666 goto exit_create_index;
2667 }
drh5e00f6c2001-09-13 13:46:56 +00002668 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002669 if( pTblName!=0 ){
2670 pIndex->tnum = db->init.newTnum;
2671 }
drhd78eeee2001-09-13 16:18:53 +00002672 }
2673
drh1d85d932004-02-14 23:05:52 +00002674 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002675 ** involves writing the index into the master table and filling in the
2676 ** index with the current table contents.
2677 **
drh1d85d932004-02-14 23:05:52 +00002678 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2679 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002680 ** CREATE INDEX statements are read out of the master table. In
2681 ** the latter case the index already exists on disk, which is why
2682 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002683 **
danielk1977cbb18d22004-05-28 11:37:27 +00002684 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002685 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2686 ** has just been created, it contains no data and the index initialization
2687 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002688 */
drh1d85d932004-02-14 23:05:52 +00002689 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002690 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002691 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002692 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002693
danielk19774adee202004-05-08 08:23:19 +00002694 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002695 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002696
drhfdd6e852005-12-16 01:06:16 +00002697
drh063336a2004-11-05 20:58:39 +00002698 /* Create the rootpage for the index
2699 */
drhaee128d2005-02-14 20:48:18 +00002700 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002701 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002702
2703 /* Gather the complete text of the CREATE INDEX statement into
2704 ** the zStmt variable
2705 */
drhe0bc4042002-06-25 01:09:11 +00002706 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002707 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002708 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002709 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002710 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002711 pName->z);
2712 }else{
2713 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002714 /* zStmt = sqlite3MPrintf(""); */
2715 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002716 }
drh063336a2004-11-05 20:58:39 +00002717
2718 /* Add an entry in sqlite_master for this index
2719 */
2720 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002721 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002722 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2723 pIndex->zName,
2724 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002725 iMem,
drh063336a2004-11-05 20:58:39 +00002726 zStmt
2727 );
drh633e6d52008-07-28 19:34:53 +00002728 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002729
danielk1977a21c6b62005-01-24 10:25:59 +00002730 /* Fill the index with data and reparse the schema. Code an OP_Expire
2731 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002732 */
danielk1977cbb18d22004-05-28 11:37:27 +00002733 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002734 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002735 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002736 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2737 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2738 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002739 }
drh75897232000-05-29 14:26:00 +00002740 }
2741
danielk1977d8123362004-06-12 09:25:12 +00002742 /* When adding an index to the list of indices for a table, make
2743 ** sure all indices labeled OE_Replace come after all those labeled
2744 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2745 ** and INSERT.
2746 */
drh234c39d2004-07-24 03:30:47 +00002747 if( db->init.busy || pTblName==0 ){
2748 if( onError!=OE_Replace || pTab->pIndex==0
2749 || pTab->pIndex->onError==OE_Replace){
2750 pIndex->pNext = pTab->pIndex;
2751 pTab->pIndex = pIndex;
2752 }else{
2753 Index *pOther = pTab->pIndex;
2754 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2755 pOther = pOther->pNext;
2756 }
2757 pIndex->pNext = pOther->pNext;
2758 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002759 }
drh234c39d2004-07-24 03:30:47 +00002760 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002761 }
danielk1977d8123362004-06-12 09:25:12 +00002762
drh75897232000-05-29 14:26:00 +00002763 /* Clean up before exiting */
2764exit_create_index:
drh956bc922004-07-24 17:38:29 +00002765 if( pIndex ){
2766 freeIndex(pIndex);
2767 }
drh633e6d52008-07-28 19:34:53 +00002768 sqlite3ExprListDelete(db, pList);
2769 sqlite3SrcListDelete(db, pTblName);
2770 sqlite3DbFree(db, zName);
drh75897232000-05-29 14:26:00 +00002771 return;
2772}
2773
2774/*
drhd28bcb32005-12-21 14:43:11 +00002775** Generate code to make sure the file format number is at least minFormat.
2776** The generated code will increase the file format number if necessary.
2777*/
2778void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2779 Vdbe *v;
2780 v = sqlite3GetVdbe(pParse);
2781 if( v ){
drh1db639c2008-01-17 02:36:28 +00002782 int r1 = sqlite3GetTempReg(pParse);
2783 int r2 = sqlite3GetTempReg(pParse);
2784 int j1;
2785 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
drhfb982642007-08-30 01:19:59 +00002786 sqlite3VdbeUsesBtree(v, iDb);
drh1db639c2008-01-17 02:36:28 +00002787 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
2788 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
2789 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
2790 sqlite3VdbeJumpHere(v, j1);
2791 sqlite3ReleaseTempReg(pParse, r1);
2792 sqlite3ReleaseTempReg(pParse, r2);
drhd28bcb32005-12-21 14:43:11 +00002793 }
2794}
2795
2796/*
drh51147ba2005-07-23 22:59:55 +00002797** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002798** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002799**
2800** aiRowEst[0] is suppose to contain the number of elements in the index.
2801** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2802** number of rows in the table that match any particular value of the
2803** first column of the index. aiRowEst[2] is an estimate of the number
2804** of rows that match any particular combiniation of the first 2 columns
2805** of the index. And so forth. It must always be the case that
2806*
2807** aiRowEst[N]<=aiRowEst[N-1]
2808** aiRowEst[N]>=1
2809**
2810** Apart from that, we have little to go on besides intuition as to
2811** how aiRowEst[] should be initialized. The numbers generated here
2812** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002813*/
2814void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002815 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002816 int i;
drh28c4cf42005-07-27 20:41:43 +00002817 assert( a!=0 );
2818 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002819 for(i=pIdx->nColumn; i>=5; i--){
2820 a[i] = 5;
2821 }
2822 while( i>=1 ){
2823 a[i] = 11 - i;
2824 i--;
drh28c4cf42005-07-27 20:41:43 +00002825 }
2826 if( pIdx->onError!=OE_None ){
2827 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002828 }
2829}
2830
2831/*
drh74e24cd2002-01-09 03:19:59 +00002832** This routine will drop an existing named index. This routine
2833** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002834*/
drh4d91a702006-01-04 15:54:36 +00002835void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002836 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002837 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002838 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002839 int iDb;
drh75897232000-05-29 14:26:00 +00002840
drh17435752007-08-16 04:30:38 +00002841 if( pParse->nErr || db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002842 goto exit_drop_index;
2843 }
drhd24cc422003-03-27 12:51:24 +00002844 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002845 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2846 goto exit_drop_index;
2847 }
danielk19774adee202004-05-08 08:23:19 +00002848 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002849 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002850 if( !ifExists ){
2851 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2852 }
drha6ecd332004-06-10 00:29:09 +00002853 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002854 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002855 }
drh485b39b2002-07-13 03:11:52 +00002856 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002857 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002858 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002859 goto exit_drop_index;
2860 }
danielk1977da184232006-01-05 11:34:32 +00002861 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002862#ifndef SQLITE_OMIT_AUTHORIZATION
2863 {
2864 int code = SQLITE_DROP_INDEX;
2865 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002866 const char *zDb = db->aDb[iDb].zName;
2867 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002868 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002869 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002870 }
danielk1977da184232006-01-05 11:34:32 +00002871 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002872 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002873 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002874 }
drhed6c8672003-01-12 18:02:16 +00002875 }
drhe5f9c642003-01-13 23:27:31 +00002876#endif
drh75897232000-05-29 14:26:00 +00002877
2878 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002879 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002880 if( v ){
drh77658e22007-12-04 16:54:52 +00002881 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002882 sqlite3NestedParse(pParse,
2883 "DELETE FROM %Q.%s WHERE name=%Q",
2884 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2885 pIndex->zName
2886 );
danielk1977006015d2008-04-11 17:11:26 +00002887 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2888 sqlite3NestedParse(pParse,
2889 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2890 db->aDb[iDb].zName, pIndex->zName
2891 );
2892 }
drh9cbf3422008-01-17 16:22:13 +00002893 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002894 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002895 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002896 }
2897
drhd24cc422003-03-27 12:51:24 +00002898exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002899 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002900}
2901
2902/*
drhcf643722007-03-27 13:36:37 +00002903** pArray is a pointer to an array of objects. Each object in the
2904** array is szEntry bytes in size. This routine allocates a new
2905** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002906**
drhcf643722007-03-27 13:36:37 +00002907** *pnEntry is the number of entries already in use. *pnAlloc is
2908** the previously allocated size of the array. initSize is the
2909** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002910**
drhcf643722007-03-27 13:36:37 +00002911** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002912**
drhcf643722007-03-27 13:36:37 +00002913** This routine returns a pointer to the array of objects. This
2914** might be the same as the pArray parameter or it might be a different
2915** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002916*/
drhcf643722007-03-27 13:36:37 +00002917void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002918 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002919 void *pArray, /* Array of objects. Might be reallocated */
2920 int szEntry, /* Size of each object in the array */
2921 int initSize, /* Suggested initial allocation, in elements */
2922 int *pnEntry, /* Number of objects currently in use */
2923 int *pnAlloc, /* Current size of the allocation, in elements */
2924 int *pIdx /* Write the index of a new slot here */
2925){
2926 char *z;
2927 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002928 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002929 int newSize;
drhcf643722007-03-27 13:36:37 +00002930 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002931 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002932 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002933 *pIdx = -1;
2934 return pArray;
drh13449892005-09-07 21:22:45 +00002935 }
drh6a1e0712008-12-05 15:24:15 +00002936 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002937 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002938 }
drhcf643722007-03-27 13:36:37 +00002939 z = (char*)pArray;
2940 memset(&z[*pnEntry * szEntry], 0, szEntry);
2941 *pIdx = *pnEntry;
2942 ++*pnEntry;
2943 return pArray;
drh13449892005-09-07 21:22:45 +00002944}
2945
2946/*
drh75897232000-05-29 14:26:00 +00002947** Append a new element to the given IdList. Create a new IdList if
2948** need be.
drhdaffd0e2001-04-11 14:28:42 +00002949**
2950** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002951*/
drh17435752007-08-16 04:30:38 +00002952IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002953 int i;
drh75897232000-05-29 14:26:00 +00002954 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002955 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002956 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002957 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002958 }
drhcf643722007-03-27 13:36:37 +00002959 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002960 db,
drhcf643722007-03-27 13:36:37 +00002961 pList->a,
2962 sizeof(pList->a[0]),
2963 5,
2964 &pList->nId,
2965 &pList->nAlloc,
2966 &i
2967 );
drh13449892005-09-07 21:22:45 +00002968 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002969 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002970 return 0;
drh75897232000-05-29 14:26:00 +00002971 }
drh17435752007-08-16 04:30:38 +00002972 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002973 return pList;
2974}
2975
2976/*
drhfe05af82005-07-21 03:14:59 +00002977** Delete an IdList.
2978*/
drh633e6d52008-07-28 19:34:53 +00002979void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00002980 int i;
2981 if( pList==0 ) return;
2982 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00002983 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00002984 }
drh633e6d52008-07-28 19:34:53 +00002985 sqlite3DbFree(db, pList->a);
2986 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00002987}
2988
2989/*
2990** Return the index in pList of the identifier named zId. Return -1
2991** if not found.
2992*/
2993int sqlite3IdListIndex(IdList *pList, const char *zName){
2994 int i;
2995 if( pList==0 ) return -1;
2996 for(i=0; i<pList->nId; i++){
2997 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2998 }
2999 return -1;
3000}
3001
3002/*
drha78c22c2008-11-11 18:28:58 +00003003** Expand the space allocated for the given SrcList object by
3004** creating nExtra new slots beginning at iStart. iStart is zero based.
3005** New slots are zeroed.
3006**
3007** For example, suppose a SrcList initially contains two entries: A,B.
3008** To append 3 new entries onto the end, do this:
3009**
3010** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3011**
3012** After the call above it would contain: A, B, nil, nil, nil.
3013** If the iStart argument had been 1 instead of 2, then the result
3014** would have been: A, nil, nil, nil, B. To prepend the new slots,
3015** the iStart value would be 0. The result then would
3016** be: nil, nil, nil, A, B.
3017**
3018** If a memory allocation fails the SrcList is unchanged. The
3019** db->mallocFailed flag will be set to true.
3020*/
3021SrcList *sqlite3SrcListEnlarge(
3022 sqlite3 *db, /* Database connection to notify of OOM errors */
3023 SrcList *pSrc, /* The SrcList to be enlarged */
3024 int nExtra, /* Number of new slots to add to pSrc->a[] */
3025 int iStart /* Index in pSrc->a[] of first new slot */
3026){
3027 int i;
3028
3029 /* Sanity checking on calling parameters */
3030 assert( iStart>=0 );
3031 assert( nExtra>=1 );
3032 if( pSrc==0 || iStart>pSrc->nSrc ){
3033 assert( db->mallocFailed );
3034 return pSrc;
3035 }
3036
3037 /* Allocate additional space if needed */
3038 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3039 SrcList *pNew;
3040 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003041 int nGot;
drha78c22c2008-11-11 18:28:58 +00003042 pNew = sqlite3DbRealloc(db, pSrc,
3043 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3044 if( pNew==0 ){
3045 assert( db->mallocFailed );
3046 return pSrc;
3047 }
3048 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003049 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
drh1bd10f82008-12-10 21:19:56 +00003050 pSrc->nAlloc = (u16)nGot;
drha78c22c2008-11-11 18:28:58 +00003051 }
3052
3053 /* Move existing slots that come after the newly inserted slots
3054 ** out of the way */
3055 for(i=pSrc->nSrc-1; i>=iStart; i--){
3056 pSrc->a[i+nExtra] = pSrc->a[i];
3057 }
shane18e526c2008-12-10 22:30:24 +00003058 pSrc->nSrc += (i16)nExtra;
drha78c22c2008-11-11 18:28:58 +00003059
3060 /* Zero the newly allocated slots */
3061 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3062 for(i=iStart; i<iStart+nExtra; i++){
3063 pSrc->a[i].iCursor = -1;
3064 }
3065
3066 /* Return a pointer to the enlarged SrcList */
3067 return pSrc;
3068}
3069
3070
3071/*
drhad3cab52002-05-24 02:04:32 +00003072** Append a new table name to the given SrcList. Create a new SrcList if
3073** need be. A new entry is created in the SrcList even if pToken is NULL.
3074**
drha78c22c2008-11-11 18:28:58 +00003075** A SrcList is returned, or NULL if there is an OOM error. The returned
3076** SrcList might be the same as the SrcList that was input or it might be
3077** a new one. If an OOM error does occurs, then the prior value of pList
3078** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003079**
3080** If pDatabase is not null, it means that the table has an optional
3081** database name prefix. Like this: "database.table". The pDatabase
3082** points to the table name and the pTable points to the database name.
3083** The SrcList.a[].zName field is filled with the table name which might
3084** come from pTable (if pDatabase is NULL) or from pDatabase.
3085** SrcList.a[].zDatabase is filled with the database name from pTable,
3086** or with NULL if no database is specified.
3087**
3088** In other words, if call like this:
3089**
drh17435752007-08-16 04:30:38 +00003090** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003091**
3092** Then B is a table name and the database name is unspecified. If called
3093** like this:
3094**
drh17435752007-08-16 04:30:38 +00003095** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003096**
3097** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00003098*/
drh17435752007-08-16 04:30:38 +00003099SrcList *sqlite3SrcListAppend(
3100 sqlite3 *db, /* Connection to notify of malloc failures */
3101 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3102 Token *pTable, /* Table to append */
3103 Token *pDatabase /* Database of the table */
3104){
drha99db3b2004-06-19 14:49:12 +00003105 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003106 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003107 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003108 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003109 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003110 }
drha78c22c2008-11-11 18:28:58 +00003111 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3112 if( db->mallocFailed ){
3113 sqlite3SrcListDelete(db, pList);
3114 return 0;
drhad3cab52002-05-24 02:04:32 +00003115 }
drha78c22c2008-11-11 18:28:58 +00003116 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003117 if( pDatabase && pDatabase->z==0 ){
3118 pDatabase = 0;
3119 }
3120 if( pDatabase && pTable ){
3121 Token *pTemp = pDatabase;
3122 pDatabase = pTable;
3123 pTable = pTemp;
3124 }
drh17435752007-08-16 04:30:38 +00003125 pItem->zName = sqlite3NameFromToken(db, pTable);
3126 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003127 return pList;
3128}
3129
3130/*
drhdfe88ec2008-11-03 20:55:06 +00003131** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003132*/
danielk19774adee202004-05-08 08:23:19 +00003133void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003134 int i;
drh9b3187e2005-01-18 14:45:47 +00003135 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003136 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003137 if( pList ){
3138 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3139 if( pItem->iCursor>=0 ) break;
3140 pItem->iCursor = pParse->nTab++;
3141 if( pItem->pSelect ){
3142 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3143 }
drh63eb5f22003-04-29 16:20:44 +00003144 }
3145 }
3146}
3147
3148/*
drhad3cab52002-05-24 02:04:32 +00003149** Delete an entire SrcList including all its substructure.
3150*/
drh633e6d52008-07-28 19:34:53 +00003151void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003152 int i;
drhbe5c89a2004-07-26 00:31:09 +00003153 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003154 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003155 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003156 sqlite3DbFree(db, pItem->zDatabase);
3157 sqlite3DbFree(db, pItem->zName);
3158 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003159 sqlite3DbFree(db, pItem->zIndex);
danielk1977a04a34f2007-04-16 15:06:25 +00003160 sqlite3DeleteTable(pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003161 sqlite3SelectDelete(db, pItem->pSelect);
3162 sqlite3ExprDelete(db, pItem->pOn);
3163 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003164 }
drh633e6d52008-07-28 19:34:53 +00003165 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003166}
3167
drh982cef72000-05-30 16:27:03 +00003168/*
drh61dfc312006-12-16 16:25:15 +00003169** This routine is called by the parser to add a new term to the
3170** end of a growing FROM clause. The "p" parameter is the part of
3171** the FROM clause that has already been constructed. "p" is NULL
3172** if this is the first term of the FROM clause. pTable and pDatabase
3173** are the name of the table and database named in the FROM clause term.
3174** pDatabase is NULL if the database name qualifier is missing - the
3175** usual case. If the term has a alias, then pAlias points to the
3176** alias token. If the term is a subquery, then pSubquery is the
3177** SELECT statement that the subquery encodes. The pTable and
3178** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3179** parameters are the content of the ON and USING clauses.
3180**
3181** Return a new SrcList which encodes is the FROM with the new
3182** term added.
3183*/
3184SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003185 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003186 SrcList *p, /* The left part of the FROM clause already seen */
3187 Token *pTable, /* Name of the table to add to the FROM clause */
3188 Token *pDatabase, /* Name of the database containing pTable */
3189 Token *pAlias, /* The right-hand side of the AS subexpression */
3190 Select *pSubquery, /* A subquery used in place of a table name */
3191 Expr *pOn, /* The ON clause of a join */
3192 IdList *pUsing /* The USING clause of a join */
3193){
3194 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003195 sqlite3 *db = pParse->db;
3196 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh61dfc312006-12-16 16:25:15 +00003197 if( p==0 || p->nSrc==0 ){
drh633e6d52008-07-28 19:34:53 +00003198 sqlite3ExprDelete(db, pOn);
3199 sqlite3IdListDelete(db, pUsing);
3200 sqlite3SelectDelete(db, pSubquery);
drh61dfc312006-12-16 16:25:15 +00003201 return p;
3202 }
3203 pItem = &p->a[p->nSrc-1];
3204 if( pAlias && pAlias->n ){
drh17435752007-08-16 04:30:38 +00003205 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003206 }
3207 pItem->pSelect = pSubquery;
3208 pItem->pOn = pOn;
3209 pItem->pUsing = pUsing;
3210 return p;
3211}
3212
3213/*
danielk1977b1c685b2008-10-06 16:18:39 +00003214** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3215** element of the source-list passed as the second argument.
3216*/
3217void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3218 if( pIndexedBy && p && p->nSrc>0 ){
3219 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3220 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3221 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3222 /* A "NOT INDEXED" clause was supplied. See parse.y
3223 ** construct "indexed_opt" for details. */
3224 pItem->notIndexed = 1;
3225 }else{
3226 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3227 }
3228 }
3229}
3230
3231/*
drh61dfc312006-12-16 16:25:15 +00003232** When building up a FROM clause in the parser, the join operator
3233** is initially attached to the left operand. But the code generator
3234** expects the join operator to be on the right operand. This routine
3235** Shifts all join operators from left to right for an entire FROM
3236** clause.
3237**
3238** Example: Suppose the join is like this:
3239**
3240** A natural cross join B
3241**
3242** The operator is "natural cross join". The A and B operands are stored
3243** in p->a[0] and p->a[1], respectively. The parser initially stores the
3244** operator with A. This routine shifts that operator over to B.
3245*/
3246void sqlite3SrcListShiftJoinType(SrcList *p){
3247 if( p && p->a ){
3248 int i;
3249 for(i=p->nSrc-1; i>0; i--){
3250 p->a[i].jointype = p->a[i-1].jointype;
3251 }
3252 p->a[0].jointype = 0;
3253 }
3254}
3255
3256/*
drhc4a3c772001-04-04 11:48:57 +00003257** Begin a transaction
3258*/
drh684917c2004-10-05 02:41:42 +00003259void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003260 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003261 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003262 int i;
drh5e00f6c2001-09-13 13:46:56 +00003263
drh001bbcb2003-03-19 03:14:00 +00003264 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003265 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003266 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003267
3268 v = sqlite3GetVdbe(pParse);
3269 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003270 if( type!=TK_DEFERRED ){
3271 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003272 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003273 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003274 }
3275 }
drh66a51672008-01-03 00:01:23 +00003276 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003277}
3278
3279/*
3280** Commit a transaction
3281*/
danielk19774adee202004-05-08 08:23:19 +00003282void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003283 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003284 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003285
drh001bbcb2003-03-19 03:14:00 +00003286 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003287 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003288 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003289
3290 v = sqlite3GetVdbe(pParse);
3291 if( v ){
drh66a51672008-01-03 00:01:23 +00003292 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003293 }
drhc4a3c772001-04-04 11:48:57 +00003294}
3295
3296/*
3297** Rollback a transaction
3298*/
danielk19774adee202004-05-08 08:23:19 +00003299void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003300 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003301 Vdbe *v;
3302
drh001bbcb2003-03-19 03:14:00 +00003303 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003304 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003305 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003306
danielk19774adee202004-05-08 08:23:19 +00003307 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003308 if( v ){
drh66a51672008-01-03 00:01:23 +00003309 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003310 }
drhc4a3c772001-04-04 11:48:57 +00003311}
drhf57b14a2001-09-14 18:54:08 +00003312
3313/*
danielk1977fd7f0452008-12-17 17:30:26 +00003314** This function is called by the parser when it parses a command to create,
3315** release or rollback an SQL savepoint.
3316*/
3317void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
danielk1977ab9b7032008-12-30 06:24:58 +00003318 char *zName = sqlite3NameFromToken(pParse->db, pName);
3319 if( zName ){
3320 Vdbe *v = sqlite3GetVdbe(pParse);
3321#ifndef SQLITE_OMIT_AUTHORIZATION
3322 static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
3323 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
3324#endif
3325 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
3326 sqlite3DbFree(pParse->db, zName);
3327 return;
3328 }
3329 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
danielk1977fd7f0452008-12-17 17:30:26 +00003330 }
3331}
3332
3333/*
drhdc3ff9c2004-08-18 02:10:15 +00003334** Make sure the TEMP database is open and available for use. Return
3335** the number of errors. Leave any error messages in the pParse structure.
3336*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003337int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003338 sqlite3 *db = pParse->db;
3339 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003340 int rc;
3341 static const int flags =
3342 SQLITE_OPEN_READWRITE |
3343 SQLITE_OPEN_CREATE |
3344 SQLITE_OPEN_EXCLUSIVE |
3345 SQLITE_OPEN_DELETEONCLOSE |
3346 SQLITE_OPEN_TEMP_DB;
3347
3348 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
drhc797d4d2007-05-08 01:08:49 +00003349 &db->aDb[1].pBt);
drhdc3ff9c2004-08-18 02:10:15 +00003350 if( rc!=SQLITE_OK ){
3351 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3352 "file for storing temporary tables");
3353 pParse->rc = rc;
3354 return 1;
3355 }
drh60a713c2008-01-21 16:22:45 +00003356 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
danielk197714db2662006-01-09 16:12:04 +00003357 assert( db->aDb[1].pSchema );
drhfdc40e92008-04-17 20:59:37 +00003358 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
3359 db->dfltJournalMode);
drhdc3ff9c2004-08-18 02:10:15 +00003360 }
3361 return 0;
3362}
3363
3364/*
drh80242052004-06-09 00:48:12 +00003365** Generate VDBE code that will verify the schema cookie and start
3366** a read-transaction for all named database files.
3367**
3368** It is important that all schema cookies be verified and all
3369** read transactions be started before anything else happens in
3370** the VDBE program. But this routine can be called after much other
3371** code has been generated. So here is what we do:
3372**
drhc275b4e2004-07-19 17:25:24 +00003373** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003374** will jump to a subroutine at the end of the program. Then we
3375** record every database that needs its schema verified in the
3376** pParse->cookieMask field. Later, after all other code has been
3377** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003378** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003379** will be made to point to that subroutine. The generation of the
3380** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003381**
3382** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3383** schema on any databases. This can be used to position the OP_Goto
3384** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003385*/
danielk19774adee202004-05-08 08:23:19 +00003386void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003387 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003388 Vdbe *v;
3389 int mask;
3390
3391 v = sqlite3GetVdbe(pParse);
3392 if( v==0 ) return; /* This only happens if there was a prior error */
3393 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003394 if( pParse->cookieGoto==0 ){
drh66a51672008-01-03 00:01:23 +00003395 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003396 }
drhc275b4e2004-07-19 17:25:24 +00003397 if( iDb>=0 ){
3398 assert( iDb<db->nDb );
3399 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003400 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003401 mask = 1<<iDb;
3402 if( (pParse->cookieMask & mask)==0 ){
3403 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003404 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003405 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003406 sqlite3OpenTempDatabase(pParse);
3407 }
drhc275b4e2004-07-19 17:25:24 +00003408 }
drh001bbcb2003-03-19 03:14:00 +00003409 }
drh001bbcb2003-03-19 03:14:00 +00003410}
3411
3412/*
drh1c928532002-01-31 15:54:21 +00003413** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003414** might change the database.
3415**
3416** This routine starts a new transaction if we are not already within
3417** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003418** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003419** be set for operations that might fail (due to a constraint) part of
3420** the way through and which will need to undo some writes without having to
3421** rollback the whole transaction. For operations where all constraints
3422** can be checked before any changes are made to the database, it is never
3423** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003424**
drh8bf8dc92003-05-17 17:35:10 +00003425** Only database iDb and the temp database are made writable by this call.
3426** If iDb==0, then the main and temp databases are made writable. If
3427** iDb==1 then only the temp database is made writable. If iDb>1 then the
3428** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003429*/
drh7f0f12e2004-05-21 13:39:50 +00003430void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003431 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003432 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003433 sqlite3CodeVerifySchema(pParse, iDb);
3434 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003435 if( setStatement && pParse->nested==0 ){
drh66a51672008-01-03 00:01:23 +00003436 sqlite3VdbeAddOp1(v, OP_Statement, iDb);
danielk19771d850a72004-05-31 08:26:49 +00003437 }
danielk197753c0f742005-03-29 03:10:59 +00003438 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003439 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003440 }
3441}
3442
drh4343fea2004-11-05 23:46:15 +00003443/*
3444** Check to see if pIndex uses the collating sequence pColl. Return
3445** true if it does and false if it does not.
3446*/
3447#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003448static int collationMatch(const char *zColl, Index *pIndex){
3449 int i;
3450 for(i=0; i<pIndex->nColumn; i++){
3451 const char *z = pIndex->azColl[i];
3452 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3453 return 1;
3454 }
drh4343fea2004-11-05 23:46:15 +00003455 }
3456 return 0;
3457}
3458#endif
3459
3460/*
3461** Recompute all indices of pTab that use the collating sequence pColl.
3462** If pColl==0 then recompute all indices of pTab.
3463*/
3464#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003465static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003466 Index *pIndex; /* An index associated with pTab */
3467
3468 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003469 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003470 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3471 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003472 sqlite3RefillIndex(pParse, pIndex, -1);
3473 }
3474 }
3475}
3476#endif
3477
3478/*
3479** Recompute all indices of all tables in all databases where the
3480** indices use the collating sequence pColl. If pColl==0 then recompute
3481** all indices everywhere.
3482*/
3483#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003484static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003485 Db *pDb; /* A single database */
3486 int iDb; /* The database index number */
3487 sqlite3 *db = pParse->db; /* The database connection */
3488 HashElem *k; /* For looping over tables in pDb */
3489 Table *pTab; /* A table in the database */
3490
3491 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003492 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003493 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003494 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003495 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003496 }
3497 }
3498}
3499#endif
3500
3501/*
drheee46cf2004-11-06 00:02:48 +00003502** Generate code for the REINDEX command.
3503**
3504** REINDEX -- 1
3505** REINDEX <collation> -- 2
3506** REINDEX ?<database>.?<tablename> -- 3
3507** REINDEX ?<database>.?<indexname> -- 4
3508**
3509** Form 1 causes all indices in all attached databases to be rebuilt.
3510** Form 2 rebuilds all indices in all databases that use the named
3511** collating function. Forms 3 and 4 rebuild the named index or all
3512** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003513*/
3514#ifndef SQLITE_OMIT_REINDEX
3515void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3516 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3517 char *z; /* Name of a table or index */
3518 const char *zDb; /* Name of the database */
3519 Table *pTab; /* A table in the database */
3520 Index *pIndex; /* An index associated with pTab */
3521 int iDb; /* The database index number */
3522 sqlite3 *db = pParse->db; /* The database connection */
3523 Token *pObjName; /* Name of the table or index to be reindexed */
3524
danielk197733a5edc2005-01-27 00:22:02 +00003525 /* Read the database schema. If an error occurs, leave an error message
3526 ** and code in pParse and return NULL. */
3527 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003528 return;
danielk197733a5edc2005-01-27 00:22:02 +00003529 }
3530
drhe497f002004-11-07 13:01:49 +00003531 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003532 reindexDatabases(pParse, 0);
3533 return;
drhe497f002004-11-07 13:01:49 +00003534 }else if( pName2==0 || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003535 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003536 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003537 zColl = sqlite3NameFromToken(pParse->db, pName1);
3538 if( !zColl ) return;
3539 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
drh4343fea2004-11-05 23:46:15 +00003540 if( pColl ){
danielk1977f0113002006-01-24 12:09:17 +00003541 if( zColl ){
3542 reindexDatabases(pParse, zColl);
drh633e6d52008-07-28 19:34:53 +00003543 sqlite3DbFree(db, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003544 }
drh4343fea2004-11-05 23:46:15 +00003545 return;
3546 }
drh633e6d52008-07-28 19:34:53 +00003547 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003548 }
3549 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3550 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003551 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003552 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003553 zDb = db->aDb[iDb].zName;
3554 pTab = sqlite3FindTable(db, z, zDb);
3555 if( pTab ){
3556 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003557 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003558 return;
3559 }
3560 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003561 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003562 if( pIndex ){
3563 sqlite3BeginWriteOperation(pParse, 0, iDb);
3564 sqlite3RefillIndex(pParse, pIndex, -1);
3565 return;
3566 }
3567 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3568}
3569#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003570
3571/*
3572** Return a dynamicly allocated KeyInfo structure that can be used
3573** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3574**
3575** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003576** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003577** pointer. If an error occurs (out of memory or missing collation
3578** sequence), NULL is returned and the state of pParse updated to reflect
3579** the error.
3580*/
3581KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3582 int i;
3583 int nCol = pIdx->nColumn;
3584 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003585 sqlite3 *db = pParse->db;
3586 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003587
3588 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003589 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003590 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3591 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3592 for(i=0; i<nCol; i++){
3593 char *zColl = pIdx->azColl[i];
3594 assert( zColl );
3595 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3596 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3597 }
drh1bd10f82008-12-10 21:19:56 +00003598 pKey->nField = (u16)nCol;
danielk1977b3bf5562006-01-10 17:58:23 +00003599 }
3600
3601 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003602 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003603 pKey = 0;
3604 }
3605 return pKey;
3606}