blob: bc242de61bf763cff1ec261b849cbc45bb467997 [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**
drh6a1e0712008-12-05 15:24:15 +000025** $Id: build.c,v 1.504 2008/12/05 15:24:16 drh Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
drhf57b14a2001-09-14 18:54:08 +000028#include <ctype.h>
drh75897232000-05-29 14:26:00 +000029
30/*
drhe0bc4042002-06-25 01:09:11 +000031** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000032** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000033*/
danielk19774adee202004-05-08 08:23:19 +000034void sqlite3BeginParse(Parse *pParse, int explainFlag){
drhe0bc4042002-06-25 01:09:11 +000035 pParse->explain = explainFlag;
drh7c972de2003-09-06 22:18:07 +000036 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000037}
38
danielk1977c00da102006-01-07 13:21:04 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
41** The TableLock structure is only used by the sqlite3TableLock() and
42** codeTableLocks() functions.
43*/
44struct TableLock {
drhd698bc12006-03-23 23:33:26 +000045 int iDb; /* The database containing the table to be locked */
46 int iTab; /* The root page of the table to be locked */
47 u8 isWriteLock; /* True for write lock. False for a read lock */
48 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000049};
50
51/*
drhd698bc12006-03-23 23:33:26 +000052** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000053**
drhd698bc12006-03-23 23:33:26 +000054** The table to be locked has root page iTab and is found in database iDb.
55** A read or a write lock can be taken depending on isWritelock.
56**
57** This routine just records the fact that the lock is desired. The
58** code to make the lock occur is generated by a later call to
59** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000060*/
61void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000062 Parse *pParse, /* Parsing context */
63 int iDb, /* Index of the database containing the table to lock */
64 int iTab, /* Root page number of the table to be locked */
65 u8 isWriteLock, /* True for a write lock */
66 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000067){
68 int i;
69 int nBytes;
70 TableLock *p;
danielk1977c00da102006-01-07 13:21:04 +000071
drhe53831d2007-08-17 01:14:38 +000072 if( iDb<0 ){
danielk1977c00da102006-01-07 13:21:04 +000073 return;
74 }
75
76 for(i=0; i<pParse->nTableLock; i++){
77 p = &pParse->aTableLock[i];
78 if( p->iDb==iDb && p->iTab==iTab ){
79 p->isWriteLock = (p->isWriteLock || isWriteLock);
80 return;
81 }
82 }
83
84 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
drh17435752007-08-16 04:30:38 +000085 pParse->aTableLock =
86 sqlite3DbReallocOrFree(pParse->db, pParse->aTableLock, nBytes);
danielk1977c00da102006-01-07 13:21:04 +000087 if( pParse->aTableLock ){
88 p = &pParse->aTableLock[pParse->nTableLock++];
89 p->iDb = iDb;
90 p->iTab = iTab;
91 p->isWriteLock = isWriteLock;
92 p->zName = zName;
drhf3a65f72007-08-22 20:18:21 +000093 }else{
94 pParse->nTableLock = 0;
95 pParse->db->mallocFailed = 1;
danielk1977c00da102006-01-07 13:21:04 +000096 }
97}
98
99/*
100** Code an OP_TableLock instruction for each table locked by the
101** statement (configured by calls to sqlite3TableLock()).
102*/
103static void codeTableLocks(Parse *pParse){
104 int i;
105 Vdbe *pVdbe;
danielk1977c00da102006-01-07 13:21:04 +0000106
107 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
108 return;
109 }
110
111 for(i=0; i<pParse->nTableLock; i++){
112 TableLock *p = &pParse->aTableLock[i];
113 int p1 = p->iDb;
drh6a9ad3d2008-04-02 16:29:30 +0000114 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
115 p->zName, P4_STATIC);
danielk1977c00da102006-01-07 13:21:04 +0000116 }
117}
118#else
119 #define codeTableLocks(x)
120#endif
121
drhe0bc4042002-06-25 01:09:11 +0000122/*
drh75897232000-05-29 14:26:00 +0000123** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000124** parsed and a VDBE program to execute that statement has been
125** prepared. This routine puts the finishing touches on the
126** VDBE program and resets the pParse structure for the next
127** parse.
drh75897232000-05-29 14:26:00 +0000128**
129** Note that if an error occurred, it might be the case that
130** no VDBE code was generated.
131*/
drh80242052004-06-09 00:48:12 +0000132void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000133 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000134 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000135
drh17435752007-08-16 04:30:38 +0000136 db = pParse->db;
137 if( db->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000138 if( pParse->nested ) return;
drhc4dd3fd2008-01-22 01:48:05 +0000139 if( pParse->nErr ) return;
danielk197748d0d862005-02-01 03:09:52 +0000140
drh80242052004-06-09 00:48:12 +0000141 /* Begin by generating some termination code at the end of the
142 ** vdbe program
143 */
drh80242052004-06-09 00:48:12 +0000144 v = sqlite3GetVdbe(pParse);
145 if( v ){
drh66a51672008-01-03 00:01:23 +0000146 sqlite3VdbeAddOp0(v, OP_Halt);
drh0e3d7472004-06-19 17:33:07 +0000147
148 /* The cookie mask contains one bit for each database file open.
149 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
150 ** set for each database that is used. Generate code to start a
151 ** transaction on each used database and to verify the schema cookie
152 ** on each used database.
153 */
drhc275b4e2004-07-19 17:25:24 +0000154 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000155 u32 mask;
drh26e4a8b2008-05-01 17:16:52 +0000156 int iDb;
drhd654be82005-09-20 17:42:23 +0000157 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000158 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
159 if( (mask & pParse->cookieMask)==0 ) continue;
drhfb982642007-08-30 01:19:59 +0000160 sqlite3VdbeUsesBtree(v, iDb);
drh66a51672008-01-03 00:01:23 +0000161 sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
162 sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +0000163 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000164#ifndef SQLITE_OMIT_VIRTUALTABLE
drh26e4a8b2008-05-01 17:16:52 +0000165 {
166 int i;
167 for(i=0; i<pParse->nVtabLock; i++){
168 char *vtab = (char *)pParse->apVtabLock[i]->pVtab;
169 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
170 }
171 pParse->nVtabLock = 0;
danielk1977f9e7dda2006-06-16 16:08:53 +0000172 }
173#endif
danielk1977c00da102006-01-07 13:21:04 +0000174
175 /* Once all the cookies have been verified and transactions opened,
176 ** obtain the required table-locks. This is a no-op unless the
177 ** shared-cache feature is enabled.
178 */
179 codeTableLocks(pParse);
drh66a51672008-01-03 00:01:23 +0000180 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000181 }
drh80242052004-06-09 00:48:12 +0000182
drh19e2d372005-08-29 23:00:03 +0000183#ifndef SQLITE_OMIT_TRACE
drh949f9cd2008-01-12 21:35:57 +0000184 if( !db->init.busy ){
185 /* Change the P4 argument of the first opcode (which will always be
186 ** an OP_Trace) to be the complete text of the current SQL statement.
187 */
188 VdbeOp *pOp = sqlite3VdbeGetOp(v, 0);
189 if( pOp && pOp->opcode==OP_Trace ){
190 sqlite3VdbeChangeP4(v, 0, pParse->zSql, pParse->zTail-pParse->zSql);
191 }
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
drh0a687d12008-07-08 14:52:07 +0000372 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen(zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000373 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000374 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000375}
376
377/*
drhc96d8532005-05-03 12:30:33 +0000378** For the index called zIdxName which is found in the database iDb,
379** unlike that index from its Table then remove the index from
380** the index hash table and free all memory structures associated
381** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000382*/
drh9bb575f2004-09-06 17:24:11 +0000383void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000384 Index *pIndex;
385 int len;
danielk1977da184232006-01-05 11:34:32 +0000386 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000387
drh0a687d12008-07-08 14:52:07 +0000388 len = sqlite3Strlen(db, zIdxName);
danielk1977da184232006-01-05 11:34:32 +0000389 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
drh956bc922004-07-24 17:38:29 +0000390 if( pIndex ){
391 if( pIndex->pTable->pIndex==pIndex ){
392 pIndex->pTable->pIndex = pIndex->pNext;
393 }else{
394 Index *p;
395 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
396 if( p && p->pNext==pIndex ){
397 p->pNext = pIndex->pNext;
398 }
drh5e00f6c2001-09-13 13:46:56 +0000399 }
drh956bc922004-07-24 17:38:29 +0000400 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000401 }
drh956bc922004-07-24 17:38:29 +0000402 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000403}
404
405/*
drhe0bc4042002-06-25 01:09:11 +0000406** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000407** a single database. This routine is called to reclaim memory
408** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000409** if there were schema changes during the transaction or if a
410** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000411**
412** If iDb<=0 then reset the internal schema tables for all database
413** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000414** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000415*/
drh9bb575f2004-09-06 17:24:11 +0000416void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000417 int i, j;
drh1c2d8412003-03-31 00:30:47 +0000418 assert( iDb>=0 && iDb<db->nDb );
danielk19774eab8b72007-12-27 15:12:16 +0000419
420 if( iDb==0 ){
421 sqlite3BtreeEnterAll(db);
422 }
drh1c2d8412003-03-31 00:30:47 +0000423 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000424 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000425 if( pDb->pSchema ){
danielk19774eab8b72007-12-27 15:12:16 +0000426 assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
danielk1977de0fe3e2006-01-06 06:33:12 +0000427 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000428 }
drh1c2d8412003-03-31 00:30:47 +0000429 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000430 }
drh1c2d8412003-03-31 00:30:47 +0000431 assert( iDb==0 );
432 db->flags &= ~SQLITE_InternChanges;
danielk19774eab8b72007-12-27 15:12:16 +0000433 sqlite3BtreeLeaveAll(db);
drh1c2d8412003-03-31 00:30:47 +0000434
435 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000436 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000437 ** opportunity to do this here since we have just deleted all of the
438 ** schema hash tables and therefore do not have to make any changes
439 ** to any of those tables.
440 */
drh4d189ca2004-02-12 18:46:38 +0000441 for(i=0; i<db->nDb; i++){
442 struct Db *pDb = &db->aDb[i];
443 if( pDb->pBt==0 ){
444 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
445 pDb->pAux = 0;
446 }
447 }
drh1c2d8412003-03-31 00:30:47 +0000448 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000449 struct Db *pDb = &db->aDb[i];
450 if( pDb->pBt==0 ){
drh633e6d52008-07-28 19:34:53 +0000451 sqlite3DbFree(db, pDb->zName);
drh4d189ca2004-02-12 18:46:38 +0000452 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000453 continue;
454 }
455 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000456 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000457 }
drh8bf8dc92003-05-17 17:35:10 +0000458 j++;
drh1c2d8412003-03-31 00:30:47 +0000459 }
460 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
461 db->nDb = j;
462 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
463 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
drh633e6d52008-07-28 19:34:53 +0000464 sqlite3DbFree(db, db->aDb);
drh1c2d8412003-03-31 00:30:47 +0000465 db->aDb = db->aDbStatic;
466 }
drhe0bc4042002-06-25 01:09:11 +0000467}
468
469/*
drhe0bc4042002-06-25 01:09:11 +0000470** This routine is called when a commit occurs.
471*/
drh9bb575f2004-09-06 17:24:11 +0000472void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000473 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000474}
475
476/*
drh956bc922004-07-24 17:38:29 +0000477** Clear the column names from a table or view.
478*/
479static void sqliteResetColumnNames(Table *pTable){
480 int i;
481 Column *pCol;
drh633e6d52008-07-28 19:34:53 +0000482 sqlite3 *db = pTable->db;
drh956bc922004-07-24 17:38:29 +0000483 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000484 if( (pCol = pTable->aCol)!=0 ){
485 for(i=0; i<pTable->nCol; i++, pCol++){
drh633e6d52008-07-28 19:34:53 +0000486 sqlite3DbFree(db, pCol->zName);
487 sqlite3ExprDelete(db, pCol->pDflt);
488 sqlite3DbFree(db, pCol->zType);
489 sqlite3DbFree(db, pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000490 }
drh633e6d52008-07-28 19:34:53 +0000491 sqlite3DbFree(db, pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000492 }
drh956bc922004-07-24 17:38:29 +0000493 pTable->aCol = 0;
494 pTable->nCol = 0;
495}
496
497/*
drh75897232000-05-29 14:26:00 +0000498** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000499** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000500**
501** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000502** the table data structure from the hash table. Nor does it remove
503** foreign keys from the sqlite.aFKey hash table. But it does destroy
504** memory structures of the indices and foreign keys associated with
505** the table.
drh75897232000-05-29 14:26:00 +0000506*/
danielk1977a04a34f2007-04-16 15:06:25 +0000507void sqlite3DeleteTable(Table *pTable){
drh75897232000-05-29 14:26:00 +0000508 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000509 FKey *pFKey, *pNextFKey;
drh633e6d52008-07-28 19:34:53 +0000510 sqlite3 *db;
drhc2eef3b2002-08-31 18:53:06 +0000511
drh75897232000-05-29 14:26:00 +0000512 if( pTable==0 ) return;
drh633e6d52008-07-28 19:34:53 +0000513 db = pTable->db;
drhc2eef3b2002-08-31 18:53:06 +0000514
drhed8a3bb2005-06-06 21:19:56 +0000515 /* Do not delete the table until the reference count reaches zero. */
516 pTable->nRef--;
517 if( pTable->nRef>0 ){
518 return;
519 }
520 assert( pTable->nRef==0 );
521
drhc2eef3b2002-08-31 18:53:06 +0000522 /* Delete all indices associated with this table
523 */
524 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
525 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000526 assert( pIndex->pSchema==pTable->pSchema );
drh74161702006-02-24 02:53:49 +0000527 sqliteDeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000528 }
529
danielk1977576ec6b2005-01-21 11:55:25 +0000530#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000531 /* Delete all foreign keys associated with this table. The keys
danielk1977a04a34f2007-04-16 15:06:25 +0000532 ** should have already been unlinked from the pSchema->aFKey hash table
drhc2eef3b2002-08-31 18:53:06 +0000533 */
534 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
535 pNextFKey = pFKey->pNextFrom;
danielk1977da184232006-01-05 11:34:32 +0000536 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
drhd24cc422003-03-27 12:51:24 +0000537 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drh633e6d52008-07-28 19:34:53 +0000538 sqlite3DbFree(db, pFKey);
drhc2eef3b2002-08-31 18:53:06 +0000539 }
danielk1977576ec6b2005-01-21 11:55:25 +0000540#endif
drhc2eef3b2002-08-31 18:53:06 +0000541
542 /* Delete the Table structure itself.
543 */
drh956bc922004-07-24 17:38:29 +0000544 sqliteResetColumnNames(pTable);
drh633e6d52008-07-28 19:34:53 +0000545 sqlite3DbFree(db, pTable->zName);
546 sqlite3DbFree(db, pTable->zColAff);
547 sqlite3SelectDelete(db, pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000548#ifndef SQLITE_OMIT_CHECK
drh633e6d52008-07-28 19:34:53 +0000549 sqlite3ExprDelete(db, pTable->pCheck);
drhffe07b22005-11-03 00:41:17 +0000550#endif
drhb9bb7c12006-06-11 23:41:55 +0000551 sqlite3VtabClear(pTable);
drh633e6d52008-07-28 19:34:53 +0000552 sqlite3DbFree(db, pTable);
drh75897232000-05-29 14:26:00 +0000553}
554
555/*
drh5edc3122001-09-13 21:53:09 +0000556** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000557** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000558*/
drh9bb575f2004-09-06 17:24:11 +0000559void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000560 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000561 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000562 Db *pDb;
563
drhd229ca92002-01-09 13:30:41 +0000564 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000565 assert( iDb>=0 && iDb<db->nDb );
566 assert( zTabName && zTabName[0] );
567 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +0000568 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
drh956bc922004-07-24 17:38:29 +0000569 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000570#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000571 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
572 int nTo = strlen(pF1->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +0000573 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
drh956bc922004-07-24 17:38:29 +0000574 if( pF2==pF1 ){
danielk1977da184232006-01-05 11:34:32 +0000575 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
drh956bc922004-07-24 17:38:29 +0000576 }else{
577 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
578 if( pF2 ){
579 pF2->pNextTo = pF1->pNextTo;
580 }
drhc2eef3b2002-08-31 18:53:06 +0000581 }
582 }
danielk1977576ec6b2005-01-21 11:55:25 +0000583#endif
danielk1977a04a34f2007-04-16 15:06:25 +0000584 sqlite3DeleteTable(p);
drhc2eef3b2002-08-31 18:53:06 +0000585 }
drh956bc922004-07-24 17:38:29 +0000586 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000587}
588
589/*
drha99db3b2004-06-19 14:49:12 +0000590** Given a token, return a string that consists of the text of that
591** token with any quotations removed. Space to hold the returned string
592** is obtained from sqliteMalloc() and must be freed by the calling
593** function.
drh75897232000-05-29 14:26:00 +0000594**
drhc96d8532005-05-03 12:30:33 +0000595** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000596** are not \000 terminated and are not persistent. The returned string
597** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000598*/
drh17435752007-08-16 04:30:38 +0000599char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
drha99db3b2004-06-19 14:49:12 +0000600 char *zName;
601 if( pName ){
drh17435752007-08-16 04:30:38 +0000602 zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
drha99db3b2004-06-19 14:49:12 +0000603 sqlite3Dequote(zName);
604 }else{
605 zName = 0;
606 }
drh75897232000-05-29 14:26:00 +0000607 return zName;
608}
609
610/*
danielk1977cbb18d22004-05-28 11:37:27 +0000611** Open the sqlite_master table stored in database number iDb for
612** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000613*/
danielk1977c00da102006-01-07 13:21:04 +0000614void sqlite3OpenMasterTable(Parse *p, int iDb){
615 Vdbe *v = sqlite3GetVdbe(p);
616 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977cd3e8f72008-03-25 09:47:35 +0000617 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 5);/* sqlite_master has 5 columns */
danielk1977207872a2008-01-03 07:54:23 +0000618 sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
drhe0bc4042002-06-25 01:09:11 +0000619}
620
621/*
danielk1977cbb18d22004-05-28 11:37:27 +0000622** The token *pName contains the name of a database (either "main" or
623** "temp" or the name of an attached db). This routine returns the
624** index of the named database in db->aDb[], or -1 if the named db
625** does not exist.
626*/
drhff2d5ea2005-07-23 00:41:48 +0000627int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000628 int i = -1; /* Database number */
danielk197700e13612008-11-17 19:18:54 +0000629 size_t n; /* Number of characters in the name */
drh73c42a12004-11-20 18:13:10 +0000630 Db *pDb; /* A database whose name space is being searched */
631 char *zName; /* Name we are searching for */
632
drh17435752007-08-16 04:30:38 +0000633 zName = sqlite3NameFromToken(db, pName);
drh73c42a12004-11-20 18:13:10 +0000634 if( zName ){
635 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000636 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000637 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
638 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000639 break;
drh73c42a12004-11-20 18:13:10 +0000640 }
danielk1977cbb18d22004-05-28 11:37:27 +0000641 }
drh633e6d52008-07-28 19:34:53 +0000642 sqlite3DbFree(db, zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000643 }
danielk1977576ec6b2005-01-21 11:55:25 +0000644 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000645}
646
drh0e3d7472004-06-19 17:33:07 +0000647/* The table or view or trigger name is passed to this routine via tokens
648** pName1 and pName2. If the table name was fully qualified, for example:
649**
650** CREATE TABLE xxx.yyy (...);
651**
652** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
653** the table name is not fully qualified, i.e.:
654**
655** CREATE TABLE yyy(...);
656**
657** Then pName1 is set to "yyy" and pName2 is "".
658**
659** This routine sets the *ppUnqual pointer to point at the token (pName1 or
660** pName2) that stores the unqualified table name. The index of the
661** database "xxx" is returned.
662*/
danielk1977ef2cb632004-05-29 02:37:19 +0000663int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000664 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000665 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000666 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
667 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000668){
drh0e3d7472004-06-19 17:33:07 +0000669 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000670 sqlite3 *db = pParse->db;
671
672 if( pName2 && pName2->n>0 ){
shanedcc50b72008-11-13 18:29:50 +0000673 if( db->init.busy ) {
674 sqlite3ErrorMsg(pParse, "corrupt database");
675 pParse->nErr++;
676 return -1;
677 }
danielk1977cbb18d22004-05-28 11:37:27 +0000678 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000679 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000680 if( iDb<0 ){
681 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
682 pParse->nErr++;
683 return -1;
684 }
685 }else{
686 assert( db->init.iDb==0 || db->init.busy );
687 iDb = db->init.iDb;
688 *pUnqual = pName1;
689 }
690 return iDb;
691}
692
693/*
danielk1977d8123362004-06-12 09:25:12 +0000694** This routine is used to check if the UTF-8 string zName is a legal
695** unqualified name for a new schema object (table, index, view or
696** trigger). All names are legal except those that begin with the string
697** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
698** is reserved for internal use.
699*/
700int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000701 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000702 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000703 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000704 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
705 return SQLITE_ERROR;
706 }
707 return SQLITE_OK;
708}
709
710/*
drh75897232000-05-29 14:26:00 +0000711** Begin constructing a new table representation in memory. This is
712** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000713** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000714** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000715** flag is true if the table should be stored in the auxiliary database
716** file instead of in the main database file. This is normally the case
717** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000718** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000719**
drhf57b3392001-10-08 13:22:32 +0000720** The new table record is initialized and put in pParse->pNewTable.
721** As more of the CREATE TABLE statement is parsed, additional action
722** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000723** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000724** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000725*/
danielk19774adee202004-05-08 08:23:19 +0000726void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000727 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000728 Token *pName1, /* First part of the name of the table or view */
729 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000730 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000731 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000732 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000733 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000734){
drh75897232000-05-29 14:26:00 +0000735 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000736 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000737 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000738 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000739 int iDb; /* Database number to create the table in */
740 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000741
danielk1977cbb18d22004-05-28 11:37:27 +0000742 /* The table or view name to create is passed to this routine via tokens
743 ** pName1 and pName2. If the table name was fully qualified, for example:
744 **
745 ** CREATE TABLE xxx.yyy (...);
746 **
747 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
748 ** the table name is not fully qualified, i.e.:
749 **
750 ** CREATE TABLE yyy(...);
751 **
752 ** Then pName1 is set to "yyy" and pName2 is "".
753 **
754 ** The call below sets the pName pointer to point at the token (pName1 or
755 ** pName2) that stores the unqualified table name. The variable iDb is
756 ** set to the index of the database that the table or view is to be
757 ** created in.
758 */
danielk1977ef2cb632004-05-29 02:37:19 +0000759 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000760 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000761 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000762 /* If creating a temp table, the name may not be qualified */
763 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000764 return;
765 }
danielk197753c0f742005-03-29 03:10:59 +0000766 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000767
768 pParse->sNameToken = *pName;
drh17435752007-08-16 04:30:38 +0000769 zName = sqlite3NameFromToken(db, pName);
danielk1977e0048402004-06-15 16:51:01 +0000770 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000771 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000772 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000773 }
drh1d85d932004-02-14 23:05:52 +0000774 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000775#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000776 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000777 {
778 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000779 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000780 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000781 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000782 }
drhe5f9c642003-01-13 23:27:31 +0000783 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000784 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000785 code = SQLITE_CREATE_TEMP_VIEW;
786 }else{
787 code = SQLITE_CREATE_VIEW;
788 }
789 }else{
danielk197753c0f742005-03-29 03:10:59 +0000790 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000791 code = SQLITE_CREATE_TEMP_TABLE;
792 }else{
793 code = SQLITE_CREATE_TABLE;
794 }
795 }
danielk1977f1a381e2006-06-16 08:01:02 +0000796 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000797 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000798 }
799 }
800#endif
drhf57b3392001-10-08 13:22:32 +0000801
drhf57b3392001-10-08 13:22:32 +0000802 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000803 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000804 ** it does. The exception is if the statement being parsed was passed
805 ** to an sqlite3_declare_vtab() call. In that case only the column names
806 ** and types will be used, so there is no need to test for namespace
807 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000808 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000809 if( !IN_DECLARE_VTAB ){
810 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
811 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000812 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000813 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
814 if( pTable ){
815 if( !noErr ){
816 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
817 }
818 goto begin_table_error;
819 }
820 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
821 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
822 goto begin_table_error;
823 }
drh75897232000-05-29 14:26:00 +0000824 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000825
danielk197726783a52007-08-29 14:06:22 +0000826 pTable = sqlite3DbMallocZero(db, sizeof(Table));
drh6d4abfb2001-10-22 02:58:08 +0000827 if( pTable==0 ){
drh17435752007-08-16 04:30:38 +0000828 db->mallocFailed = 1;
danielk1977e0048402004-06-15 16:51:01 +0000829 pParse->rc = SQLITE_NOMEM;
830 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000831 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000832 }
drh75897232000-05-29 14:26:00 +0000833 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000834 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000835 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000836 pTable->nRef = 1;
drh633e6d52008-07-28 19:34:53 +0000837 pTable->db = db;
danielk1977a04a34f2007-04-16 15:06:25 +0000838 if( pParse->pNewTable ) sqlite3DeleteTable(pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000839 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000840
drh4794f732004-11-05 17:17:50 +0000841 /* If this is the magic sqlite_sequence table used by autoincrement,
842 ** then record a pointer to this table in the main database structure
843 ** so that INSERT can find the table easily.
844 */
845#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000846 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000847 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000848 }
849#endif
850
drh17f71932002-02-21 12:01:27 +0000851 /* Begin generating the code that will insert the table record into
852 ** the SQLITE_MASTER table. Note in particular that we must go ahead
853 ** and allocate the record number for the table entry now. Before any
854 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
855 ** indices to be created and the table record must come before the
856 ** indices. Hence, the record number for the table must be allocated
857 ** now.
858 */
danielk19774adee202004-05-08 08:23:19 +0000859 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
drhb7654112008-01-12 12:48:07 +0000860 int j1;
drhe321c292006-01-12 01:56:43 +0000861 int fileFormat;
drhb7654112008-01-12 12:48:07 +0000862 int reg1, reg2, reg3;
danielk1977cbb18d22004-05-28 11:37:27 +0000863 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000864
danielk197720b1eaf2006-07-26 16:22:14 +0000865#ifndef SQLITE_OMIT_VIRTUALTABLE
866 if( isVirtual ){
drh66a51672008-01-03 00:01:23 +0000867 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +0000868 }
869#endif
870
danielk197736963fd2005-02-19 08:18:05 +0000871 /* If the file format and encoding in the database have not been set,
872 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000873 */
drhb7654112008-01-12 12:48:07 +0000874 reg1 = pParse->regRowid = ++pParse->nMem;
875 reg2 = pParse->regRoot = ++pParse->nMem;
876 reg3 = ++pParse->nMem;
877 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, 1); /* file_format */
drhfb982642007-08-30 01:19:59 +0000878 sqlite3VdbeUsesBtree(v, iDb);
drhb7654112008-01-12 12:48:07 +0000879 j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
drhe321c292006-01-12 01:56:43 +0000880 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
drh76fe8032006-07-11 14:17:51 +0000881 1 : SQLITE_MAX_FILE_FORMAT;
drhb7654112008-01-12 12:48:07 +0000882 sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
883 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, reg3);
884 sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
885 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 4, reg3);
886 sqlite3VdbeJumpHere(v, j1);
danielk1977d008cfe2004-06-19 02:22:10 +0000887
drh4794f732004-11-05 17:17:50 +0000888 /* This just creates a place-holder record in the sqlite_master table.
889 ** The record created does not contain anything yet. It will be replaced
890 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000891 **
892 ** The rowid for the new entry is left on the top of the stack.
893 ** The rowid value is needed by the code that sqlite3EndTable will
894 ** generate.
drh4794f732004-11-05 17:17:50 +0000895 */
danielk1977f1a381e2006-06-16 08:01:02 +0000896#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
897 if( isView || isVirtual ){
drhb7654112008-01-12 12:48:07 +0000898 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000899 }else
900#endif
901 {
drhb7654112008-01-12 12:48:07 +0000902 sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
danielk1977a21c6b62005-01-24 10:25:59 +0000903 }
danielk1977c00da102006-01-07 13:21:04 +0000904 sqlite3OpenMasterTable(pParse, iDb);
drhb7654112008-01-12 12:48:07 +0000905 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
906 sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
907 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
908 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh66a51672008-01-03 00:01:23 +0000909 sqlite3VdbeAddOp0(v, OP_Close);
drh5e00f6c2001-09-13 13:46:56 +0000910 }
drh23bf66d2004-12-14 03:34:34 +0000911
912 /* Normal (non-error) return. */
913 return;
914
915 /* If an error occurs, we jump here */
916begin_table_error:
drh633e6d52008-07-28 19:34:53 +0000917 sqlite3DbFree(db, zName);
drh23bf66d2004-12-14 03:34:34 +0000918 return;
drh75897232000-05-29 14:26:00 +0000919}
920
921/*
danielk1977c60e9b82005-01-31 12:42:29 +0000922** This macro is used to compare two strings in a case-insensitive manner.
923** It is slightly faster than calling sqlite3StrICmp() directly, but
924** produces larger code.
925**
926** WARNING: This macro is not compatible with the strcmp() family. It
927** returns true if the two strings are equal, otherwise false.
928*/
929#define STRICMP(x, y) (\
930sqlite3UpperToLower[*(unsigned char *)(x)]== \
931sqlite3UpperToLower[*(unsigned char *)(y)] \
932&& sqlite3StrICmp((x)+1,(y)+1)==0 )
933
934/*
drh75897232000-05-29 14:26:00 +0000935** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000936**
937** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000938** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000939** first to get things going. Then this routine is called for each
940** column.
drh75897232000-05-29 14:26:00 +0000941*/
danielk19774adee202004-05-08 08:23:19 +0000942void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000943 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000944 int i;
drha99db3b2004-06-19 14:49:12 +0000945 char *z;
drhc9b84a12002-06-20 11:36:48 +0000946 Column *pCol;
drhbb4957f2008-03-20 14:03:29 +0000947 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +0000948 if( (p = pParse->pNewTable)==0 ) return;
drhbb4957f2008-03-20 14:03:29 +0000949#if SQLITE_MAX_COLUMN
950 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
drhe5c941b2007-05-08 13:58:26 +0000951 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
952 return;
953 }
drhbb4957f2008-03-20 14:03:29 +0000954#endif
drh17435752007-08-16 04:30:38 +0000955 z = sqlite3NameFromToken(pParse->db, pName);
drh97fc3d02002-05-22 21:27:03 +0000956 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000957 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000958 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000959 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh633e6d52008-07-28 19:34:53 +0000960 sqlite3DbFree(db, z);
drh97fc3d02002-05-22 21:27:03 +0000961 return;
962 }
963 }
drh75897232000-05-29 14:26:00 +0000964 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000965 Column *aNew;
danielk197726783a52007-08-29 14:06:22 +0000966 aNew = sqlite3DbRealloc(pParse->db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000967 if( aNew==0 ){
drh633e6d52008-07-28 19:34:53 +0000968 sqlite3DbFree(db, z);
danielk1977d5d56522005-03-16 12:15:20 +0000969 return;
970 }
drh6d4abfb2001-10-22 02:58:08 +0000971 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000972 }
drhc9b84a12002-06-20 11:36:48 +0000973 pCol = &p->aCol[p->nCol];
974 memset(pCol, 0, sizeof(p->aCol[0]));
975 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000976
977 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000978 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
979 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000980 */
danielk19774f057f92004-06-08 00:02:33 +0000981 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000982 p->nCol++;
drh75897232000-05-29 14:26:00 +0000983}
984
985/*
drh382c0242001-10-06 16:33:02 +0000986** This routine is called by the parser while in the middle of
987** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
988** been seen on a column. This routine sets the notNull flag on
989** the column currently under construction.
990*/
danielk19774adee202004-05-08 08:23:19 +0000991void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000992 Table *p;
993 int i;
994 if( (p = pParse->pNewTable)==0 ) return;
995 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000996 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000997}
998
999/*
danielk197752a83fb2005-01-31 12:56:44 +00001000** Scan the column type name zType (length nType) and return the
1001** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +00001002**
1003** This routine does a case-independent search of zType for the
1004** substrings in the following table. If one of the substrings is
1005** found, the corresponding affinity is returned. If zType contains
1006** more than one of the substrings, entries toward the top of
1007** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +00001008** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +00001009**
1010** Substring | Affinity
1011** --------------------------------
1012** 'INT' | SQLITE_AFF_INTEGER
1013** 'CHAR' | SQLITE_AFF_TEXT
1014** 'CLOB' | SQLITE_AFF_TEXT
1015** 'TEXT' | SQLITE_AFF_TEXT
1016** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +00001017** 'REAL' | SQLITE_AFF_REAL
1018** 'FLOA' | SQLITE_AFF_REAL
1019** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +00001020**
1021** If none of the substrings in the above table are found,
1022** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +00001023*/
drh8a512562005-11-14 22:29:05 +00001024char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +00001025 u32 h = 0;
1026 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +00001027 const unsigned char *zIn = pType->z;
1028 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +00001029
danielk1977b3dff962005-02-01 01:21:55 +00001030 while( zIn!=zEnd ){
1031 h = (h<<8) + sqlite3UpperToLower[*zIn];
1032 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001033 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1034 aff = SQLITE_AFF_TEXT;
1035 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1036 aff = SQLITE_AFF_TEXT;
1037 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1038 aff = SQLITE_AFF_TEXT;
1039 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001040 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001041 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001042#ifndef SQLITE_OMIT_FLOATING_POINT
1043 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1044 && aff==SQLITE_AFF_NUMERIC ){
1045 aff = SQLITE_AFF_REAL;
1046 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1047 && aff==SQLITE_AFF_NUMERIC ){
1048 aff = SQLITE_AFF_REAL;
1049 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1050 && aff==SQLITE_AFF_NUMERIC ){
1051 aff = SQLITE_AFF_REAL;
1052#endif
danielk1977201f7162005-02-01 02:13:29 +00001053 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001054 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001055 break;
danielk197752a83fb2005-01-31 12:56:44 +00001056 }
1057 }
danielk1977b3dff962005-02-01 01:21:55 +00001058
1059 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001060}
1061
1062/*
drh382c0242001-10-06 16:33:02 +00001063** This routine is called by the parser while in the middle of
1064** parsing a CREATE TABLE statement. The pFirst token is the first
1065** token in the sequence of tokens that describe the type of the
1066** column currently under construction. pLast is the last token
1067** in the sequence. Use this information to construct a string
1068** that contains the typename of the column and store that string
1069** in zType.
1070*/
drh487e2622005-06-25 18:42:14 +00001071void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001072 Table *p;
drh487e2622005-06-25 18:42:14 +00001073 int i;
drhc9b84a12002-06-20 11:36:48 +00001074 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001075 sqlite3 *db;
drh487e2622005-06-25 18:42:14 +00001076
drh382c0242001-10-06 16:33:02 +00001077 if( (p = pParse->pNewTable)==0 ) return;
1078 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001079 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001080 pCol = &p->aCol[i];
drh633e6d52008-07-28 19:34:53 +00001081 db = pParse->db;
1082 sqlite3DbFree(db, pCol->zType);
1083 pCol->zType = sqlite3NameFromToken(db, pType);
drh8a512562005-11-14 22:29:05 +00001084 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001085}
1086
1087/*
danielk19777977a172004-11-09 12:44:37 +00001088** The expression is the default value for the most recently added column
1089** of the table currently under construction.
1090**
1091** Default value expressions must be constant. Raise an exception if this
1092** is not the case.
drhd9b02572001-04-15 00:37:09 +00001093**
1094** This routine is called by the parser while in the middle of
1095** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001096*/
danielk19777977a172004-11-09 12:44:37 +00001097void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001098 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001099 Column *pCol;
drh633e6d52008-07-28 19:34:53 +00001100 sqlite3 *db = pParse->db;
drh42b9d7c2005-08-13 00:56:27 +00001101 if( (p = pParse->pNewTable)!=0 ){
1102 pCol = &(p->aCol[p->nCol-1]);
1103 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1104 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1105 pCol->zName);
1106 }else{
drh417ec632006-08-14 14:23:41 +00001107 Expr *pCopy;
drh633e6d52008-07-28 19:34:53 +00001108 sqlite3ExprDelete(db, pCol->pDflt);
drh17435752007-08-16 04:30:38 +00001109 pCol->pDflt = pCopy = sqlite3ExprDup(db, pExpr);
drh417ec632006-08-14 14:23:41 +00001110 if( pCopy ){
drh17435752007-08-16 04:30:38 +00001111 sqlite3TokenCopy(db, &pCopy->span, &pExpr->span);
drh417ec632006-08-14 14:23:41 +00001112 }
drh42b9d7c2005-08-13 00:56:27 +00001113 }
danielk19777977a172004-11-09 12:44:37 +00001114 }
drh633e6d52008-07-28 19:34:53 +00001115 sqlite3ExprDelete(db, pExpr);
drh7020f652000-06-03 18:06:52 +00001116}
1117
1118/*
drh4a324312001-12-21 14:30:42 +00001119** Designate the PRIMARY KEY for the table. pList is a list of names
1120** of columns that form the primary key. If pList is NULL, then the
1121** most recently added column of the table is the primary key.
1122**
1123** A table can have at most one primary key. If the table already has
1124** a primary key (and this is the second primary key) then create an
1125** error.
1126**
1127** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001128** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001129** field of the table under construction to be the index of the
1130** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1131** no INTEGER PRIMARY KEY.
1132**
1133** If the key is not an INTEGER PRIMARY KEY, then create a unique
1134** index for the key. No index is created for INTEGER PRIMARY KEYs.
1135*/
drh205f48e2004-11-05 00:43:11 +00001136void sqlite3AddPrimaryKey(
1137 Parse *pParse, /* Parsing context */
1138 ExprList *pList, /* List of field names to be indexed */
1139 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001140 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1141 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001142){
drh4a324312001-12-21 14:30:42 +00001143 Table *pTab = pParse->pNewTable;
1144 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001145 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001146 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh7d10d5a2008-08-20 16:35:10 +00001147 if( pTab->tabFlags & TF_HasPrimaryKey ){
danielk19774adee202004-05-08 08:23:19 +00001148 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001149 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001150 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001151 }
drh7d10d5a2008-08-20 16:35:10 +00001152 pTab->tabFlags |= TF_HasPrimaryKey;
drh4a324312001-12-21 14:30:42 +00001153 if( pList==0 ){
1154 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001155 pTab->aCol[iCol].isPrimKey = 1;
1156 }else{
danielk19770202b292004-06-09 09:55:16 +00001157 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001158 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001159 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1160 break;
1161 }
drh78100cc2003-08-23 22:40:53 +00001162 }
drh6e4fc2c2005-09-15 21:24:51 +00001163 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001164 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001165 }
drh4a324312001-12-21 14:30:42 +00001166 }
danielk19770202b292004-06-09 09:55:16 +00001167 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001168 }
1169 if( iCol>=0 && iCol<pTab->nCol ){
1170 zType = pTab->aCol[iCol].zType;
1171 }
drhfdd6e852005-12-16 01:06:16 +00001172 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1173 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001174 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001175 pTab->keyConf = onError;
drh7d10d5a2008-08-20 16:35:10 +00001176 assert( autoInc==0 || autoInc==1 );
1177 pTab->tabFlags |= autoInc*TF_Autoincrement;
drh205f48e2004-11-05 00:43:11 +00001178 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001179#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001180 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1181 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001182#endif
drh4a324312001-12-21 14:30:42 +00001183 }else{
drh4d91a702006-01-04 15:54:36 +00001184 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001185 pList = 0;
drh4a324312001-12-21 14:30:42 +00001186 }
drhe0194f22003-02-26 13:52:51 +00001187
1188primary_key_exit:
drh633e6d52008-07-28 19:34:53 +00001189 sqlite3ExprListDelete(pParse->db, pList);
drhe0194f22003-02-26 13:52:51 +00001190 return;
drh4a324312001-12-21 14:30:42 +00001191}
1192
1193/*
drhffe07b22005-11-03 00:41:17 +00001194** Add a new CHECK constraint to the table currently under construction.
1195*/
1196void sqlite3AddCheckConstraint(
1197 Parse *pParse, /* Parsing context */
1198 Expr *pCheckExpr /* The check expression */
1199){
drh633e6d52008-07-28 19:34:53 +00001200 sqlite3 *db = pParse->db;
drhffe07b22005-11-03 00:41:17 +00001201#ifndef SQLITE_OMIT_CHECK
1202 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001203 if( pTab && !IN_DECLARE_VTAB ){
drhffe07b22005-11-03 00:41:17 +00001204 /* The CHECK expression must be duplicated so that tokens refer
1205 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1206 ** statement */
drh17435752007-08-16 04:30:38 +00001207 pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck,
1208 sqlite3ExprDup(db, pCheckExpr));
drhffe07b22005-11-03 00:41:17 +00001209 }
1210#endif
drh633e6d52008-07-28 19:34:53 +00001211 sqlite3ExprDelete(db, pCheckExpr);
drhffe07b22005-11-03 00:41:17 +00001212}
1213
1214/*
drhd3d39e92004-05-20 22:16:29 +00001215** Set the collation function of the most recently parsed table column
1216** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001217*/
danielk197739002502007-11-12 09:50:26 +00001218void sqlite3AddCollateType(Parse *pParse, Token *pToken){
drh8e2ca022002-06-17 17:07:19 +00001219 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001220 int i;
danielk197739002502007-11-12 09:50:26 +00001221 char *zColl; /* Dequoted name of collation sequence */
drh633e6d52008-07-28 19:34:53 +00001222 sqlite3 *db;
danielk1977a37cdde2004-05-16 11:15:36 +00001223
danielk1977b8cbb872006-06-19 05:33:45 +00001224 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001225 i = p->nCol-1;
drh633e6d52008-07-28 19:34:53 +00001226 db = pParse->db;
1227 zColl = sqlite3NameFromToken(db, pToken);
danielk197739002502007-11-12 09:50:26 +00001228 if( !zColl ) return;
1229
1230 if( sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk1977b3bf5562006-01-10 17:58:23 +00001231 Index *pIdx;
danielk197739002502007-11-12 09:50:26 +00001232 p->aCol[i].zColl = zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00001233
1234 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1235 ** then an index may have been created on this column before the
1236 ** collation type was added. Correct this if it is the case.
1237 */
1238 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1239 assert( pIdx->nColumn==1 );
1240 if( pIdx->aiColumn[0]==i ){
1241 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001242 }
1243 }
danielk197739002502007-11-12 09:50:26 +00001244 }else{
drh633e6d52008-07-28 19:34:53 +00001245 sqlite3DbFree(db, zColl);
danielk19777cedc8d2004-06-10 10:50:08 +00001246 }
danielk19777cedc8d2004-06-10 10:50:08 +00001247}
1248
danielk1977466be562004-06-10 02:16:01 +00001249/*
1250** This function returns the collation sequence for database native text
1251** encoding identified by the string zName, length nName.
1252**
1253** If the requested collation sequence is not available, or not available
1254** in the database native encoding, the collation factory is invoked to
1255** request it. If the collation factory does not supply such a sequence,
1256** and the sequence is available in another text encoding, then that is
1257** returned instead.
1258**
1259** If no versions of the requested collations sequence are available, or
1260** another error occurs, NULL is returned and an error message written into
1261** pParse.
drha34001c2007-02-02 12:44:37 +00001262**
1263** This routine is a wrapper around sqlite3FindCollSeq(). This routine
1264** invokes the collation factory if the named collation cannot be found
1265** and generates an error message.
danielk1977466be562004-06-10 02:16:01 +00001266*/
danielk19770202b292004-06-09 09:55:16 +00001267CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001268 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001269 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001270 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001271 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001272
danielk1977b3bf5562006-01-10 17:58:23 +00001273 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001274 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001275 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1276 if( !pColl ){
1277 if( nName<0 ){
drh0a687d12008-07-08 14:52:07 +00001278 nName = sqlite3Strlen(db, zName);
danielk1977466be562004-06-10 02:16:01 +00001279 }
danielk19774dade032005-05-25 10:45:10 +00001280 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1281 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001282 }
1283 }
1284
danielk19770202b292004-06-09 09:55:16 +00001285 return pColl;
1286}
1287
1288
drh8e2ca022002-06-17 17:07:19 +00001289/*
drh3f7d4e42004-07-24 14:35:58 +00001290** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001291**
1292** The schema cookie is used to determine when the schema for the
1293** database changes. After each schema change, the cookie value
1294** changes. When a process first reads the schema it records the
1295** cookie. Thereafter, whenever it goes to access the database,
1296** it checks the cookie to make sure the schema has not changed
1297** since it was last read.
1298**
1299** This plan is not completely bullet-proof. It is possible for
1300** the schema to change multiple times and for the cookie to be
1301** set back to prior value. But schema changes are infrequent
1302** and the probability of hitting the same cookie value is only
1303** 1 chance in 2^32. So we're safe enough.
1304*/
drh9cbf3422008-01-17 16:22:13 +00001305void sqlite3ChangeCookie(Parse *pParse, int iDb){
1306 int r1 = sqlite3GetTempReg(pParse);
1307 sqlite3 *db = pParse->db;
1308 Vdbe *v = pParse->pVdbe;
1309 sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
1310 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 0, r1);
1311 sqlite3ReleaseTempReg(pParse, r1);
drh50e5dad2001-09-15 00:57:28 +00001312}
1313
1314/*
drh969fa7c2002-02-18 18:30:32 +00001315** Measure the number of characters needed to output the given
1316** identifier. The number returned includes any quotes used
1317** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001318**
1319** The estimate is conservative. It might be larger that what is
1320** really needed.
drh969fa7c2002-02-18 18:30:32 +00001321*/
1322static int identLength(const char *z){
1323 int n;
drh17f71932002-02-21 12:01:27 +00001324 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001325 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001326 }
drh234c39d2004-07-24 03:30:47 +00001327 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001328}
1329
1330/*
1331** Write an identifier onto the end of the given string. Add
1332** quote characters as needed.
1333*/
drh4c755c02004-08-08 20:22:17 +00001334static void identPut(char *z, int *pIdx, char *zSignedIdent){
1335 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001336 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001337 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001338 for(j=0; zIdent[j]; j++){
1339 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1340 }
1341 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001342 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001343 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001344 for(j=0; zIdent[j]; j++){
1345 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001346 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001347 }
drh234c39d2004-07-24 03:30:47 +00001348 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001349 z[i] = 0;
1350 *pIdx = i;
1351}
1352
1353/*
1354** Generate a CREATE TABLE statement appropriate for the given
1355** table. Memory to hold the text of the statement is obtained
1356** from sqliteMalloc() and must be freed by the calling function.
1357*/
drh820a9062008-01-31 13:35:48 +00001358static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001359 int i, k, n;
1360 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001361 char *zSep, *zSep2, *zEnd, *z;
1362 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001363 n = 0;
drh234c39d2004-07-24 03:30:47 +00001364 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1365 n += identLength(pCol->zName);
1366 z = pCol->zType;
1367 if( z ){
1368 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001369 }
drh969fa7c2002-02-18 18:30:32 +00001370 }
1371 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001372 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001373 zSep = "";
1374 zSep2 = ",";
1375 zEnd = ")";
1376 }else{
1377 zSep = "\n ";
1378 zSep2 = ",\n ";
1379 zEnd = "\n)";
1380 }
drhe0bc4042002-06-25 01:09:11 +00001381 n += 35 + 6*p->nCol;
drhe5ae5732008-06-15 02:51:47 +00001382 zStmt = sqlite3Malloc( n );
drh820a9062008-01-31 13:35:48 +00001383 if( zStmt==0 ){
1384 db->mallocFailed = 1;
1385 return 0;
1386 }
drh5bb3eb92007-05-04 13:15:55 +00001387 sqlite3_snprintf(n, zStmt,
1388 !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001389 k = strlen(zStmt);
1390 identPut(zStmt, &k, p->zName);
1391 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001392 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh5bb3eb92007-05-04 13:15:55 +00001393 sqlite3_snprintf(n-k, &zStmt[k], zSep);
drh969fa7c2002-02-18 18:30:32 +00001394 k += strlen(&zStmt[k]);
1395 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001396 identPut(zStmt, &k, pCol->zName);
1397 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001398 zStmt[k++] = ' ';
danielk197700e13612008-11-17 19:18:54 +00001399 assert( (int)(strlen(z)+k+1)<=n );
drh5bb3eb92007-05-04 13:15:55 +00001400 sqlite3_snprintf(n-k, &zStmt[k], "%s", z);
drh234c39d2004-07-24 03:30:47 +00001401 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001402 }
drh969fa7c2002-02-18 18:30:32 +00001403 }
drh5bb3eb92007-05-04 13:15:55 +00001404 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
drh969fa7c2002-02-18 18:30:32 +00001405 return zStmt;
1406}
1407
1408/*
drh75897232000-05-29 14:26:00 +00001409** This routine is called to report the final ")" that terminates
1410** a CREATE TABLE statement.
1411**
drhf57b3392001-10-08 13:22:32 +00001412** The table structure that other action routines have been building
1413** is added to the internal hash tables, assuming no errors have
1414** occurred.
drh75897232000-05-29 14:26:00 +00001415**
drh1d85d932004-02-14 23:05:52 +00001416** An entry for the table is made in the master table on disk, unless
1417** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001418** it means we are reading the sqlite_master table because we just
1419** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001420** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001421** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001422**
1423** If the pSelect argument is not NULL, it means that this routine
1424** was called to create a table generated from a
1425** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1426** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001427*/
danielk197719a8e7e2005-03-17 05:03:38 +00001428void sqlite3EndTable(
1429 Parse *pParse, /* Parse context */
1430 Token *pCons, /* The ',' token after the last column defn. */
1431 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1432 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1433){
drh75897232000-05-29 14:26:00 +00001434 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001435 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001436 int iDb;
drh75897232000-05-29 14:26:00 +00001437
drh17435752007-08-16 04:30:38 +00001438 if( (pEnd==0 && pSelect==0) || pParse->nErr || db->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001439 return;
1440 }
drh28037572000-08-02 13:47:41 +00001441 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001442 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001443
danielk1977517eb642004-06-07 10:00:31 +00001444 assert( !db->init.busy || !pSelect );
1445
drhb9bb7c12006-06-11 23:41:55 +00001446 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001447
drhffe07b22005-11-03 00:41:17 +00001448#ifndef SQLITE_OMIT_CHECK
1449 /* Resolve names in all CHECK constraint expressions.
1450 */
1451 if( p->pCheck ){
1452 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1453 NameContext sNC; /* Name context for pParse->pNewTable */
1454
1455 memset(&sNC, 0, sizeof(sNC));
1456 memset(&sSrc, 0, sizeof(sSrc));
1457 sSrc.nSrc = 1;
1458 sSrc.a[0].zName = p->zName;
1459 sSrc.a[0].pTab = p;
1460 sSrc.a[0].iCursor = -1;
1461 sNC.pParse = pParse;
1462 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001463 sNC.isCheck = 1;
drh7d10d5a2008-08-20 16:35:10 +00001464 if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
drhffe07b22005-11-03 00:41:17 +00001465 return;
1466 }
1467 }
1468#endif /* !defined(SQLITE_OMIT_CHECK) */
1469
drh1d85d932004-02-14 23:05:52 +00001470 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001471 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1472 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001473 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001474 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001475 */
drh1d85d932004-02-14 23:05:52 +00001476 if( db->init.busy ){
1477 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001478 }
1479
drhe3c41372001-09-17 20:25:58 +00001480 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001481 ** in the SQLITE_MASTER table of the database. The record number
1482 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001483 **
drhe0bc4042002-06-25 01:09:11 +00001484 ** If this is a TEMPORARY table, write the entry into the auxiliary
1485 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001486 */
drh1d85d932004-02-14 23:05:52 +00001487 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001488 int n;
drhd8bc7082000-06-07 23:51:50 +00001489 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001490 char *zType; /* "view" or "table" */
1491 char *zType2; /* "VIEW" or "TABLE" */
1492 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001493
danielk19774adee202004-05-08 08:23:19 +00001494 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001495 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001496
drh66a51672008-01-03 00:01:23 +00001497 sqlite3VdbeAddOp1(v, OP_Close, 0);
danielk1977e6efa742004-11-10 11:55:10 +00001498
drh4794f732004-11-05 17:17:50 +00001499 /* Create the rootpage for the new table and push it onto the stack.
1500 ** A view has no rootpage, so just push a zero onto the stack for
1501 ** views. Initialize zType at the same time.
1502 */
drh4ff6dfa2002-03-03 23:06:00 +00001503 if( p->pSelect==0 ){
1504 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001505 zType = "table";
1506 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001507#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001508 }else{
1509 /* A view */
drh4794f732004-11-05 17:17:50 +00001510 zType = "view";
1511 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001512#endif
drh4ff6dfa2002-03-03 23:06:00 +00001513 }
danielk1977517eb642004-06-07 10:00:31 +00001514
danielk1977517eb642004-06-07 10:00:31 +00001515 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1516 ** statement to populate the new table. The root-page number for the
1517 ** new table is on the top of the vdbe stack.
1518 **
1519 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1520 ** suitable state to query for the column names and types to be used
1521 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001522 **
1523 ** A shared-cache write-lock is not required to write to the new table,
1524 ** as a schema-lock must have already been obtained to create it. Since
1525 ** a schema-lock excludes all other database users, the write-lock would
1526 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001527 */
1528 if( pSelect ){
drh1013c932008-01-06 00:25:21 +00001529 SelectDest dest;
danielk1977517eb642004-06-07 10:00:31 +00001530 Table *pSelTab;
drh1013c932008-01-06 00:25:21 +00001531
danielk1977df206b02008-08-04 04:39:48 +00001532 assert(pParse->nTab==0);
drhb7654112008-01-12 12:48:07 +00001533 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
drh98757152008-01-09 23:04:12 +00001534 sqlite3VdbeChangeP5(v, 1);
danielk1977517eb642004-06-07 10:00:31 +00001535 pParse->nTab = 2;
drh1013c932008-01-06 00:25:21 +00001536 sqlite3SelectDestInit(&dest, SRT_Table, 1);
drh7d10d5a2008-08-20 16:35:10 +00001537 sqlite3Select(pParse, pSelect, &dest);
drh66a51672008-01-03 00:01:23 +00001538 sqlite3VdbeAddOp1(v, OP_Close, 1);
danielk1977517eb642004-06-07 10:00:31 +00001539 if( pParse->nErr==0 ){
drh7d10d5a2008-08-20 16:35:10 +00001540 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
danielk1977517eb642004-06-07 10:00:31 +00001541 if( pSelTab==0 ) return;
1542 assert( p->aCol==0 );
1543 p->nCol = pSelTab->nCol;
1544 p->aCol = pSelTab->aCol;
1545 pSelTab->nCol = 0;
1546 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001547 sqlite3DeleteTable(pSelTab);
danielk1977517eb642004-06-07 10:00:31 +00001548 }
1549 }
drh4794f732004-11-05 17:17:50 +00001550
drh4794f732004-11-05 17:17:50 +00001551 /* Compute the complete text of the CREATE statement */
1552 if( pSelect ){
drh820a9062008-01-31 13:35:48 +00001553 zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001554 }else{
drh97903fe2005-05-24 20:19:57 +00001555 n = pEnd->z - pParse->sNameToken.z + 1;
danielk19771e536952007-08-16 10:09:01 +00001556 zStmt = sqlite3MPrintf(db,
1557 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
1558 );
drh4794f732004-11-05 17:17:50 +00001559 }
1560
1561 /* A slot for the record has already been allocated in the
1562 ** SQLITE_MASTER table. We just need to update that slot with all
1563 ** the information we've collected. The rowid for the preallocated
1564 ** slot is the 2nd item on the stack. The top of the stack is the
1565 ** root page for the new table (or a 0 if this is a view).
1566 */
1567 sqlite3NestedParse(pParse,
1568 "UPDATE %Q.%s "
drhb7654112008-01-12 12:48:07 +00001569 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
1570 "WHERE rowid=#%d",
danielk1977da184232006-01-05 11:34:32 +00001571 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001572 zType,
1573 p->zName,
1574 p->zName,
drhb7654112008-01-12 12:48:07 +00001575 pParse->regRoot,
1576 zStmt,
1577 pParse->regRowid
drh4794f732004-11-05 17:17:50 +00001578 );
drh633e6d52008-07-28 19:34:53 +00001579 sqlite3DbFree(db, zStmt);
drh9cbf3422008-01-17 16:22:13 +00001580 sqlite3ChangeCookie(pParse, iDb);
drh2958a4e2004-11-12 03:56:15 +00001581
1582#ifndef SQLITE_OMIT_AUTOINCREMENT
1583 /* Check to see if we need to create an sqlite_sequence table for
1584 ** keeping track of autoincrement keys.
1585 */
drh7d10d5a2008-08-20 16:35:10 +00001586 if( p->tabFlags & TF_Autoincrement ){
danielk1977da184232006-01-05 11:34:32 +00001587 Db *pDb = &db->aDb[iDb];
1588 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001589 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001590 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1591 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001592 );
1593 }
1594 }
1595#endif
drh4794f732004-11-05 17:17:50 +00001596
1597 /* Reparse everything to update our internal data structures */
drh66a51672008-01-03 00:01:23 +00001598 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
1599 sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001600 }
drh17e9e292003-02-01 13:53:28 +00001601
drh2958a4e2004-11-12 03:56:15 +00001602
drh17e9e292003-02-01 13:53:28 +00001603 /* Add the table to the in-memory representation of the database.
1604 */
drh234c39d2004-07-24 03:30:47 +00001605 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001606 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001607 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001608 Schema *pSchema = p->pSchema;
danielk1977da184232006-01-05 11:34:32 +00001609 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001610 if( pOld ){
1611 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
drh17435752007-08-16 04:30:38 +00001612 db->mallocFailed = 1;
drh17e9e292003-02-01 13:53:28 +00001613 return;
1614 }
danielk1977576ec6b2005-01-21 11:55:25 +00001615#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001616 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
danielk1977a1644fd2007-08-29 12:31:25 +00001617 void *data;
drh17e9e292003-02-01 13:53:28 +00001618 int nTo = strlen(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001619 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
danielk1977a1644fd2007-08-29 12:31:25 +00001620 data = sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
1621 if( data==(void *)pFKey ){
1622 db->mallocFailed = 1;
1623 }
drh17e9e292003-02-01 13:53:28 +00001624 }
danielk1977576ec6b2005-01-21 11:55:25 +00001625#endif
drh17e9e292003-02-01 13:53:28 +00001626 pParse->pNewTable = 0;
1627 db->nTable++;
1628 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001629
1630#ifndef SQLITE_OMIT_ALTERTABLE
1631 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001632 const char *zName = (const char *)pParse->sNameToken.z;
drh9a087a92007-05-15 14:34:32 +00001633 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001634 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001635 if( pCons->z==0 ){
1636 pCons = pEnd;
1637 }
1638 nName = (const char *)pCons->z - zName;
drh9a087a92007-05-15 14:34:32 +00001639 p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001640 }
1641#endif
drh17e9e292003-02-01 13:53:28 +00001642 }
drh75897232000-05-29 14:26:00 +00001643}
1644
drhb7f91642004-10-31 02:22:47 +00001645#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001646/*
drha76b5df2002-02-23 02:32:10 +00001647** The parser calls this routine in order to create a new VIEW
1648*/
danielk19774adee202004-05-08 08:23:19 +00001649void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001650 Parse *pParse, /* The parsing context */
1651 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001652 Token *pName1, /* The token that holds the name of the view */
1653 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001654 Select *pSelect, /* A SELECT statement that will become the new view */
drhfdd48a72006-09-11 23:45:48 +00001655 int isTemp, /* TRUE for a TEMPORARY view */
1656 int noErr /* Suppress error messages if VIEW already exists */
drha76b5df2002-02-23 02:32:10 +00001657){
drha76b5df2002-02-23 02:32:10 +00001658 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001659 int n;
drh4c755c02004-08-08 20:22:17 +00001660 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001661 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001662 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001663 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001664 int iDb;
drh17435752007-08-16 04:30:38 +00001665 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +00001666
drh7c3d64f2005-06-06 15:32:08 +00001667 if( pParse->nVar>0 ){
1668 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
drh633e6d52008-07-28 19:34:53 +00001669 sqlite3SelectDelete(db, pSelect);
drh7c3d64f2005-06-06 15:32:08 +00001670 return;
1671 }
drhfdd48a72006-09-11 23:45:48 +00001672 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
drha76b5df2002-02-23 02:32:10 +00001673 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001674 if( p==0 || pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00001675 sqlite3SelectDelete(db, pSelect);
drh417be792002-03-03 18:59:40 +00001676 return;
1677 }
danielk1977ef2cb632004-05-29 02:37:19 +00001678 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
drh17435752007-08-16 04:30:38 +00001679 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001680 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001681 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001682 ){
drh633e6d52008-07-28 19:34:53 +00001683 sqlite3SelectDelete(db, pSelect);
drhf26e09c2003-05-31 16:21:12 +00001684 return;
1685 }
drh174b6192002-12-03 02:22:52 +00001686
drh4b59ab52002-08-24 18:24:51 +00001687 /* Make a copy of the entire SELECT statement that defines the view.
1688 ** This will force all the Expr.token.z values to be dynamically
1689 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001690 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001691 */
drh17435752007-08-16 04:30:38 +00001692 p->pSelect = sqlite3SelectDup(db, pSelect);
drh633e6d52008-07-28 19:34:53 +00001693 sqlite3SelectDelete(db, pSelect);
drh17435752007-08-16 04:30:38 +00001694 if( db->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001695 return;
1696 }
drh17435752007-08-16 04:30:38 +00001697 if( !db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001698 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001699 }
drh4b59ab52002-08-24 18:24:51 +00001700
1701 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1702 ** the end.
1703 */
drha76b5df2002-02-23 02:32:10 +00001704 sEnd = pParse->sLastToken;
1705 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1706 sEnd.z += sEnd.n;
1707 }
1708 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001709 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001710 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001711 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1712 sEnd.z = &z[n-1];
1713 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001714
danielk19774adee202004-05-08 08:23:19 +00001715 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001716 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001717 return;
drh417be792002-03-03 18:59:40 +00001718}
drhb7f91642004-10-31 02:22:47 +00001719#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001720
danielk1977fe3fcbe22006-06-12 12:08:45 +00001721#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001722/*
1723** The Table structure pTable is really a VIEW. Fill in the names of
1724** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001725** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001726*/
danielk19774adee202004-05-08 08:23:19 +00001727int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001728 Table *pSelTab; /* A fake table from which we get the result set */
1729 Select *pSel; /* Copy of the SELECT that implements the view */
1730 int nErr = 0; /* Number of errors encountered */
1731 int n; /* Temporarily holds the number of cursors assigned */
drh17435752007-08-16 04:30:38 +00001732 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
drha6d0ffc2007-10-12 20:42:28 +00001733 int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
drh417be792002-03-03 18:59:40 +00001734
1735 assert( pTable );
1736
danielk1977fe3fcbe22006-06-12 12:08:45 +00001737#ifndef SQLITE_OMIT_VIRTUALTABLE
1738 if( sqlite3VtabCallConnect(pParse, pTable) ){
1739 return SQLITE_ERROR;
1740 }
drh4cbdda92006-06-14 19:00:20 +00001741 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001742#endif
1743
1744#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001745 /* A positive nCol means the columns names for this view are
1746 ** already known.
1747 */
1748 if( pTable->nCol>0 ) return 0;
1749
1750 /* A negative nCol is a special marker meaning that we are currently
1751 ** trying to compute the column names. If we enter this routine with
1752 ** a negative nCol, it means two or more views form a loop, like this:
1753 **
1754 ** CREATE VIEW one AS SELECT * FROM two;
1755 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001756 **
1757 ** Actually, this error is caught previously and so the following test
1758 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001759 */
1760 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001761 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001762 return 1;
1763 }
drh85c23c62005-08-20 03:03:04 +00001764 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001765
1766 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001767 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1768 ** "*" elements in the results set of the view and will assign cursors
1769 ** to the elements of the FROM clause. But we do not want these changes
1770 ** to be permanent. So the computation is done on a copy of the SELECT
1771 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001772 */
drh9b3187e2005-01-18 14:45:47 +00001773 assert( pTable->pSelect );
drh17435752007-08-16 04:30:38 +00001774 pSel = sqlite3SelectDup(db, pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001775 if( pSel ){
1776 n = pParse->nTab;
1777 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1778 pTable->nCol = -1;
danielk1977db2d2862007-10-15 07:08:44 +00001779#ifndef SQLITE_OMIT_AUTHORIZATION
drha6d0ffc2007-10-12 20:42:28 +00001780 xAuth = db->xAuth;
1781 db->xAuth = 0;
drh7d10d5a2008-08-20 16:35:10 +00001782 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
drha6d0ffc2007-10-12 20:42:28 +00001783 db->xAuth = xAuth;
danielk1977db2d2862007-10-15 07:08:44 +00001784#else
drh7d10d5a2008-08-20 16:35:10 +00001785 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
danielk1977db2d2862007-10-15 07:08:44 +00001786#endif
danielk1977261919c2005-12-06 12:52:59 +00001787 pParse->nTab = n;
1788 if( pSelTab ){
1789 assert( pTable->aCol==0 );
1790 pTable->nCol = pSelTab->nCol;
1791 pTable->aCol = pSelTab->aCol;
1792 pSelTab->nCol = 0;
1793 pSelTab->aCol = 0;
danielk1977a04a34f2007-04-16 15:06:25 +00001794 sqlite3DeleteTable(pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001795 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001796 }else{
1797 pTable->nCol = 0;
1798 nErr++;
1799 }
drh633e6d52008-07-28 19:34:53 +00001800 sqlite3SelectDelete(db, pSel);
danielk1977261919c2005-12-06 12:52:59 +00001801 } else {
drh417be792002-03-03 18:59:40 +00001802 nErr++;
1803 }
drhb7f91642004-10-31 02:22:47 +00001804#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001805 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001806}
1807#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001808
drhb7f91642004-10-31 02:22:47 +00001809#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001810/*
drh8bf8dc92003-05-17 17:35:10 +00001811** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001812*/
drh9bb575f2004-09-06 17:24:11 +00001813static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001814 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001815 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001816 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001817 Table *pTab = sqliteHashData(i);
1818 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001819 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001820 }
1821 }
drh8bf8dc92003-05-17 17:35:10 +00001822 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001823}
drhb7f91642004-10-31 02:22:47 +00001824#else
1825# define sqliteViewResetAll(A,B)
1826#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001827
drh75897232000-05-29 14:26:00 +00001828/*
danielk1977a0bf2652004-11-04 14:30:04 +00001829** This function is called by the VDBE to adjust the internal schema
1830** used by SQLite when the btree layer moves a table root page. The
1831** root-page of a table or index in database iDb has changed from iFrom
1832** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001833**
1834** Ticket #1728: The symbol table might still contain information
1835** on tables and/or indices that are the process of being deleted.
1836** If you are unlucky, one of those deleted indices or tables might
1837** have the same rootpage number as the real table or index that is
1838** being moved. So we cannot stop searching after the first match
1839** because the first match might be for one of the deleted indices
1840** or tables and not the table/index that is actually being moved.
1841** We must continue looping until all tables and indices with
1842** rootpage==iFrom have been converted to have a rootpage of iTo
1843** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001844*/
1845#ifndef SQLITE_OMIT_AUTOVACUUM
1846void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1847 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001848 Hash *pHash;
1849
1850 pHash = &pDb->pSchema->tblHash;
1851 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001852 Table *pTab = sqliteHashData(pElem);
1853 if( pTab->tnum==iFrom ){
1854 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001855 }
1856 }
danielk1977da184232006-01-05 11:34:32 +00001857 pHash = &pDb->pSchema->idxHash;
1858 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001859 Index *pIdx = sqliteHashData(pElem);
1860 if( pIdx->tnum==iFrom ){
1861 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001862 }
1863 }
danielk1977a0bf2652004-11-04 14:30:04 +00001864}
1865#endif
1866
1867/*
1868** Write code to erase the table with root-page iTable from database iDb.
1869** Also write code to modify the sqlite_master table and internal schema
1870** if a root-page of another table is moved by the btree-layer whilst
1871** erasing iTable (this can happen with an auto-vacuum database).
1872*/
drh4e0cff62004-11-05 05:10:28 +00001873static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1874 Vdbe *v = sqlite3GetVdbe(pParse);
drhb7654112008-01-12 12:48:07 +00001875 int r1 = sqlite3GetTempReg(pParse);
1876 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
drh40e016e2004-11-04 14:47:11 +00001877#ifndef SQLITE_OMIT_AUTOVACUUM
drhb7654112008-01-12 12:48:07 +00001878 /* OP_Destroy stores an in integer r1. If this integer
drh4e0cff62004-11-05 05:10:28 +00001879 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001880 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001881 ** reflect this.
1882 **
drhb7654112008-01-12 12:48:07 +00001883 ** The "#%d" in the SQL is a special constant that means whatever value
drh4e0cff62004-11-05 05:10:28 +00001884 ** is on the top of the stack. See sqlite3RegisterExpr().
1885 */
danielk197763e3e9f2004-11-05 09:19:27 +00001886 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00001887 "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
1888 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001889#endif
drhb7654112008-01-12 12:48:07 +00001890 sqlite3ReleaseTempReg(pParse, r1);
danielk1977a0bf2652004-11-04 14:30:04 +00001891}
1892
1893/*
1894** Write VDBE code to erase table pTab and all associated indices on disk.
1895** Code to update the sqlite_master tables and internal schema definitions
1896** in case a root-page belonging to another table is moved by the btree layer
1897** is also added (this can happen with an auto-vacuum database).
1898*/
drh4e0cff62004-11-05 05:10:28 +00001899static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001900#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001901 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001902 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1903 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001904 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001905 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001906 }
1907#else
1908 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1909 ** is not defined), then it is important to call OP_Destroy on the
1910 ** table and index root-pages in order, starting with the numerically
1911 ** largest root-page number. This guarantees that none of the root-pages
1912 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1913 ** following were coded:
1914 **
1915 ** OP_Destroy 4 0
1916 ** ...
1917 ** OP_Destroy 5 0
1918 **
1919 ** and root page 5 happened to be the largest root-page number in the
1920 ** database, then root page 5 would be moved to page 4 by the
1921 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1922 ** a free-list page.
1923 */
1924 int iTab = pTab->tnum;
1925 int iDestroyed = 0;
1926
1927 while( 1 ){
1928 Index *pIdx;
1929 int iLargest = 0;
1930
1931 if( iDestroyed==0 || iTab<iDestroyed ){
1932 iLargest = iTab;
1933 }
1934 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1935 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001936 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001937 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1938 iLargest = iIdx;
1939 }
1940 }
danielk1977da184232006-01-05 11:34:32 +00001941 if( iLargest==0 ){
1942 return;
1943 }else{
1944 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1945 destroyRootPage(pParse, iLargest, iDb);
1946 iDestroyed = iLargest;
1947 }
danielk1977a0bf2652004-11-04 14:30:04 +00001948 }
1949#endif
1950}
1951
1952/*
drh75897232000-05-29 14:26:00 +00001953** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001954** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001955*/
drha0733842005-12-29 01:11:36 +00001956void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001957 Table *pTab;
drh75897232000-05-29 14:26:00 +00001958 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001959 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001960 int iDb;
drh75897232000-05-29 14:26:00 +00001961
drh17435752007-08-16 04:30:38 +00001962 if( pParse->nErr || db->mallocFailed ){
drh6f7adc82006-01-11 21:41:20 +00001963 goto exit_drop_table;
1964 }
danielk1977a8858102004-05-28 12:11:21 +00001965 assert( pName->nSrc==1 );
drhca424112008-01-25 15:04:48 +00001966 pTab = sqlite3LocateTable(pParse, isView,
1967 pName->a[0].zName, pName->a[0].zDatabase);
danielk1977a8858102004-05-28 12:11:21 +00001968
drha0733842005-12-29 01:11:36 +00001969 if( pTab==0 ){
1970 if( noErr ){
1971 sqlite3ErrorClear(pParse);
1972 }
1973 goto exit_drop_table;
1974 }
danielk1977da184232006-01-05 11:34:32 +00001975 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001976 assert( iDb>=0 && iDb<db->nDb );
danielk1977b5258c32007-10-04 18:11:15 +00001977
1978 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
1979 ** it is initialized.
1980 */
1981 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
1982 goto exit_drop_table;
1983 }
drhe5f9c642003-01-13 23:27:31 +00001984#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001985 {
1986 int code;
danielk1977da184232006-01-05 11:34:32 +00001987 const char *zTab = SCHEMA_TABLE(iDb);
1988 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001989 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001990 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001991 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001992 }
drhe5f9c642003-01-13 23:27:31 +00001993 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001994 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001995 code = SQLITE_DROP_TEMP_VIEW;
1996 }else{
1997 code = SQLITE_DROP_VIEW;
1998 }
danielk19774b2688a2006-06-20 11:01:07 +00001999#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00002000 }else if( IsVirtual(pTab) ){
2001 code = SQLITE_DROP_VTABLE;
2002 zArg2 = pTab->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00002003#endif
drhe5f9c642003-01-13 23:27:31 +00002004 }else{
danielk197753c0f742005-03-29 03:10:59 +00002005 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00002006 code = SQLITE_DROP_TEMP_TABLE;
2007 }else{
2008 code = SQLITE_DROP_TABLE;
2009 }
2010 }
danielk1977f1a381e2006-06-16 08:01:02 +00002011 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00002012 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00002013 }
danielk1977a8858102004-05-28 12:11:21 +00002014 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
2015 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00002016 }
drhe5f9c642003-01-13 23:27:31 +00002017 }
2018#endif
drhc456e572008-08-11 18:44:58 +00002019 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk1977a8858102004-05-28 12:11:21 +00002020 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00002021 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00002022 }
danielk1977576ec6b2005-01-21 11:55:25 +00002023
2024#ifndef SQLITE_OMIT_VIEW
2025 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
2026 ** on a table.
2027 */
danielk1977a8858102004-05-28 12:11:21 +00002028 if( isView && pTab->pSelect==0 ){
2029 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
2030 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002031 }
danielk1977a8858102004-05-28 12:11:21 +00002032 if( !isView && pTab->pSelect ){
2033 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
2034 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00002035 }
danielk1977576ec6b2005-01-21 11:55:25 +00002036#endif
drh75897232000-05-29 14:26:00 +00002037
drh1ccde152000-06-17 13:12:39 +00002038 /* Generate code to remove the table from the master table
2039 ** on disk.
2040 */
danielk19774adee202004-05-08 08:23:19 +00002041 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002042 if( v ){
drhe0bc4042002-06-25 01:09:11 +00002043 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00002044 Db *pDb = &db->aDb[iDb];
drh77658e22007-12-04 16:54:52 +00002045 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh8bf8dc92003-05-17 17:35:10 +00002046
danielk197720b1eaf2006-07-26 16:22:14 +00002047#ifndef SQLITE_OMIT_VIRTUALTABLE
2048 if( IsVirtual(pTab) ){
2049 Vdbe *v = sqlite3GetVdbe(pParse);
2050 if( v ){
drh66a51672008-01-03 00:01:23 +00002051 sqlite3VdbeAddOp0(v, OP_VBegin);
danielk197720b1eaf2006-07-26 16:22:14 +00002052 }
2053 }
2054#endif
2055
danielk19778e227872004-06-07 07:52:17 +00002056 /* Drop all triggers associated with the table being dropped. Code
2057 ** is generated to remove entries from sqlite_master and/or
2058 ** sqlite_temp_master if required.
2059 */
danielk1977a8858102004-05-28 12:11:21 +00002060 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00002061 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00002062 assert( pTrigger->pSchema==pTab->pSchema ||
2063 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00002064 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00002065 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00002066 }
drh8bf8dc92003-05-17 17:35:10 +00002067
danielk19774d36b812004-11-19 07:07:30 +00002068#ifndef SQLITE_OMIT_AUTOINCREMENT
2069 /* Remove any entries of the sqlite_sequence table associated with
2070 ** the table being dropped. This is done before the table is dropped
2071 ** at the btree level, in case the sqlite_sequence table needs to
2072 ** move as a result of the drop (can happen in auto-vacuum mode).
2073 */
drh7d10d5a2008-08-20 16:35:10 +00002074 if( pTab->tabFlags & TF_Autoincrement ){
danielk19774d36b812004-11-19 07:07:30 +00002075 sqlite3NestedParse(pParse,
2076 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
2077 pDb->zName, pTab->zName
2078 );
2079 }
2080#endif
2081
danielk19778e227872004-06-07 07:52:17 +00002082 /* Drop all SQLITE_MASTER table and index entries that refer to the
2083 ** table. The program name loops through the master table and deletes
2084 ** every row that refers to a table of the same name as the one being
2085 ** dropped. Triggers are handled seperately because a trigger can be
2086 ** created in the temp database that refers to a table in another
2087 ** database.
2088 */
drhf1974842004-11-05 03:56:00 +00002089 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00002090 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00002091 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk1977006015d2008-04-11 17:11:26 +00002092
2093 /* Drop any statistics from the sqlite_stat1 table, if it exists */
2094 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2095 sqlite3NestedParse(pParse,
2096 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
2097 );
2098 }
2099
danielk19774b2688a2006-06-20 11:01:07 +00002100 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00002101 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00002102 }
drh2958a4e2004-11-12 03:56:15 +00002103
danielk1977a21c6b62005-01-24 10:25:59 +00002104 /* Remove the table entry from SQLite's internal schema and modify
2105 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00002106 */
drh4cbdda92006-06-14 19:00:20 +00002107 if( IsVirtual(pTab) ){
drh66a51672008-01-03 00:01:23 +00002108 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002109 }
drh66a51672008-01-03 00:01:23 +00002110 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
drh9cbf3422008-01-17 16:22:13 +00002111 sqlite3ChangeCookie(pParse, iDb);
drh75897232000-05-29 14:26:00 +00002112 }
drhd24cc422003-03-27 12:51:24 +00002113 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002114
2115exit_drop_table:
drh633e6d52008-07-28 19:34:53 +00002116 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002117}
2118
2119/*
drhc2eef3b2002-08-31 18:53:06 +00002120** This routine is called to create a new foreign key on the table
2121** currently under construction. pFromCol determines which columns
2122** in the current table point to the foreign key. If pFromCol==0 then
2123** connect the key to the last column inserted. pTo is the name of
2124** the table referred to. pToCol is a list of tables in the other
2125** pTo table that the foreign key points to. flags contains all
2126** information about the conflict resolution algorithms specified
2127** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2128**
2129** An FKey structure is created and added to the table currently
2130** under construction in the pParse->pNewTable field. The new FKey
2131** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00002132** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00002133**
2134** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002135** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002136*/
danielk19774adee202004-05-08 08:23:19 +00002137void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002138 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002139 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002140 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002141 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002142 int flags /* Conflict resolution algorithms. */
2143){
danielk197718576932008-08-06 13:47:40 +00002144 sqlite3 *db = pParse->db;
drhb7f91642004-10-31 02:22:47 +00002145#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002146 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00002147 Table *p = pParse->pNewTable;
2148 int nByte;
2149 int i;
2150 int nCol;
2151 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002152
2153 assert( pTo!=0 );
danielk1977c7d54102006-06-15 07:29:00 +00002154 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002155 if( pFromCol==0 ){
2156 int iCol = p->nCol-1;
2157 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002158 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002159 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002160 " should reference only one column of table %T",
2161 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002162 goto fk_end;
2163 }
2164 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002165 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002166 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002167 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002168 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002169 goto fk_end;
2170 }else{
danielk19770202b292004-06-09 09:55:16 +00002171 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002172 }
2173 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2174 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002175 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00002176 nByte += strlen(pToCol->a[i].zName) + 1;
2177 }
2178 }
drh633e6d52008-07-28 19:34:53 +00002179 pFKey = sqlite3DbMallocZero(db, nByte );
drh17435752007-08-16 04:30:38 +00002180 if( pFKey==0 ){
2181 goto fk_end;
2182 }
drhc2eef3b2002-08-31 18:53:06 +00002183 pFKey->pFrom = p;
2184 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002185 z = (char*)&pFKey[1];
2186 pFKey->aCol = (struct sColMap*)z;
2187 z += sizeof(struct sColMap)*nCol;
2188 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002189 memcpy(z, pTo->z, pTo->n);
2190 z[pTo->n] = 0;
2191 z += pTo->n+1;
2192 pFKey->pNextTo = 0;
2193 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002194 if( pFromCol==0 ){
2195 pFKey->aCol[0].iFrom = p->nCol-1;
2196 }else{
2197 for(i=0; i<nCol; i++){
2198 int j;
2199 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002200 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002201 pFKey->aCol[i].iFrom = j;
2202 break;
2203 }
2204 }
2205 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002206 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002207 "unknown column \"%s\" in foreign key definition",
2208 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002209 goto fk_end;
2210 }
2211 }
2212 }
2213 if( pToCol ){
2214 for(i=0; i<nCol; i++){
2215 int n = strlen(pToCol->a[i].zName);
2216 pFKey->aCol[i].zCol = z;
2217 memcpy(z, pToCol->a[i].zName, n);
2218 z[n] = 0;
2219 z += n+1;
2220 }
2221 }
2222 pFKey->isDeferred = 0;
2223 pFKey->deleteConf = flags & 0xff;
2224 pFKey->updateConf = (flags >> 8 ) & 0xff;
2225 pFKey->insertConf = (flags >> 16 ) & 0xff;
2226
2227 /* Link the foreign key to the table as the last step.
2228 */
2229 p->pFKey = pFKey;
2230 pFKey = 0;
2231
2232fk_end:
drh633e6d52008-07-28 19:34:53 +00002233 sqlite3DbFree(db, pFKey);
drhb7f91642004-10-31 02:22:47 +00002234#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
drh633e6d52008-07-28 19:34:53 +00002235 sqlite3ExprListDelete(db, pFromCol);
2236 sqlite3ExprListDelete(db, pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002237}
2238
2239/*
2240** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2241** clause is seen as part of a foreign key definition. The isDeferred
2242** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2243** The behavior of the most recently created foreign key is adjusted
2244** accordingly.
2245*/
danielk19774adee202004-05-08 08:23:19 +00002246void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002247#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002248 Table *pTab;
2249 FKey *pFKey;
2250 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2251 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002252#endif
drhc2eef3b2002-08-31 18:53:06 +00002253}
2254
2255/*
drh063336a2004-11-05 20:58:39 +00002256** Generate code that will erase and refill index *pIdx. This is
2257** used to initialize a newly created index or to recompute the
2258** content of an index in response to a REINDEX command.
2259**
2260** if memRootPage is not negative, it means that the index is newly
drh1db639c2008-01-17 02:36:28 +00002261** created. The register specified by memRootPage contains the
drh063336a2004-11-05 20:58:39 +00002262** root page number of the index. If memRootPage is negative, then
2263** the index already exists and must be cleared before being refilled and
2264** the root page number of the index is taken from pIndex->tnum.
2265*/
2266static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2267 Table *pTab = pIndex->pTable; /* The table that is indexed */
2268 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2269 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2270 int addr1; /* Address of top of loop */
2271 int tnum; /* Root page of index */
2272 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002273 KeyInfo *pKey; /* KeyInfo for index */
drh2d401ab2008-01-10 23:50:11 +00002274 int regIdxKey; /* Registers containing the index key */
2275 int regRecord; /* Register holding assemblied index record */
drh17435752007-08-16 04:30:38 +00002276 sqlite3 *db = pParse->db; /* The database connection */
2277 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002278
danielk19771d54df82004-11-23 15:41:16 +00002279#ifndef SQLITE_OMIT_AUTHORIZATION
2280 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
drh17435752007-08-16 04:30:38 +00002281 db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002282 return;
2283 }
2284#endif
2285
danielk1977c00da102006-01-07 13:21:04 +00002286 /* Require a write-lock on the table to perform this operation */
2287 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2288
drh063336a2004-11-05 20:58:39 +00002289 v = sqlite3GetVdbe(pParse);
2290 if( v==0 ) return;
2291 if( memRootPage>=0 ){
drh1db639c2008-01-17 02:36:28 +00002292 tnum = memRootPage;
drh063336a2004-11-05 20:58:39 +00002293 }else{
2294 tnum = pIndex->tnum;
drh66a51672008-01-03 00:01:23 +00002295 sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002296 }
danielk1977b3bf5562006-01-10 17:58:23 +00002297 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
danielk1977207872a2008-01-03 07:54:23 +00002298 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
drh66a51672008-01-03 00:01:23 +00002299 (char *)pKey, P4_KEYINFO_HANDOFF);
drh98757152008-01-09 23:04:12 +00002300 if( memRootPage>=0 ){
2301 sqlite3VdbeChangeP5(v, 1);
2302 }
danielk1977c00da102006-01-07 13:21:04 +00002303 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh66a51672008-01-03 00:01:23 +00002304 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
drh2d401ab2008-01-10 23:50:11 +00002305 regRecord = sqlite3GetTempReg(pParse);
drhe14006d2008-03-25 17:23:32 +00002306 regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
drh7f057c92005-06-24 03:53:06 +00002307 if( pIndex->onError!=OE_None ){
drh2d401ab2008-01-10 23:50:11 +00002308 int j1, j2;
2309 int regRowid;
2310
2311 regRowid = regIdxKey + pIndex->nColumn;
2312 j1 = sqlite3VdbeAddOp3(v, OP_IsNull, regIdxKey, 0, pIndex->nColumn);
2313 j2 = sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx,
shane1fc41292008-07-08 22:28:48 +00002314 0, regRowid, SQLITE_INT_TO_PTR(regRecord), P4_INT32);
drh66a51672008-01-03 00:01:23 +00002315 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort, 0,
2316 "indexed columns are not unique", P4_STATIC);
drh2d401ab2008-01-10 23:50:11 +00002317 sqlite3VdbeJumpHere(v, j1);
2318 sqlite3VdbeJumpHere(v, j2);
drh4343fea2004-11-05 23:46:15 +00002319 }
drh2d401ab2008-01-10 23:50:11 +00002320 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
2321 sqlite3ReleaseTempReg(pParse, regRecord);
drh66a51672008-01-03 00:01:23 +00002322 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002323 sqlite3VdbeJumpHere(v, addr1);
drh66a51672008-01-03 00:01:23 +00002324 sqlite3VdbeAddOp1(v, OP_Close, iTab);
2325 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
drh063336a2004-11-05 20:58:39 +00002326}
2327
2328/*
drh23bf66d2004-12-14 03:34:34 +00002329** Create a new index for an SQL table. pName1.pName2 is the name of the index
2330** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002331** be NULL for a primary key or an index that is created to satisfy a
2332** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002333** as the table to be indexed. pParse->pNewTable is a table that is
2334** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002335**
drh382c0242001-10-06 16:33:02 +00002336** pList is a list of columns to be indexed. pList will be NULL if this
2337** is a primary key or unique-constraint on the most recent column added
2338** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002339*/
danielk19774adee202004-05-08 08:23:19 +00002340void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002341 Parse *pParse, /* All information about this parse */
2342 Token *pName1, /* First part of index name. May be NULL */
2343 Token *pName2, /* Second part of index name. May be NULL */
2344 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002345 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002346 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
drh1c55ba02007-07-02 19:31:27 +00002347 Token *pStart, /* The CREATE token that begins this statement */
drhfdd6e852005-12-16 01:06:16 +00002348 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002349 int sortOrder, /* Sort order of primary key when pList==NULL */
2350 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002351){
drhfdd6e852005-12-16 01:06:16 +00002352 Table *pTab = 0; /* Table to be indexed */
2353 Index *pIndex = 0; /* The index to be created */
2354 char *zName = 0; /* Name of the index */
2355 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002356 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002357 Token nullId; /* Fake token for an empty ID list */
2358 DbFixer sFix; /* For assigning database names to pTable */
2359 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002360 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002361 Db *pDb; /* The specific table containing the indexed database */
2362 int iDb; /* Index of the database that is being written */
2363 Token *pName = 0; /* Unqualified name of the index to create */
2364 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002365 int nCol;
2366 int nExtra = 0;
2367 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002368
drh17435752007-08-16 04:30:38 +00002369 if( pParse->nErr || db->mallocFailed || IN_DECLARE_VTAB ){
danielk1977e501b892006-01-09 06:29:47 +00002370 goto exit_create_index;
2371 }
drhdaffd0e2001-04-11 14:28:42 +00002372
drh75897232000-05-29 14:26:00 +00002373 /*
2374 ** Find the table that is to be indexed. Return early if not found.
2375 */
danielk1977cbb18d22004-05-28 11:37:27 +00002376 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002377
2378 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002379 ** to search for the table. 'Fix' the table name to this db
2380 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002381 */
2382 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002383 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002384 if( iDb<0 ) goto exit_create_index;
2385
danielk197753c0f742005-03-29 03:10:59 +00002386#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002387 /* If the index name was unqualified, check if the the table
danielk1977fe910332007-12-02 11:46:34 +00002388 ** is a temp table. If so, set the database to 1. Do not do this
2389 ** if initialising a database schema.
danielk1977cbb18d22004-05-28 11:37:27 +00002390 */
danielk1977fe910332007-12-02 11:46:34 +00002391 if( !db->init.busy ){
2392 pTab = sqlite3SrcListLookup(pParse, pTblName);
2393 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
2394 iDb = 1;
2395 }
danielk1977ef2cb632004-05-29 02:37:19 +00002396 }
danielk197753c0f742005-03-29 03:10:59 +00002397#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002398
2399 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2400 sqlite3FixSrcList(&sFix, pTblName)
2401 ){
drh85c23c62005-08-20 03:03:04 +00002402 /* Because the parser constructs pTblName from a single identifier,
2403 ** sqlite3FixSrcList can never fail. */
2404 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002405 }
drhca424112008-01-25 15:04:48 +00002406 pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName,
danielk1977ef2cb632004-05-29 02:37:19 +00002407 pTblName->a[0].zDatabase);
danielk1977d207d802008-10-22 10:45:37 +00002408 if( !pTab || db->mallocFailed ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002409 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002410 }else{
drhe3c41372001-09-17 20:25:58 +00002411 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002412 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002413 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002414 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002415 }
drhfdd6e852005-12-16 01:06:16 +00002416 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002417
drh75897232000-05-29 14:26:00 +00002418 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drhc456e572008-08-11 18:44:58 +00002419 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
danielk19774adee202004-05-08 08:23:19 +00002420 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002421 goto exit_create_index;
2422 }
danielk1977576ec6b2005-01-21 11:55:25 +00002423#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002424 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002425 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002426 goto exit_create_index;
2427 }
danielk1977576ec6b2005-01-21 11:55:25 +00002428#endif
danielk19775ee9d692006-06-21 12:36:25 +00002429#ifndef SQLITE_OMIT_VIRTUALTABLE
2430 if( IsVirtual(pTab) ){
2431 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
2432 goto exit_create_index;
2433 }
2434#endif
drh75897232000-05-29 14:26:00 +00002435
2436 /*
2437 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002438 ** index or table with the same name.
2439 **
2440 ** Exception: If we are reading the names of permanent indices from the
2441 ** sqlite_master table (because some other process changed the schema) and
2442 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002443 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002444 **
2445 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002446 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2447 ** own name.
drh75897232000-05-29 14:26:00 +00002448 */
danielk1977d8123362004-06-12 09:25:12 +00002449 if( pName ){
drh17435752007-08-16 04:30:38 +00002450 zName = sqlite3NameFromToken(db, pName);
danielk19778a414492004-06-29 08:59:35 +00002451 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002452 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002453 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002454 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002455 }
danielk1977d8123362004-06-12 09:25:12 +00002456 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002457 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
danielk1977d45a0312007-03-13 16:32:25 +00002458 if( sqlite3FindTable(db, zName, 0)!=0 ){
2459 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2460 goto exit_create_index;
2461 }
2462 }
danielk197759a33f92007-03-17 10:26:59 +00002463 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
2464 if( !ifNotExist ){
2465 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
danielk1977d8123362004-06-12 09:25:12 +00002466 }
danielk197759a33f92007-03-17 10:26:59 +00002467 goto exit_create_index;
2468 }
danielk1977a21c6b62005-01-24 10:25:59 +00002469 }else{
drhadbca9c2001-09-27 15:11:53 +00002470 int n;
2471 Index *pLoop;
2472 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
drhf089aa42008-07-08 19:34:06 +00002473 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
danielk1977a1644fd2007-08-29 12:31:25 +00002474 if( zName==0 ){
danielk1977a1644fd2007-08-29 12:31:25 +00002475 goto exit_create_index;
2476 }
drh75897232000-05-29 14:26:00 +00002477 }
2478
drhe5f9c642003-01-13 23:27:31 +00002479 /* Check for authorization to create an index.
2480 */
2481#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002482 {
drhfdd6e852005-12-16 01:06:16 +00002483 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002484 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002485 goto exit_create_index;
2486 }
2487 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002488 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002489 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002490 goto exit_create_index;
2491 }
drhe5f9c642003-01-13 23:27:31 +00002492 }
2493#endif
2494
drh75897232000-05-29 14:26:00 +00002495 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002496 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002497 ** So create a fake list to simulate this.
2498 */
2499 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002500 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2501 nullId.n = strlen((char*)nullId.z);
danielk19771e536952007-08-16 10:09:01 +00002502 pList = sqlite3ExprListAppend(pParse, 0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002503 if( pList==0 ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002504 pList->a[0].sortOrder = sortOrder;
drh75897232000-05-29 14:26:00 +00002505 }
2506
danielk1977b3bf5562006-01-10 17:58:23 +00002507 /* Figure out how many bytes of space are required to store explicitly
2508 ** specified collation sequence names.
2509 */
2510 for(i=0; i<pList->nExpr; i++){
drh7d10d5a2008-08-20 16:35:10 +00002511 Expr *pExpr;
2512 CollSeq *pColl;
2513 if( (pExpr = pList->a[i].pExpr)!=0 && (pColl = pExpr->pColl)!=0 ){
2514 nExtra += (1 + strlen(pColl->zName));
danielk1977b3bf5562006-01-10 17:58:23 +00002515 }
2516 }
2517
drh75897232000-05-29 14:26:00 +00002518 /*
2519 ** Allocate the index structure.
2520 */
drhfdd6e852005-12-16 01:06:16 +00002521 nName = strlen(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002522 nCol = pList->nExpr;
drh17435752007-08-16 04:30:38 +00002523 pIndex = sqlite3DbMallocZero(db,
danielk1977b3bf5562006-01-10 17:58:23 +00002524 sizeof(Index) + /* Index structure */
2525 sizeof(int)*nCol + /* Index.aiColumn */
2526 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2527 sizeof(char *)*nCol + /* Index.azColl */
2528 sizeof(u8)*nCol + /* Index.aSortOrder */
2529 nName + 1 + /* Index.zName */
2530 nExtra /* Collation sequence names */
2531 );
drh17435752007-08-16 04:30:38 +00002532 if( db->mallocFailed ){
2533 goto exit_create_index;
2534 }
drh78aecb72006-02-10 18:08:09 +00002535 pIndex->azColl = (char**)(&pIndex[1]);
2536 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002537 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002538 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002539 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2540 zExtra = (char *)(&pIndex->zName[nName+1]);
drh5bb3eb92007-05-04 13:15:55 +00002541 memcpy(pIndex->zName, zName, nName+1);
drh75897232000-05-29 14:26:00 +00002542 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002543 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002544 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002545 pIndex->autoIndex = pName==0;
danielk1977da184232006-01-05 11:34:32 +00002546 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002547
drhfdd6e852005-12-16 01:06:16 +00002548 /* Check to see if we should honor DESC requests on index columns
2549 */
danielk1977da184232006-01-05 11:34:32 +00002550 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002551 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002552 }else{
2553 sortOrderMask = 0; /* Ignore DESC */
2554 }
2555
drh1ccde152000-06-17 13:12:39 +00002556 /* Scan the names of the columns of the table to be indexed and
2557 ** load the column indices into the Index structure. Report an error
2558 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002559 */
drhfdd6e852005-12-16 01:06:16 +00002560 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2561 const char *zColName = pListItem->zName;
2562 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002563 int requestedSortOrder;
drha34001c2007-02-02 12:44:37 +00002564 char *zColl; /* Collation sequence name */
danielk1977b3bf5562006-01-10 17:58:23 +00002565
drhfdd6e852005-12-16 01:06:16 +00002566 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2567 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002568 }
2569 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002570 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002571 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002572 goto exit_create_index;
2573 }
drha34001c2007-02-02 12:44:37 +00002574 /* TODO: Add a test to make sure that the same column is not named
2575 ** more than once within the same index. Only the first instance of
2576 ** the column will ever be used by the optimizer. Note that using the
2577 ** same column more than once cannot be an error because that would
2578 ** break backwards compatibility - it needs to be a warning.
2579 */
drh967e8b72000-06-21 13:59:10 +00002580 pIndex->aiColumn[i] = j;
drh7d10d5a2008-08-20 16:35:10 +00002581 if( pListItem->pExpr && pListItem->pExpr->pColl ){
drhfdd6e852005-12-16 01:06:16 +00002582 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002583 zColl = zExtra;
drh5bb3eb92007-05-04 13:15:55 +00002584 sqlite3_snprintf(nExtra, zExtra, "%s", pListItem->pExpr->pColl->zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002585 zExtra += (strlen(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002586 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002587 zColl = pTab->aCol[j].zColl;
2588 if( !zColl ){
2589 zColl = db->pDfltColl->zName;
2590 }
danielk19770202b292004-06-09 09:55:16 +00002591 }
danielk1977b3bf5562006-01-10 17:58:23 +00002592 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002593 goto exit_create_index;
2594 }
danielk1977b3bf5562006-01-10 17:58:23 +00002595 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002596 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
danielk1977b3bf5562006-01-10 17:58:23 +00002597 pIndex->aSortOrder[i] = requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002598 }
drh51147ba2005-07-23 22:59:55 +00002599 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002600
danielk1977d8123362004-06-12 09:25:12 +00002601 if( pTab==pParse->pNewTable ){
2602 /* This routine has been called to create an automatic index as a
2603 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2604 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2605 ** i.e. one of:
2606 **
2607 ** CREATE TABLE t(x PRIMARY KEY, y);
2608 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2609 **
2610 ** Either way, check to see if the table already has such an index. If
2611 ** so, don't bother creating this one. This only applies to
2612 ** automatically created indices. Users can do as they wish with
2613 ** explicit indices.
2614 */
2615 Index *pIdx;
2616 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2617 int k;
2618 assert( pIdx->onError!=OE_None );
2619 assert( pIdx->autoIndex );
2620 assert( pIndex->onError!=OE_None );
2621
2622 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2623 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002624 const char *z1 = pIdx->azColl[k];
2625 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002626 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002627 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2628 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002629 }
2630 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002631 if( pIdx->onError!=pIndex->onError ){
2632 /* This constraint creates the same index as a previous
2633 ** constraint specified somewhere in the CREATE TABLE statement.
2634 ** However the ON CONFLICT clauses are different. If both this
2635 ** constraint and the previous equivalent constraint have explicit
2636 ** ON CONFLICT clauses this is an error. Otherwise, use the
2637 ** explicitly specified behaviour for the index.
2638 */
2639 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2640 sqlite3ErrorMsg(pParse,
2641 "conflicting ON CONFLICT clauses specified", 0);
2642 }
2643 if( pIdx->onError==OE_Default ){
2644 pIdx->onError = pIndex->onError;
2645 }
2646 }
danielk1977d8123362004-06-12 09:25:12 +00002647 goto exit_create_index;
2648 }
2649 }
2650 }
2651
drh75897232000-05-29 14:26:00 +00002652 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002653 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002654 */
drh234c39d2004-07-24 03:30:47 +00002655 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002656 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002657 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drh3c8bf552003-07-01 18:13:14 +00002658 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002659 if( p ){
2660 assert( p==pIndex ); /* Malloc must have failed */
drh17435752007-08-16 04:30:38 +00002661 db->mallocFailed = 1;
drh6d4abfb2001-10-22 02:58:08 +00002662 goto exit_create_index;
2663 }
drh5e00f6c2001-09-13 13:46:56 +00002664 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002665 if( pTblName!=0 ){
2666 pIndex->tnum = db->init.newTnum;
2667 }
drhd78eeee2001-09-13 16:18:53 +00002668 }
2669
drh1d85d932004-02-14 23:05:52 +00002670 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002671 ** involves writing the index into the master table and filling in the
2672 ** index with the current table contents.
2673 **
drh1d85d932004-02-14 23:05:52 +00002674 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2675 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002676 ** CREATE INDEX statements are read out of the master table. In
2677 ** the latter case the index already exists on disk, which is why
2678 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002679 **
danielk1977cbb18d22004-05-28 11:37:27 +00002680 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002681 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2682 ** has just been created, it contains no data and the index initialization
2683 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002684 */
drh1d85d932004-02-14 23:05:52 +00002685 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002686 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002687 char *zStmt;
drh0a07c102008-01-03 18:03:08 +00002688 int iMem = ++pParse->nMem;
drh75897232000-05-29 14:26:00 +00002689
danielk19774adee202004-05-08 08:23:19 +00002690 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002691 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002692
drhfdd6e852005-12-16 01:06:16 +00002693
drh063336a2004-11-05 20:58:39 +00002694 /* Create the rootpage for the index
2695 */
drhaee128d2005-02-14 20:48:18 +00002696 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb7654112008-01-12 12:48:07 +00002697 sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
drh063336a2004-11-05 20:58:39 +00002698
2699 /* Gather the complete text of the CREATE INDEX statement into
2700 ** the zStmt variable
2701 */
drhe0bc4042002-06-25 01:09:11 +00002702 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002703 /* A named index with an explicit CREATE INDEX statement */
danielk19771e536952007-08-16 10:09:01 +00002704 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002705 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002706 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002707 pName->z);
2708 }else{
2709 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002710 /* zStmt = sqlite3MPrintf(""); */
2711 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002712 }
drh063336a2004-11-05 20:58:39 +00002713
2714 /* Add an entry in sqlite_master for this index
2715 */
2716 sqlite3NestedParse(pParse,
drhb7654112008-01-12 12:48:07 +00002717 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
drh063336a2004-11-05 20:58:39 +00002718 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2719 pIndex->zName,
2720 pTab->zName,
drhb7654112008-01-12 12:48:07 +00002721 iMem,
drh063336a2004-11-05 20:58:39 +00002722 zStmt
2723 );
drh633e6d52008-07-28 19:34:53 +00002724 sqlite3DbFree(db, zStmt);
drh063336a2004-11-05 20:58:39 +00002725
danielk1977a21c6b62005-01-24 10:25:59 +00002726 /* Fill the index with data and reparse the schema. Code an OP_Expire
2727 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002728 */
danielk1977cbb18d22004-05-28 11:37:27 +00002729 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002730 sqlite3RefillIndex(pParse, pIndex, iMem);
drh9cbf3422008-01-17 16:22:13 +00002731 sqlite3ChangeCookie(pParse, iDb);
drh66a51672008-01-03 00:01:23 +00002732 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
2733 sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
2734 sqlite3VdbeAddOp1(v, OP_Expire, 0);
drh5e00f6c2001-09-13 13:46:56 +00002735 }
drh75897232000-05-29 14:26:00 +00002736 }
2737
danielk1977d8123362004-06-12 09:25:12 +00002738 /* When adding an index to the list of indices for a table, make
2739 ** sure all indices labeled OE_Replace come after all those labeled
2740 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2741 ** and INSERT.
2742 */
drh234c39d2004-07-24 03:30:47 +00002743 if( db->init.busy || pTblName==0 ){
2744 if( onError!=OE_Replace || pTab->pIndex==0
2745 || pTab->pIndex->onError==OE_Replace){
2746 pIndex->pNext = pTab->pIndex;
2747 pTab->pIndex = pIndex;
2748 }else{
2749 Index *pOther = pTab->pIndex;
2750 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2751 pOther = pOther->pNext;
2752 }
2753 pIndex->pNext = pOther->pNext;
2754 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002755 }
drh234c39d2004-07-24 03:30:47 +00002756 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002757 }
danielk1977d8123362004-06-12 09:25:12 +00002758
drh75897232000-05-29 14:26:00 +00002759 /* Clean up before exiting */
2760exit_create_index:
drh956bc922004-07-24 17:38:29 +00002761 if( pIndex ){
2762 freeIndex(pIndex);
2763 }
drh633e6d52008-07-28 19:34:53 +00002764 sqlite3ExprListDelete(db, pList);
2765 sqlite3SrcListDelete(db, pTblName);
2766 sqlite3DbFree(db, zName);
drh75897232000-05-29 14:26:00 +00002767 return;
2768}
2769
2770/*
drhd28bcb32005-12-21 14:43:11 +00002771** Generate code to make sure the file format number is at least minFormat.
2772** The generated code will increase the file format number if necessary.
2773*/
2774void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2775 Vdbe *v;
2776 v = sqlite3GetVdbe(pParse);
2777 if( v ){
drh1db639c2008-01-17 02:36:28 +00002778 int r1 = sqlite3GetTempReg(pParse);
2779 int r2 = sqlite3GetTempReg(pParse);
2780 int j1;
2781 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, 1);
drhfb982642007-08-30 01:19:59 +00002782 sqlite3VdbeUsesBtree(v, iDb);
drh1db639c2008-01-17 02:36:28 +00002783 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
2784 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
2785 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, 1, r2);
2786 sqlite3VdbeJumpHere(v, j1);
2787 sqlite3ReleaseTempReg(pParse, r1);
2788 sqlite3ReleaseTempReg(pParse, r2);
drhd28bcb32005-12-21 14:43:11 +00002789 }
2790}
2791
2792/*
drh51147ba2005-07-23 22:59:55 +00002793** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002794** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002795**
2796** aiRowEst[0] is suppose to contain the number of elements in the index.
2797** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2798** number of rows in the table that match any particular value of the
2799** first column of the index. aiRowEst[2] is an estimate of the number
2800** of rows that match any particular combiniation of the first 2 columns
2801** of the index. And so forth. It must always be the case that
2802*
2803** aiRowEst[N]<=aiRowEst[N-1]
2804** aiRowEst[N]>=1
2805**
2806** Apart from that, we have little to go on besides intuition as to
2807** how aiRowEst[] should be initialized. The numbers generated here
2808** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002809*/
2810void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002811 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002812 int i;
drh28c4cf42005-07-27 20:41:43 +00002813 assert( a!=0 );
2814 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002815 for(i=pIdx->nColumn; i>=5; i--){
2816 a[i] = 5;
2817 }
2818 while( i>=1 ){
2819 a[i] = 11 - i;
2820 i--;
drh28c4cf42005-07-27 20:41:43 +00002821 }
2822 if( pIdx->onError!=OE_None ){
2823 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002824 }
2825}
2826
2827/*
drh74e24cd2002-01-09 03:19:59 +00002828** This routine will drop an existing named index. This routine
2829** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002830*/
drh4d91a702006-01-04 15:54:36 +00002831void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002832 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002833 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002834 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002835 int iDb;
drh75897232000-05-29 14:26:00 +00002836
drh17435752007-08-16 04:30:38 +00002837 if( pParse->nErr || db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002838 goto exit_drop_index;
2839 }
drhd24cc422003-03-27 12:51:24 +00002840 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002841 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2842 goto exit_drop_index;
2843 }
danielk19774adee202004-05-08 08:23:19 +00002844 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002845 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002846 if( !ifExists ){
2847 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2848 }
drha6ecd332004-06-10 00:29:09 +00002849 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002850 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002851 }
drh485b39b2002-07-13 03:11:52 +00002852 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002853 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002854 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002855 goto exit_drop_index;
2856 }
danielk1977da184232006-01-05 11:34:32 +00002857 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002858#ifndef SQLITE_OMIT_AUTHORIZATION
2859 {
2860 int code = SQLITE_DROP_INDEX;
2861 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002862 const char *zDb = db->aDb[iDb].zName;
2863 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002864 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002865 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002866 }
danielk1977da184232006-01-05 11:34:32 +00002867 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002868 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002869 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002870 }
drhed6c8672003-01-12 18:02:16 +00002871 }
drhe5f9c642003-01-13 23:27:31 +00002872#endif
drh75897232000-05-29 14:26:00 +00002873
2874 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002875 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002876 if( v ){
drh77658e22007-12-04 16:54:52 +00002877 sqlite3BeginWriteOperation(pParse, 1, iDb);
drhb17131a2004-11-05 22:18:49 +00002878 sqlite3NestedParse(pParse,
2879 "DELETE FROM %Q.%s WHERE name=%Q",
2880 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2881 pIndex->zName
2882 );
danielk1977006015d2008-04-11 17:11:26 +00002883 if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
2884 sqlite3NestedParse(pParse,
2885 "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
2886 db->aDb[iDb].zName, pIndex->zName
2887 );
2888 }
drh9cbf3422008-01-17 16:22:13 +00002889 sqlite3ChangeCookie(pParse, iDb);
drhb17131a2004-11-05 22:18:49 +00002890 destroyRootPage(pParse, pIndex->tnum, iDb);
drh66a51672008-01-03 00:01:23 +00002891 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002892 }
2893
drhd24cc422003-03-27 12:51:24 +00002894exit_drop_index:
drh633e6d52008-07-28 19:34:53 +00002895 sqlite3SrcListDelete(db, pName);
drh75897232000-05-29 14:26:00 +00002896}
2897
2898/*
drhcf643722007-03-27 13:36:37 +00002899** pArray is a pointer to an array of objects. Each object in the
2900** array is szEntry bytes in size. This routine allocates a new
2901** object on the end of the array.
drh13449892005-09-07 21:22:45 +00002902**
drhcf643722007-03-27 13:36:37 +00002903** *pnEntry is the number of entries already in use. *pnAlloc is
2904** the previously allocated size of the array. initSize is the
2905** suggested initial array size allocation.
drh13449892005-09-07 21:22:45 +00002906**
drhcf643722007-03-27 13:36:37 +00002907** The index of the new entry is returned in *pIdx.
drh13449892005-09-07 21:22:45 +00002908**
drhcf643722007-03-27 13:36:37 +00002909** This routine returns a pointer to the array of objects. This
2910** might be the same as the pArray parameter or it might be a different
2911** pointer if the array was resized.
drh13449892005-09-07 21:22:45 +00002912*/
drhcf643722007-03-27 13:36:37 +00002913void *sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002914 sqlite3 *db, /* Connection to notify of malloc failures */
drhcf643722007-03-27 13:36:37 +00002915 void *pArray, /* Array of objects. Might be reallocated */
2916 int szEntry, /* Size of each object in the array */
2917 int initSize, /* Suggested initial allocation, in elements */
2918 int *pnEntry, /* Number of objects currently in use */
2919 int *pnAlloc, /* Current size of the allocation, in elements */
2920 int *pIdx /* Write the index of a new slot here */
2921){
2922 char *z;
2923 if( *pnEntry >= *pnAlloc ){
drh13449892005-09-07 21:22:45 +00002924 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002925 int newSize;
drhcf643722007-03-27 13:36:37 +00002926 newSize = (*pnAlloc)*2 + initSize;
danielk197726783a52007-08-29 14:06:22 +00002927 pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002928 if( pNew==0 ){
drhcf643722007-03-27 13:36:37 +00002929 *pIdx = -1;
2930 return pArray;
drh13449892005-09-07 21:22:45 +00002931 }
drh6a1e0712008-12-05 15:24:15 +00002932 *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
drhcf643722007-03-27 13:36:37 +00002933 pArray = pNew;
drh13449892005-09-07 21:22:45 +00002934 }
drhcf643722007-03-27 13:36:37 +00002935 z = (char*)pArray;
2936 memset(&z[*pnEntry * szEntry], 0, szEntry);
2937 *pIdx = *pnEntry;
2938 ++*pnEntry;
2939 return pArray;
drh13449892005-09-07 21:22:45 +00002940}
2941
2942/*
drh75897232000-05-29 14:26:00 +00002943** Append a new element to the given IdList. Create a new IdList if
2944** need be.
drhdaffd0e2001-04-11 14:28:42 +00002945**
2946** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002947*/
drh17435752007-08-16 04:30:38 +00002948IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002949 int i;
drh75897232000-05-29 14:26:00 +00002950 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00002951 pList = sqlite3DbMallocZero(db, sizeof(IdList) );
drh75897232000-05-29 14:26:00 +00002952 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002953 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002954 }
drhcf643722007-03-27 13:36:37 +00002955 pList->a = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00002956 db,
drhcf643722007-03-27 13:36:37 +00002957 pList->a,
2958 sizeof(pList->a[0]),
2959 5,
2960 &pList->nId,
2961 &pList->nAlloc,
2962 &i
2963 );
drh13449892005-09-07 21:22:45 +00002964 if( i<0 ){
drh633e6d52008-07-28 19:34:53 +00002965 sqlite3IdListDelete(db, pList);
drh13449892005-09-07 21:22:45 +00002966 return 0;
drh75897232000-05-29 14:26:00 +00002967 }
drh17435752007-08-16 04:30:38 +00002968 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
drh75897232000-05-29 14:26:00 +00002969 return pList;
2970}
2971
2972/*
drhfe05af82005-07-21 03:14:59 +00002973** Delete an IdList.
2974*/
drh633e6d52008-07-28 19:34:53 +00002975void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
drhfe05af82005-07-21 03:14:59 +00002976 int i;
2977 if( pList==0 ) return;
2978 for(i=0; i<pList->nId; i++){
drh633e6d52008-07-28 19:34:53 +00002979 sqlite3DbFree(db, pList->a[i].zName);
drhfe05af82005-07-21 03:14:59 +00002980 }
drh633e6d52008-07-28 19:34:53 +00002981 sqlite3DbFree(db, pList->a);
2982 sqlite3DbFree(db, pList);
drhfe05af82005-07-21 03:14:59 +00002983}
2984
2985/*
2986** Return the index in pList of the identifier named zId. Return -1
2987** if not found.
2988*/
2989int sqlite3IdListIndex(IdList *pList, const char *zName){
2990 int i;
2991 if( pList==0 ) return -1;
2992 for(i=0; i<pList->nId; i++){
2993 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2994 }
2995 return -1;
2996}
2997
2998/*
drha78c22c2008-11-11 18:28:58 +00002999** Expand the space allocated for the given SrcList object by
3000** creating nExtra new slots beginning at iStart. iStart is zero based.
3001** New slots are zeroed.
3002**
3003** For example, suppose a SrcList initially contains two entries: A,B.
3004** To append 3 new entries onto the end, do this:
3005**
3006** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
3007**
3008** After the call above it would contain: A, B, nil, nil, nil.
3009** If the iStart argument had been 1 instead of 2, then the result
3010** would have been: A, nil, nil, nil, B. To prepend the new slots,
3011** the iStart value would be 0. The result then would
3012** be: nil, nil, nil, A, B.
3013**
3014** If a memory allocation fails the SrcList is unchanged. The
3015** db->mallocFailed flag will be set to true.
3016*/
3017SrcList *sqlite3SrcListEnlarge(
3018 sqlite3 *db, /* Database connection to notify of OOM errors */
3019 SrcList *pSrc, /* The SrcList to be enlarged */
3020 int nExtra, /* Number of new slots to add to pSrc->a[] */
3021 int iStart /* Index in pSrc->a[] of first new slot */
3022){
3023 int i;
3024
3025 /* Sanity checking on calling parameters */
3026 assert( iStart>=0 );
3027 assert( nExtra>=1 );
3028 if( pSrc==0 || iStart>pSrc->nSrc ){
3029 assert( db->mallocFailed );
3030 return pSrc;
3031 }
3032
3033 /* Allocate additional space if needed */
3034 if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
3035 SrcList *pNew;
3036 int nAlloc = pSrc->nSrc+nExtra;
drh6a1e0712008-12-05 15:24:15 +00003037 int nGot;
drha78c22c2008-11-11 18:28:58 +00003038 pNew = sqlite3DbRealloc(db, pSrc,
3039 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
3040 if( pNew==0 ){
3041 assert( db->mallocFailed );
3042 return pSrc;
3043 }
3044 pSrc = pNew;
drh6a1e0712008-12-05 15:24:15 +00003045 nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
3046 pSrc->nAlloc = nGot;
drha78c22c2008-11-11 18:28:58 +00003047 }
3048
3049 /* Move existing slots that come after the newly inserted slots
3050 ** out of the way */
3051 for(i=pSrc->nSrc-1; i>=iStart; i--){
3052 pSrc->a[i+nExtra] = pSrc->a[i];
3053 }
3054 pSrc->nSrc += nExtra;
3055
3056 /* Zero the newly allocated slots */
3057 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
3058 for(i=iStart; i<iStart+nExtra; i++){
3059 pSrc->a[i].iCursor = -1;
3060 }
3061
3062 /* Return a pointer to the enlarged SrcList */
3063 return pSrc;
3064}
3065
3066
3067/*
drhad3cab52002-05-24 02:04:32 +00003068** Append a new table name to the given SrcList. Create a new SrcList if
3069** need be. A new entry is created in the SrcList even if pToken is NULL.
3070**
drha78c22c2008-11-11 18:28:58 +00003071** A SrcList is returned, or NULL if there is an OOM error. The returned
3072** SrcList might be the same as the SrcList that was input or it might be
3073** a new one. If an OOM error does occurs, then the prior value of pList
3074** that is input to this routine is automatically freed.
drh113088e2003-03-20 01:16:58 +00003075**
3076** If pDatabase is not null, it means that the table has an optional
3077** database name prefix. Like this: "database.table". The pDatabase
3078** points to the table name and the pTable points to the database name.
3079** The SrcList.a[].zName field is filled with the table name which might
3080** come from pTable (if pDatabase is NULL) or from pDatabase.
3081** SrcList.a[].zDatabase is filled with the database name from pTable,
3082** or with NULL if no database is specified.
3083**
3084** In other words, if call like this:
3085**
drh17435752007-08-16 04:30:38 +00003086** sqlite3SrcListAppend(D,A,B,0);
drh113088e2003-03-20 01:16:58 +00003087**
3088** Then B is a table name and the database name is unspecified. If called
3089** like this:
3090**
drh17435752007-08-16 04:30:38 +00003091** sqlite3SrcListAppend(D,A,B,C);
drh113088e2003-03-20 01:16:58 +00003092**
3093** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00003094*/
drh17435752007-08-16 04:30:38 +00003095SrcList *sqlite3SrcListAppend(
3096 sqlite3 *db, /* Connection to notify of malloc failures */
3097 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
3098 Token *pTable, /* Table to append */
3099 Token *pDatabase /* Database of the table */
3100){
drha99db3b2004-06-19 14:49:12 +00003101 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003102 if( pList==0 ){
drh17435752007-08-16 04:30:38 +00003103 pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00003104 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00003105 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00003106 }
drha78c22c2008-11-11 18:28:58 +00003107 pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
3108 if( db->mallocFailed ){
3109 sqlite3SrcListDelete(db, pList);
3110 return 0;
drhad3cab52002-05-24 02:04:32 +00003111 }
drha78c22c2008-11-11 18:28:58 +00003112 pItem = &pList->a[pList->nSrc-1];
drh113088e2003-03-20 01:16:58 +00003113 if( pDatabase && pDatabase->z==0 ){
3114 pDatabase = 0;
3115 }
3116 if( pDatabase && pTable ){
3117 Token *pTemp = pDatabase;
3118 pDatabase = pTable;
3119 pTable = pTemp;
3120 }
drh17435752007-08-16 04:30:38 +00003121 pItem->zName = sqlite3NameFromToken(db, pTable);
3122 pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
drhad3cab52002-05-24 02:04:32 +00003123 return pList;
3124}
3125
3126/*
drhdfe88ec2008-11-03 20:55:06 +00003127** Assign VdbeCursor index numbers to all tables in a SrcList
drh63eb5f22003-04-29 16:20:44 +00003128*/
danielk19774adee202004-05-08 08:23:19 +00003129void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00003130 int i;
drh9b3187e2005-01-18 14:45:47 +00003131 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003132 assert(pList || pParse->db->mallocFailed );
danielk1977261919c2005-12-06 12:52:59 +00003133 if( pList ){
3134 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
3135 if( pItem->iCursor>=0 ) break;
3136 pItem->iCursor = pParse->nTab++;
3137 if( pItem->pSelect ){
3138 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
3139 }
drh63eb5f22003-04-29 16:20:44 +00003140 }
3141 }
3142}
3143
3144/*
drhad3cab52002-05-24 02:04:32 +00003145** Delete an entire SrcList including all its substructure.
3146*/
drh633e6d52008-07-28 19:34:53 +00003147void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00003148 int i;
drhbe5c89a2004-07-26 00:31:09 +00003149 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00003150 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00003151 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00003152 sqlite3DbFree(db, pItem->zDatabase);
3153 sqlite3DbFree(db, pItem->zName);
3154 sqlite3DbFree(db, pItem->zAlias);
danielk197785574e32008-10-06 05:32:18 +00003155 sqlite3DbFree(db, pItem->zIndex);
danielk1977a04a34f2007-04-16 15:06:25 +00003156 sqlite3DeleteTable(pItem->pTab);
drh633e6d52008-07-28 19:34:53 +00003157 sqlite3SelectDelete(db, pItem->pSelect);
3158 sqlite3ExprDelete(db, pItem->pOn);
3159 sqlite3IdListDelete(db, pItem->pUsing);
drh75897232000-05-29 14:26:00 +00003160 }
drh633e6d52008-07-28 19:34:53 +00003161 sqlite3DbFree(db, pList);
drh75897232000-05-29 14:26:00 +00003162}
3163
drh982cef72000-05-30 16:27:03 +00003164/*
drh61dfc312006-12-16 16:25:15 +00003165** This routine is called by the parser to add a new term to the
3166** end of a growing FROM clause. The "p" parameter is the part of
3167** the FROM clause that has already been constructed. "p" is NULL
3168** if this is the first term of the FROM clause. pTable and pDatabase
3169** are the name of the table and database named in the FROM clause term.
3170** pDatabase is NULL if the database name qualifier is missing - the
3171** usual case. If the term has a alias, then pAlias points to the
3172** alias token. If the term is a subquery, then pSubquery is the
3173** SELECT statement that the subquery encodes. The pTable and
3174** pDatabase parameters are NULL for subqueries. The pOn and pUsing
3175** parameters are the content of the ON and USING clauses.
3176**
3177** Return a new SrcList which encodes is the FROM with the new
3178** term added.
3179*/
3180SrcList *sqlite3SrcListAppendFromTerm(
drh17435752007-08-16 04:30:38 +00003181 Parse *pParse, /* Parsing context */
drh61dfc312006-12-16 16:25:15 +00003182 SrcList *p, /* The left part of the FROM clause already seen */
3183 Token *pTable, /* Name of the table to add to the FROM clause */
3184 Token *pDatabase, /* Name of the database containing pTable */
3185 Token *pAlias, /* The right-hand side of the AS subexpression */
3186 Select *pSubquery, /* A subquery used in place of a table name */
3187 Expr *pOn, /* The ON clause of a join */
3188 IdList *pUsing /* The USING clause of a join */
3189){
3190 struct SrcList_item *pItem;
drh17435752007-08-16 04:30:38 +00003191 sqlite3 *db = pParse->db;
3192 p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
drh61dfc312006-12-16 16:25:15 +00003193 if( p==0 || p->nSrc==0 ){
drh633e6d52008-07-28 19:34:53 +00003194 sqlite3ExprDelete(db, pOn);
3195 sqlite3IdListDelete(db, pUsing);
3196 sqlite3SelectDelete(db, pSubquery);
drh61dfc312006-12-16 16:25:15 +00003197 return p;
3198 }
3199 pItem = &p->a[p->nSrc-1];
3200 if( pAlias && pAlias->n ){
drh17435752007-08-16 04:30:38 +00003201 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
drh61dfc312006-12-16 16:25:15 +00003202 }
3203 pItem->pSelect = pSubquery;
3204 pItem->pOn = pOn;
3205 pItem->pUsing = pUsing;
3206 return p;
3207}
3208
3209/*
danielk1977b1c685b2008-10-06 16:18:39 +00003210** Add an INDEXED BY or NOT INDEXED clause to the most recently added
3211** element of the source-list passed as the second argument.
3212*/
3213void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
3214 if( pIndexedBy && p && p->nSrc>0 ){
3215 struct SrcList_item *pItem = &p->a[p->nSrc-1];
3216 assert( pItem->notIndexed==0 && pItem->zIndex==0 );
3217 if( pIndexedBy->n==1 && !pIndexedBy->z ){
3218 /* A "NOT INDEXED" clause was supplied. See parse.y
3219 ** construct "indexed_opt" for details. */
3220 pItem->notIndexed = 1;
3221 }else{
3222 pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
3223 }
3224 }
3225}
3226
3227/*
drh61dfc312006-12-16 16:25:15 +00003228** When building up a FROM clause in the parser, the join operator
3229** is initially attached to the left operand. But the code generator
3230** expects the join operator to be on the right operand. This routine
3231** Shifts all join operators from left to right for an entire FROM
3232** clause.
3233**
3234** Example: Suppose the join is like this:
3235**
3236** A natural cross join B
3237**
3238** The operator is "natural cross join". The A and B operands are stored
3239** in p->a[0] and p->a[1], respectively. The parser initially stores the
3240** operator with A. This routine shifts that operator over to B.
3241*/
3242void sqlite3SrcListShiftJoinType(SrcList *p){
3243 if( p && p->a ){
3244 int i;
3245 for(i=p->nSrc-1; i>0; i--){
3246 p->a[i].jointype = p->a[i-1].jointype;
3247 }
3248 p->a[0].jointype = 0;
3249 }
3250}
3251
3252/*
drhc4a3c772001-04-04 11:48:57 +00003253** Begin a transaction
3254*/
drh684917c2004-10-05 02:41:42 +00003255void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00003256 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003257 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00003258 int i;
drh5e00f6c2001-09-13 13:46:56 +00003259
drh001bbcb2003-03-19 03:14:00 +00003260 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003261 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003262 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003263
3264 v = sqlite3GetVdbe(pParse);
3265 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00003266 if( type!=TK_DEFERRED ){
3267 for(i=0; i<db->nDb; i++){
drh66a51672008-01-03 00:01:23 +00003268 sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
drhfb982642007-08-30 01:19:59 +00003269 sqlite3VdbeUsesBtree(v, i);
drh684917c2004-10-05 02:41:42 +00003270 }
3271 }
drh66a51672008-01-03 00:01:23 +00003272 sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00003273}
3274
3275/*
3276** Commit a transaction
3277*/
danielk19774adee202004-05-08 08:23:19 +00003278void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003279 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00003280 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00003281
drh001bbcb2003-03-19 03:14:00 +00003282 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003283 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003284 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003285
3286 v = sqlite3GetVdbe(pParse);
3287 if( v ){
drh66a51672008-01-03 00:01:23 +00003288 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00003289 }
drhc4a3c772001-04-04 11:48:57 +00003290}
3291
3292/*
3293** Rollback a transaction
3294*/
danielk19774adee202004-05-08 08:23:19 +00003295void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00003296 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00003297 Vdbe *v;
3298
drh001bbcb2003-03-19 03:14:00 +00003299 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh17435752007-08-16 04:30:38 +00003300 if( pParse->nErr || db->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00003301 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00003302
danielk19774adee202004-05-08 08:23:19 +00003303 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00003304 if( v ){
drh66a51672008-01-03 00:01:23 +00003305 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00003306 }
drhc4a3c772001-04-04 11:48:57 +00003307}
drhf57b14a2001-09-14 18:54:08 +00003308
3309/*
drhdc3ff9c2004-08-18 02:10:15 +00003310** Make sure the TEMP database is open and available for use. Return
3311** the number of errors. Leave any error messages in the pParse structure.
3312*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003313int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003314 sqlite3 *db = pParse->db;
3315 if( db->aDb[1].pBt==0 && !pParse->explain ){
drh33f4e022007-09-03 15:19:34 +00003316 int rc;
3317 static const int flags =
3318 SQLITE_OPEN_READWRITE |
3319 SQLITE_OPEN_CREATE |
3320 SQLITE_OPEN_EXCLUSIVE |
3321 SQLITE_OPEN_DELETEONCLOSE |
3322 SQLITE_OPEN_TEMP_DB;
3323
3324 rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags,
drhc797d4d2007-05-08 01:08:49 +00003325 &db->aDb[1].pBt);
drhdc3ff9c2004-08-18 02:10:15 +00003326 if( rc!=SQLITE_OK ){
3327 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3328 "file for storing temporary tables");
3329 pParse->rc = rc;
3330 return 1;
3331 }
drh60a713c2008-01-21 16:22:45 +00003332 assert( (db->flags & SQLITE_InTrans)==0 || db->autoCommit );
danielk197714db2662006-01-09 16:12:04 +00003333 assert( db->aDb[1].pSchema );
drhfdc40e92008-04-17 20:59:37 +00003334 sqlite3PagerJournalMode(sqlite3BtreePager(db->aDb[1].pBt),
3335 db->dfltJournalMode);
drhdc3ff9c2004-08-18 02:10:15 +00003336 }
3337 return 0;
3338}
3339
3340/*
drh80242052004-06-09 00:48:12 +00003341** Generate VDBE code that will verify the schema cookie and start
3342** a read-transaction for all named database files.
3343**
3344** It is important that all schema cookies be verified and all
3345** read transactions be started before anything else happens in
3346** the VDBE program. But this routine can be called after much other
3347** code has been generated. So here is what we do:
3348**
drhc275b4e2004-07-19 17:25:24 +00003349** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003350** will jump to a subroutine at the end of the program. Then we
3351** record every database that needs its schema verified in the
3352** pParse->cookieMask field. Later, after all other code has been
3353** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003354** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003355** will be made to point to that subroutine. The generation of the
3356** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003357**
3358** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3359** schema on any databases. This can be used to position the OP_Goto
3360** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003361*/
danielk19774adee202004-05-08 08:23:19 +00003362void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003363 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003364 Vdbe *v;
3365 int mask;
3366
3367 v = sqlite3GetVdbe(pParse);
3368 if( v==0 ) return; /* This only happens if there was a prior error */
3369 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003370 if( pParse->cookieGoto==0 ){
drh66a51672008-01-03 00:01:23 +00003371 pParse->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003372 }
drhc275b4e2004-07-19 17:25:24 +00003373 if( iDb>=0 ){
3374 assert( iDb<db->nDb );
3375 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drhc797d4d2007-05-08 01:08:49 +00003376 assert( iDb<SQLITE_MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003377 mask = 1<<iDb;
3378 if( (pParse->cookieMask & mask)==0 ){
3379 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003380 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003381 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003382 sqlite3OpenTempDatabase(pParse);
3383 }
drhc275b4e2004-07-19 17:25:24 +00003384 }
drh001bbcb2003-03-19 03:14:00 +00003385 }
drh001bbcb2003-03-19 03:14:00 +00003386}
3387
3388/*
drh1c928532002-01-31 15:54:21 +00003389** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003390** might change the database.
3391**
3392** This routine starts a new transaction if we are not already within
3393** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003394** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003395** be set for operations that might fail (due to a constraint) part of
3396** the way through and which will need to undo some writes without having to
3397** rollback the whole transaction. For operations where all constraints
3398** can be checked before any changes are made to the database, it is never
3399** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003400**
drh8bf8dc92003-05-17 17:35:10 +00003401** Only database iDb and the temp database are made writable by this call.
3402** If iDb==0, then the main and temp databases are made writable. If
3403** iDb==1 then only the temp database is made writable. If iDb>1 then the
3404** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003405*/
drh7f0f12e2004-05-21 13:39:50 +00003406void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003407 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003408 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003409 sqlite3CodeVerifySchema(pParse, iDb);
3410 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003411 if( setStatement && pParse->nested==0 ){
drh66a51672008-01-03 00:01:23 +00003412 sqlite3VdbeAddOp1(v, OP_Statement, iDb);
danielk19771d850a72004-05-31 08:26:49 +00003413 }
danielk197753c0f742005-03-29 03:10:59 +00003414 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003415 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003416 }
3417}
3418
drh4343fea2004-11-05 23:46:15 +00003419/*
3420** Check to see if pIndex uses the collating sequence pColl. Return
3421** true if it does and false if it does not.
3422*/
3423#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003424static int collationMatch(const char *zColl, Index *pIndex){
3425 int i;
3426 for(i=0; i<pIndex->nColumn; i++){
3427 const char *z = pIndex->azColl[i];
3428 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3429 return 1;
3430 }
drh4343fea2004-11-05 23:46:15 +00003431 }
3432 return 0;
3433}
3434#endif
3435
3436/*
3437** Recompute all indices of pTab that use the collating sequence pColl.
3438** If pColl==0 then recompute all indices of pTab.
3439*/
3440#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003441static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003442 Index *pIndex; /* An index associated with pTab */
3443
3444 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003445 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003446 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3447 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003448 sqlite3RefillIndex(pParse, pIndex, -1);
3449 }
3450 }
3451}
3452#endif
3453
3454/*
3455** Recompute all indices of all tables in all databases where the
3456** indices use the collating sequence pColl. If pColl==0 then recompute
3457** all indices everywhere.
3458*/
3459#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003460static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003461 Db *pDb; /* A single database */
3462 int iDb; /* The database index number */
3463 sqlite3 *db = pParse->db; /* The database connection */
3464 HashElem *k; /* For looping over tables in pDb */
3465 Table *pTab; /* A table in the database */
3466
3467 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003468 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003469 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003470 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003471 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003472 }
3473 }
3474}
3475#endif
3476
3477/*
drheee46cf2004-11-06 00:02:48 +00003478** Generate code for the REINDEX command.
3479**
3480** REINDEX -- 1
3481** REINDEX <collation> -- 2
3482** REINDEX ?<database>.?<tablename> -- 3
3483** REINDEX ?<database>.?<indexname> -- 4
3484**
3485** Form 1 causes all indices in all attached databases to be rebuilt.
3486** Form 2 rebuilds all indices in all databases that use the named
3487** collating function. Forms 3 and 4 rebuild the named index or all
3488** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003489*/
3490#ifndef SQLITE_OMIT_REINDEX
3491void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3492 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3493 char *z; /* Name of a table or index */
3494 const char *zDb; /* Name of the database */
3495 Table *pTab; /* A table in the database */
3496 Index *pIndex; /* An index associated with pTab */
3497 int iDb; /* The database index number */
3498 sqlite3 *db = pParse->db; /* The database connection */
3499 Token *pObjName; /* Name of the table or index to be reindexed */
3500
danielk197733a5edc2005-01-27 00:22:02 +00003501 /* Read the database schema. If an error occurs, leave an error message
3502 ** and code in pParse and return NULL. */
3503 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003504 return;
danielk197733a5edc2005-01-27 00:22:02 +00003505 }
3506
drhe497f002004-11-07 13:01:49 +00003507 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003508 reindexDatabases(pParse, 0);
3509 return;
drhe497f002004-11-07 13:01:49 +00003510 }else if( pName2==0 || pName2->z==0 ){
danielk197739002502007-11-12 09:50:26 +00003511 char *zColl;
danielk1977b3bf5562006-01-10 17:58:23 +00003512 assert( pName1->z );
danielk197739002502007-11-12 09:50:26 +00003513 zColl = sqlite3NameFromToken(pParse->db, pName1);
3514 if( !zColl ) return;
3515 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, -1, 0);
drh4343fea2004-11-05 23:46:15 +00003516 if( pColl ){
danielk1977f0113002006-01-24 12:09:17 +00003517 if( zColl ){
3518 reindexDatabases(pParse, zColl);
drh633e6d52008-07-28 19:34:53 +00003519 sqlite3DbFree(db, zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003520 }
drh4343fea2004-11-05 23:46:15 +00003521 return;
3522 }
drh633e6d52008-07-28 19:34:53 +00003523 sqlite3DbFree(db, zColl);
drh4343fea2004-11-05 23:46:15 +00003524 }
3525 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3526 if( iDb<0 ) return;
drh17435752007-08-16 04:30:38 +00003527 z = sqlite3NameFromToken(db, pObjName);
drh84f31122007-05-12 15:00:14 +00003528 if( z==0 ) return;
drh4343fea2004-11-05 23:46:15 +00003529 zDb = db->aDb[iDb].zName;
3530 pTab = sqlite3FindTable(db, z, zDb);
3531 if( pTab ){
3532 reindexTable(pParse, pTab, 0);
drh633e6d52008-07-28 19:34:53 +00003533 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003534 return;
3535 }
3536 pIndex = sqlite3FindIndex(db, z, zDb);
drh633e6d52008-07-28 19:34:53 +00003537 sqlite3DbFree(db, z);
drh4343fea2004-11-05 23:46:15 +00003538 if( pIndex ){
3539 sqlite3BeginWriteOperation(pParse, 0, iDb);
3540 sqlite3RefillIndex(pParse, pIndex, -1);
3541 return;
3542 }
3543 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3544}
3545#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003546
3547/*
3548** Return a dynamicly allocated KeyInfo structure that can be used
3549** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3550**
3551** If successful, a pointer to the new structure is returned. In this case
drh633e6d52008-07-28 19:34:53 +00003552** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
danielk1977b3bf5562006-01-10 17:58:23 +00003553** pointer. If an error occurs (out of memory or missing collation
3554** sequence), NULL is returned and the state of pParse updated to reflect
3555** the error.
3556*/
3557KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3558 int i;
3559 int nCol = pIdx->nColumn;
3560 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
drh633e6d52008-07-28 19:34:53 +00003561 sqlite3 *db = pParse->db;
3562 KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
danielk1977b3bf5562006-01-10 17:58:23 +00003563
3564 if( pKey ){
drhb21c8cd2007-08-21 19:33:56 +00003565 pKey->db = pParse->db;
danielk1977b3bf5562006-01-10 17:58:23 +00003566 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3567 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3568 for(i=0; i<nCol; i++){
3569 char *zColl = pIdx->azColl[i];
3570 assert( zColl );
3571 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3572 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3573 }
3574 pKey->nField = nCol;
3575 }
3576
3577 if( pParse->nErr ){
drh633e6d52008-07-28 19:34:53 +00003578 sqlite3DbFree(db, pKey);
danielk1977b3bf5562006-01-10 17:58:23 +00003579 pKey = 0;
3580 }
3581 return pKey;
3582}