blob: 65ce2e5331ac362d6b7a94dc260066d9c47d958d [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**
danielk1977b82e7ed2006-01-11 14:09:31 +000025** $Id: build.c,v 1.376 2006/01/11 14:09:32 danielk1977 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 {
45 int iDb;
46 int iTab;
47 u8 isWriteLock;
48 const char *zName;
49};
50
51/*
52** Have the compiled statement lock the table with rootpage iTab in database
53** iDb at the shared-cache level when executed. The isWriteLock argument
54** is zero for a read-lock, or non-zero for a write-lock.
55**
56** The zName parameter should point to the unqualified table name. This is
57** used to provide a more informative error message should the lock fail.
58*/
59void sqlite3TableLock(
60 Parse *pParse,
61 int iDb,
62 int iTab,
63 u8 isWriteLock,
64 const char *zName
65){
66 int i;
67 int nBytes;
68 TableLock *p;
danielk1977e501b892006-01-09 06:29:47 +000069 ThreadData *pTsd = sqlite3ThreadData();
danielk1977c00da102006-01-07 13:21:04 +000070
danielk197714db2662006-01-09 16:12:04 +000071 if( 0==pTsd->useSharedData || iDb<0 ){
danielk1977c00da102006-01-07 13:21:04 +000072 return;
73 }
74
75 for(i=0; i<pParse->nTableLock; i++){
76 p = &pParse->aTableLock[i];
77 if( p->iDb==iDb && p->iTab==iTab ){
78 p->isWriteLock = (p->isWriteLock || isWriteLock);
79 return;
80 }
81 }
82
83 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
84 sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
85 if( pParse->aTableLock ){
86 p = &pParse->aTableLock[pParse->nTableLock++];
87 p->iDb = iDb;
88 p->iTab = iTab;
89 p->isWriteLock = isWriteLock;
90 p->zName = zName;
91 }
92}
93
94/*
95** Code an OP_TableLock instruction for each table locked by the
96** statement (configured by calls to sqlite3TableLock()).
97*/
98static void codeTableLocks(Parse *pParse){
99 int i;
100 Vdbe *pVdbe;
danielk1977e501b892006-01-09 06:29:47 +0000101 assert( sqlite3ThreadData()->useSharedData || pParse->nTableLock==0 );
danielk1977c00da102006-01-07 13:21:04 +0000102
103 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
104 return;
105 }
106
107 for(i=0; i<pParse->nTableLock; i++){
108 TableLock *p = &pParse->aTableLock[i];
109 int p1 = p->iDb;
110 if( p->isWriteLock ){
111 p1 = -1*(p1+1);
112 }
113 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
114 }
115}
116#else
117 #define codeTableLocks(x)
118#endif
119
drhe0bc4042002-06-25 01:09:11 +0000120/*
drh75897232000-05-29 14:26:00 +0000121** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000122** parsed and a VDBE program to execute that statement has been
123** prepared. This routine puts the finishing touches on the
124** VDBE program and resets the pParse structure for the next
125** parse.
drh75897232000-05-29 14:26:00 +0000126**
127** Note that if an error occurred, it might be the case that
128** no VDBE code was generated.
129*/
drh80242052004-06-09 00:48:12 +0000130void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000131 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000132 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000133
danielk1977e501b892006-01-09 06:29:47 +0000134 if( sqlite3ThreadData()->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000135 if( pParse->nested ) return;
danielk1977441daf62005-02-01 03:46:43 +0000136 if( !pParse->pVdbe ){
danielk1977c30f9e72005-02-09 07:05:46 +0000137 if( pParse->rc==SQLITE_OK && pParse->nErr ){
138 pParse->rc = SQLITE_ERROR;
139 }
danielk1977441daf62005-02-01 03:46:43 +0000140 return;
141 }
danielk197748d0d862005-02-01 03:09:52 +0000142
drh80242052004-06-09 00:48:12 +0000143 /* Begin by generating some termination code at the end of the
144 ** vdbe program
145 */
146 db = pParse->db;
147 v = sqlite3GetVdbe(pParse);
148 if( v ){
149 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
drh0e3d7472004-06-19 17:33:07 +0000150
151 /* The cookie mask contains one bit for each database file open.
152 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
153 ** set for each database that is used. Generate code to start a
154 ** transaction on each used database and to verify the schema cookie
155 ** on each used database.
156 */
drhc275b4e2004-07-19 17:25:24 +0000157 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000158 u32 mask;
159 int iDb;
drhd654be82005-09-20 17:42:23 +0000160 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000161 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
162 if( (mask & pParse->cookieMask)==0 ) continue;
163 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drhc275b4e2004-07-19 17:25:24 +0000164 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +0000165 }
danielk1977c00da102006-01-07 13:21:04 +0000166
167 /* Once all the cookies have been verified and transactions opened,
168 ** obtain the required table-locks. This is a no-op unless the
169 ** shared-cache feature is enabled.
170 */
171 codeTableLocks(pParse);
drhc275b4e2004-07-19 17:25:24 +0000172 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000173 }
drh80242052004-06-09 00:48:12 +0000174
drh19e2d372005-08-29 23:00:03 +0000175#ifndef SQLITE_OMIT_TRACE
drh71c697e2004-08-08 23:39:19 +0000176 /* Add a No-op that contains the complete text of the compiled SQL
177 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +0000178 ** of the program.
179 **
drh23bf66d2004-12-14 03:34:34 +0000180 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +0000181 */
182 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh19e2d372005-08-29 23:00:03 +0000183#endif /* SQLITE_OMIT_TRACE */
drh71c697e2004-08-08 23:39:19 +0000184 }
185
drh3f7d4e42004-07-24 14:35:58 +0000186
drh80242052004-06-09 00:48:12 +0000187 /* Get the VDBE program ready for execution
188 */
drhb86ccfb2003-01-28 23:13:10 +0000189 if( v && pParse->nErr==0 ){
190 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000191 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +0000192 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
drh13449892005-09-07 21:22:45 +0000193 pParse->nTab+3, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000194 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000195 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000196 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000197 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000198 }
drha226d052002-09-25 19:04:07 +0000199 pParse->nTab = 0;
200 pParse->nMem = 0;
201 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000202 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000203 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000204 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000205}
206
207/*
drh205f48e2004-11-05 00:43:11 +0000208** Run the parser and code generator recursively in order to generate
209** code for the SQL statement given onto the end of the pParse context
210** currently under construction. When the parser is run recursively
211** this way, the final OP_Halt is not appended and other initialization
212** and finalization steps are omitted because those are handling by the
213** outermost parser.
214**
215** Not everything is nestable. This facility is designed to permit
216** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000217** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000218*/
219void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
220 va_list ap;
221 char *zSql;
drhf1974842004-11-05 03:56:00 +0000222# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
223 char saveBuf[SAVE_SZ];
224
drh205f48e2004-11-05 00:43:11 +0000225 if( pParse->nErr ) return;
226 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
227 va_start(ap, zFormat);
228 zSql = sqlite3VMPrintf(zFormat, ap);
229 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000230 if( zSql==0 ){
231 return; /* A malloc must have failed */
232 }
drh205f48e2004-11-05 00:43:11 +0000233 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000234 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
235 memset(&pParse->nVar, 0, SAVE_SZ);
drh4f26bb62005-09-08 14:17:20 +0000236 sqlite3RunParser(pParse, zSql, 0);
drh205f48e2004-11-05 00:43:11 +0000237 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000238 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000239 pParse->nested--;
240}
241
242/*
danielk19778a414492004-06-29 08:59:35 +0000243** Locate the in-memory structure that describes a particular database
244** table given the name of that table and (optionally) the name of the
245** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000246**
danielk19778a414492004-06-29 08:59:35 +0000247** If zDatabase is 0, all databases are searched for the table and the
248** first matching table is returned. (No checking for duplicate table
249** names is done.) The search order is TEMP first, then MAIN, then any
250** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000251**
danielk19774adee202004-05-08 08:23:19 +0000252** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000253*/
drh9bb575f2004-09-06 17:24:11 +0000254Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000255 Table *p = 0;
256 int i;
drh645f63e2004-06-22 13:22:40 +0000257 assert( zName!=0 );
danielk197753c0f742005-03-29 03:10:59 +0000258 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000259 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000260 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000261 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000262 if( p ) break;
263 }
drh74e24cd2002-01-09 03:19:59 +0000264 return p;
drh75897232000-05-29 14:26:00 +0000265}
266
267/*
danielk19778a414492004-06-29 08:59:35 +0000268** Locate the in-memory structure that describes a particular database
269** table given the name of that table and (optionally) the name of the
270** database containing the table. Return NULL if not found. Also leave an
271** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000272**
danielk19778a414492004-06-29 08:59:35 +0000273** The difference between this routine and sqlite3FindTable() is that this
274** routine leaves an error message in pParse->zErrMsg where
275** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000276*/
danielk19774adee202004-05-08 08:23:19 +0000277Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000278 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000279
danielk19778a414492004-06-29 08:59:35 +0000280 /* Read the database schema. If an error occurs, leave an error message
281 ** and code in pParse and return NULL. */
282 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
283 return 0;
284 }
285
danielk19774adee202004-05-08 08:23:19 +0000286 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000287 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000288 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000289 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000290 }else{
danielk19774adee202004-05-08 08:23:19 +0000291 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000292 }
drha6ecd332004-06-10 00:29:09 +0000293 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000294 }
295 return p;
296}
297
298/*
299** Locate the in-memory structure that describes
300** a particular index given the name of that index
301** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000302** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000303**
304** If zDatabase is 0, all databases are searched for the
305** table and the first matching index is returned. (No checking
306** for duplicate index names is done.) The search order is
307** TEMP first, then MAIN, then any auxiliary databases added
308** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000309*/
drh9bb575f2004-09-06 17:24:11 +0000310Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000311 Index *p = 0;
312 int i;
danielk197753c0f742005-03-29 03:10:59 +0000313 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000314 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000315 Schema *pSchema = db->aDb[j].pSchema;
danielk19774adee202004-05-08 08:23:19 +0000316 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000317 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
318 if( pSchema ){
319 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
320 }
drhd24cc422003-03-27 12:51:24 +0000321 if( p ) break;
322 }
drh74e24cd2002-01-09 03:19:59 +0000323 return p;
drh75897232000-05-29 14:26:00 +0000324}
325
326/*
drh956bc922004-07-24 17:38:29 +0000327** Reclaim the memory used by an index
328*/
329static void freeIndex(Index *p){
330 sqliteFree(p->zColAff);
331 sqliteFree(p);
332}
333
334/*
drh75897232000-05-29 14:26:00 +0000335** Remove the given index from the index hash table, and free
336** its memory structures.
337**
drhd229ca92002-01-09 13:30:41 +0000338** The index is removed from the database hash tables but
339** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000340** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000341*/
drh9bb575f2004-09-06 17:24:11 +0000342static void sqliteDeleteIndex(sqlite3 *db, Index *p){
drhd229ca92002-01-09 13:30:41 +0000343 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000344 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000345
danielk1977da184232006-01-05 11:34:32 +0000346 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000347 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000348 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000349}
350
351/*
drhc96d8532005-05-03 12:30:33 +0000352** For the index called zIdxName which is found in the database iDb,
353** unlike that index from its Table then remove the index from
354** the index hash table and free all memory structures associated
355** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000356*/
drh9bb575f2004-09-06 17:24:11 +0000357void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000358 Index *pIndex;
359 int len;
danielk1977da184232006-01-05 11:34:32 +0000360 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000361
362 len = strlen(zIdxName);
danielk1977da184232006-01-05 11:34:32 +0000363 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
drh956bc922004-07-24 17:38:29 +0000364 if( pIndex ){
365 if( pIndex->pTable->pIndex==pIndex ){
366 pIndex->pTable->pIndex = pIndex->pNext;
367 }else{
368 Index *p;
369 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
370 if( p && p->pNext==pIndex ){
371 p->pNext = pIndex->pNext;
372 }
drh5e00f6c2001-09-13 13:46:56 +0000373 }
drh956bc922004-07-24 17:38:29 +0000374 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000375 }
drh956bc922004-07-24 17:38:29 +0000376 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000377}
378
379/*
drhe0bc4042002-06-25 01:09:11 +0000380** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000381** a single database. This routine is called to reclaim memory
382** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000383** if there were schema changes during the transaction or if a
384** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000385**
386** If iDb<=0 then reset the internal schema tables for all database
387** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000388** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000389*/
drh9bb575f2004-09-06 17:24:11 +0000390void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000391 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000392
drh1c2d8412003-03-31 00:30:47 +0000393 assert( iDb>=0 && iDb<db->nDb );
drh1c2d8412003-03-31 00:30:47 +0000394 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000395 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000396 if( pDb->pSchema ){
danielk1977de0fe3e2006-01-06 06:33:12 +0000397 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000398 }
drh1c2d8412003-03-31 00:30:47 +0000399 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000400 }
drh1c2d8412003-03-31 00:30:47 +0000401 assert( iDb==0 );
402 db->flags &= ~SQLITE_InternChanges;
403
404 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000405 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000406 ** opportunity to do this here since we have just deleted all of the
407 ** schema hash tables and therefore do not have to make any changes
408 ** to any of those tables.
409 */
drh4d189ca2004-02-12 18:46:38 +0000410 for(i=0; i<db->nDb; i++){
411 struct Db *pDb = &db->aDb[i];
412 if( pDb->pBt==0 ){
413 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
414 pDb->pAux = 0;
415 }
416 }
drh1c2d8412003-03-31 00:30:47 +0000417 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000418 struct Db *pDb = &db->aDb[i];
419 if( pDb->pBt==0 ){
420 sqliteFree(pDb->zName);
421 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000422 continue;
423 }
424 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000425 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000426 }
drh8bf8dc92003-05-17 17:35:10 +0000427 j++;
drh1c2d8412003-03-31 00:30:47 +0000428 }
429 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
430 db->nDb = j;
431 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
432 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
433 sqliteFree(db->aDb);
434 db->aDb = db->aDbStatic;
435 }
drhe0bc4042002-06-25 01:09:11 +0000436}
437
438/*
439** This routine is called whenever a rollback occurs. If there were
440** schema changes during the transaction, then we have to reset the
441** internal hash tables and reload them from disk.
442*/
drh9bb575f2004-09-06 17:24:11 +0000443void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000444 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000445 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000446 }
447}
448
449/*
450** This routine is called when a commit occurs.
451*/
drh9bb575f2004-09-06 17:24:11 +0000452void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000453 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000454}
455
456/*
drh956bc922004-07-24 17:38:29 +0000457** Clear the column names from a table or view.
458*/
459static void sqliteResetColumnNames(Table *pTable){
460 int i;
461 Column *pCol;
462 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000463 if( (pCol = pTable->aCol)!=0 ){
464 for(i=0; i<pTable->nCol; i++, pCol++){
465 sqliteFree(pCol->zName);
466 sqlite3ExprDelete(pCol->pDflt);
467 sqliteFree(pCol->zType);
danielk1977b3bf5562006-01-10 17:58:23 +0000468 sqliteFree(pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000469 }
470 sqliteFree(pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000471 }
drh956bc922004-07-24 17:38:29 +0000472 pTable->aCol = 0;
473 pTable->nCol = 0;
474}
475
476/*
drh75897232000-05-29 14:26:00 +0000477** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000478** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000479**
480** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000481** the table data structure from the hash table. Nor does it remove
482** foreign keys from the sqlite.aFKey hash table. But it does destroy
483** memory structures of the indices and foreign keys associated with
484** the table.
drhdaffd0e2001-04-11 14:28:42 +0000485**
486** Indices associated with the table are unlinked from the "db"
487** data structure if db!=NULL. If db==NULL, indices attached to
488** the table are deleted, but it is assumed they have already been
489** unlinked.
drh75897232000-05-29 14:26:00 +0000490*/
drh9bb575f2004-09-06 17:24:11 +0000491void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000492 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000493 FKey *pFKey, *pNextFKey;
494
danielk1977de0fe3e2006-01-06 06:33:12 +0000495 db = 0;
496
drh75897232000-05-29 14:26:00 +0000497 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000498
drhed8a3bb2005-06-06 21:19:56 +0000499 /* Do not delete the table until the reference count reaches zero. */
500 pTable->nRef--;
501 if( pTable->nRef>0 ){
502 return;
503 }
504 assert( pTable->nRef==0 );
505
drhc2eef3b2002-08-31 18:53:06 +0000506 /* Delete all indices associated with this table
507 */
508 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
509 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000510 assert( pIndex->pSchema==pTable->pSchema );
drhc2eef3b2002-08-31 18:53:06 +0000511 sqliteDeleteIndex(db, pIndex);
512 }
513
danielk1977576ec6b2005-01-21 11:55:25 +0000514#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000515 /* Delete all foreign keys associated with this table. The keys
516 ** should have already been unlinked from the db->aFKey hash table
517 */
518 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
519 pNextFKey = pFKey->pNextFrom;
danielk1977da184232006-01-05 11:34:32 +0000520 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
drhd24cc422003-03-27 12:51:24 +0000521 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000522 sqliteFree(pFKey);
523 }
danielk1977576ec6b2005-01-21 11:55:25 +0000524#endif
drhc2eef3b2002-08-31 18:53:06 +0000525
526 /* Delete the Table structure itself.
527 */
drh956bc922004-07-24 17:38:29 +0000528 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000529 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000530 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000531 sqlite3SelectDelete(pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000532#ifndef SQLITE_OMIT_CHECK
533 sqlite3ExprDelete(pTable->pCheck);
534#endif
drh75897232000-05-29 14:26:00 +0000535 sqliteFree(pTable);
536}
537
538/*
drh5edc3122001-09-13 21:53:09 +0000539** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000540** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000541*/
drh9bb575f2004-09-06 17:24:11 +0000542void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000543 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000544 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000545 Db *pDb;
546
drhd229ca92002-01-09 13:30:41 +0000547 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000548 assert( iDb>=0 && iDb<db->nDb );
549 assert( zTabName && zTabName[0] );
550 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +0000551 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
drh956bc922004-07-24 17:38:29 +0000552 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000553#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000554 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
555 int nTo = strlen(pF1->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +0000556 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
drh956bc922004-07-24 17:38:29 +0000557 if( pF2==pF1 ){
danielk1977da184232006-01-05 11:34:32 +0000558 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
drh956bc922004-07-24 17:38:29 +0000559 }else{
560 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
561 if( pF2 ){
562 pF2->pNextTo = pF1->pNextTo;
563 }
drhc2eef3b2002-08-31 18:53:06 +0000564 }
565 }
danielk1977576ec6b2005-01-21 11:55:25 +0000566#endif
drh956bc922004-07-24 17:38:29 +0000567 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000568 }
drh956bc922004-07-24 17:38:29 +0000569 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000570}
571
572/*
drha99db3b2004-06-19 14:49:12 +0000573** Given a token, return a string that consists of the text of that
574** token with any quotations removed. Space to hold the returned string
575** is obtained from sqliteMalloc() and must be freed by the calling
576** function.
drh75897232000-05-29 14:26:00 +0000577**
drhc96d8532005-05-03 12:30:33 +0000578** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000579** are not \000 terminated and are not persistent. The returned string
580** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000581*/
drha99db3b2004-06-19 14:49:12 +0000582char *sqlite3NameFromToken(Token *pName){
583 char *zName;
584 if( pName ){
drh2646da72005-12-09 20:02:05 +0000585 zName = sqliteStrNDup((char*)pName->z, pName->n);
drha99db3b2004-06-19 14:49:12 +0000586 sqlite3Dequote(zName);
587 }else{
588 zName = 0;
589 }
drh75897232000-05-29 14:26:00 +0000590 return zName;
591}
592
593/*
danielk1977cbb18d22004-05-28 11:37:27 +0000594** Open the sqlite_master table stored in database number iDb for
595** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000596*/
danielk1977c00da102006-01-07 13:21:04 +0000597void sqlite3OpenMasterTable(Parse *p, int iDb){
598 Vdbe *v = sqlite3GetVdbe(p);
599 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977cbb18d22004-05-28 11:37:27 +0000600 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000601 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000602 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000603}
604
605/*
danielk1977cbb18d22004-05-28 11:37:27 +0000606** The token *pName contains the name of a database (either "main" or
607** "temp" or the name of an attached db). This routine returns the
608** index of the named database in db->aDb[], or -1 if the named db
609** does not exist.
610*/
drhff2d5ea2005-07-23 00:41:48 +0000611int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000612 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000613 int n; /* Number of characters in the name */
614 Db *pDb; /* A database whose name space is being searched */
615 char *zName; /* Name we are searching for */
616
617 zName = sqlite3NameFromToken(pName);
618 if( zName ){
619 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000620 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000621 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
622 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000623 break;
drh73c42a12004-11-20 18:13:10 +0000624 }
danielk1977cbb18d22004-05-28 11:37:27 +0000625 }
drh73c42a12004-11-20 18:13:10 +0000626 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000627 }
danielk1977576ec6b2005-01-21 11:55:25 +0000628 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000629}
630
drh0e3d7472004-06-19 17:33:07 +0000631/* The table or view or trigger name is passed to this routine via tokens
632** pName1 and pName2. If the table name was fully qualified, for example:
633**
634** CREATE TABLE xxx.yyy (...);
635**
636** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
637** the table name is not fully qualified, i.e.:
638**
639** CREATE TABLE yyy(...);
640**
641** Then pName1 is set to "yyy" and pName2 is "".
642**
643** This routine sets the *ppUnqual pointer to point at the token (pName1 or
644** pName2) that stores the unqualified table name. The index of the
645** database "xxx" is returned.
646*/
danielk1977ef2cb632004-05-29 02:37:19 +0000647int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000648 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000649 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000650 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
651 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000652){
drh0e3d7472004-06-19 17:33:07 +0000653 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000654 sqlite3 *db = pParse->db;
655
656 if( pName2 && pName2->n>0 ){
657 assert( !db->init.busy );
658 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000659 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000660 if( iDb<0 ){
661 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
662 pParse->nErr++;
663 return -1;
664 }
665 }else{
666 assert( db->init.iDb==0 || db->init.busy );
667 iDb = db->init.iDb;
668 *pUnqual = pName1;
669 }
670 return iDb;
671}
672
673/*
danielk1977d8123362004-06-12 09:25:12 +0000674** This routine is used to check if the UTF-8 string zName is a legal
675** unqualified name for a new schema object (table, index, view or
676** trigger). All names are legal except those that begin with the string
677** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
678** is reserved for internal use.
679*/
680int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000681 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000682 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000683 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000684 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
685 return SQLITE_ERROR;
686 }
687 return SQLITE_OK;
688}
689
690/*
drh75897232000-05-29 14:26:00 +0000691** Begin constructing a new table representation in memory. This is
692** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000693** to a CREATE TABLE statement. In particular, this routine is called
694** after seeing tokens "CREATE" and "TABLE" and the table name. The
drhf57b3392001-10-08 13:22:32 +0000695** pStart token is the CREATE and pName is the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000696** flag is true if the table should be stored in the auxiliary database
697** file instead of in the main database file. This is normally the case
698** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000699** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000700**
drhf57b3392001-10-08 13:22:32 +0000701** The new table record is initialized and put in pParse->pNewTable.
702** As more of the CREATE TABLE statement is parsed, additional action
703** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000704** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000705** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000706*/
danielk19774adee202004-05-08 08:23:19 +0000707void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000708 Parse *pParse, /* Parser context */
709 Token *pStart, /* The "CREATE" token */
danielk1977cbb18d22004-05-28 11:37:27 +0000710 Token *pName1, /* First part of the name of the table or view */
711 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000712 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000713 int isView, /* True if this is a VIEW */
714 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000715){
drh75897232000-05-29 14:26:00 +0000716 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000717 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000718 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000719 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000720 int iDb; /* Database number to create the table in */
721 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000722
danielk1977cbb18d22004-05-28 11:37:27 +0000723 /* The table or view name to create is passed to this routine via tokens
724 ** pName1 and pName2. If the table name was fully qualified, for example:
725 **
726 ** CREATE TABLE xxx.yyy (...);
727 **
728 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
729 ** the table name is not fully qualified, i.e.:
730 **
731 ** CREATE TABLE yyy(...);
732 **
733 ** Then pName1 is set to "yyy" and pName2 is "".
734 **
735 ** The call below sets the pName pointer to point at the token (pName1 or
736 ** pName2) that stores the unqualified table name. The variable iDb is
737 ** set to the index of the database that the table or view is to be
738 ** created in.
739 */
danielk1977ef2cb632004-05-29 02:37:19 +0000740 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000741 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000742 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000743 /* If creating a temp table, the name may not be qualified */
744 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000745 return;
746 }
danielk197753c0f742005-03-29 03:10:59 +0000747 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000748
749 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000750 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000751 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000752 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000753 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000754 }
drh1d85d932004-02-14 23:05:52 +0000755 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000756#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000757 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000758 {
759 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000760 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000761 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000762 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000763 }
drhe5f9c642003-01-13 23:27:31 +0000764 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000765 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000766 code = SQLITE_CREATE_TEMP_VIEW;
767 }else{
768 code = SQLITE_CREATE_VIEW;
769 }
770 }else{
danielk197753c0f742005-03-29 03:10:59 +0000771 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000772 code = SQLITE_CREATE_TEMP_TABLE;
773 }else{
774 code = SQLITE_CREATE_TABLE;
775 }
776 }
danielk19774adee202004-05-08 08:23:19 +0000777 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000778 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000779 }
780 }
781#endif
drhf57b3392001-10-08 13:22:32 +0000782
drhf57b3392001-10-08 13:22:32 +0000783 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000784 ** index or table name in the same database. Issue an error message if
785 ** it does.
drhf57b3392001-10-08 13:22:32 +0000786 */
danielk19775558a8a2005-01-17 07:53:44 +0000787 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
788 goto begin_table_error;
789 }
danielk19773df6b252004-05-29 10:23:19 +0000790 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
791 if( pTable ){
drhfaa59552005-12-29 23:33:54 +0000792 if( !noErr ){
793 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
794 }
drh23bf66d2004-12-14 03:34:34 +0000795 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000796 }
drh4f26bb62005-09-08 14:17:20 +0000797 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
danielk19774adee202004-05-08 08:23:19 +0000798 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
drh23bf66d2004-12-14 03:34:34 +0000799 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000800 }
801 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000802 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000803 pParse->rc = SQLITE_NOMEM;
804 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000805 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000806 }
drh75897232000-05-29 14:26:00 +0000807 pTable->zName = zName;
drh75897232000-05-29 14:26:00 +0000808 pTable->nCol = 0;
drh7020f652000-06-03 18:06:52 +0000809 pTable->aCol = 0;
drh4a324312001-12-21 14:30:42 +0000810 pTable->iPKey = -1;
drh75897232000-05-29 14:26:00 +0000811 pTable->pIndex = 0;
danielk1977da184232006-01-05 11:34:32 +0000812 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000813 pTable->nRef = 1;
danielk19774adee202004-05-08 08:23:19 +0000814 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000815 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000816
drh4794f732004-11-05 17:17:50 +0000817 /* If this is the magic sqlite_sequence table used by autoincrement,
818 ** then record a pointer to this table in the main database structure
819 ** so that INSERT can find the table easily.
820 */
821#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000822 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000823 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000824 }
825#endif
826
drh17f71932002-02-21 12:01:27 +0000827 /* Begin generating the code that will insert the table record into
828 ** the SQLITE_MASTER table. Note in particular that we must go ahead
829 ** and allocate the record number for the table entry now. Before any
830 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
831 ** indices to be created and the table record must come before the
832 ** indices. Hence, the record number for the table must be allocated
833 ** now.
834 */
danielk19774adee202004-05-08 08:23:19 +0000835 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk197736963fd2005-02-19 08:18:05 +0000836 int lbl;
danielk1977cbb18d22004-05-28 11:37:27 +0000837 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000838
danielk197736963fd2005-02-19 08:18:05 +0000839 /* If the file format and encoding in the database have not been set,
840 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000841 */
danielk197736963fd2005-02-19 08:18:05 +0000842 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
843 lbl = sqlite3VdbeMakeLabel(v);
844 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
drhd946db02005-12-29 19:23:06 +0000845 sqlite3VdbeAddOp(v, OP_Integer, SQLITE_DEFAULT_FILE_FORMAT, 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000846 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
danielk197714db2662006-01-09 16:12:04 +0000847 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000848 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000849 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000850
drh4794f732004-11-05 17:17:50 +0000851 /* This just creates a place-holder record in the sqlite_master table.
852 ** The record created does not contain anything yet. It will be replaced
853 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000854 **
855 ** The rowid for the new entry is left on the top of the stack.
856 ** The rowid value is needed by the code that sqlite3EndTable will
857 ** generate.
drh4794f732004-11-05 17:17:50 +0000858 */
danielk1977a21c6b62005-01-24 10:25:59 +0000859#ifndef SQLITE_OMIT_VIEW
860 if( isView ){
861 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
862 }else
863#endif
864 {
865 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
866 }
danielk1977c00da102006-01-07 13:21:04 +0000867 sqlite3OpenMasterTable(pParse, iDb);
drhf0863fe2005-06-12 21:35:51 +0000868 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000869 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000870 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
871 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000872 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000873 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000874 }
drh23bf66d2004-12-14 03:34:34 +0000875
876 /* Normal (non-error) return. */
877 return;
878
879 /* If an error occurs, we jump here */
880begin_table_error:
881 sqliteFree(zName);
882 return;
drh75897232000-05-29 14:26:00 +0000883}
884
885/*
danielk1977c60e9b82005-01-31 12:42:29 +0000886** This macro is used to compare two strings in a case-insensitive manner.
887** It is slightly faster than calling sqlite3StrICmp() directly, but
888** produces larger code.
889**
890** WARNING: This macro is not compatible with the strcmp() family. It
891** returns true if the two strings are equal, otherwise false.
892*/
893#define STRICMP(x, y) (\
894sqlite3UpperToLower[*(unsigned char *)(x)]== \
895sqlite3UpperToLower[*(unsigned char *)(y)] \
896&& sqlite3StrICmp((x)+1,(y)+1)==0 )
897
898/*
drh75897232000-05-29 14:26:00 +0000899** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000900**
901** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000902** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000903** first to get things going. Then this routine is called for each
904** column.
drh75897232000-05-29 14:26:00 +0000905*/
danielk19774adee202004-05-08 08:23:19 +0000906void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000907 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000908 int i;
drha99db3b2004-06-19 14:49:12 +0000909 char *z;
drhc9b84a12002-06-20 11:36:48 +0000910 Column *pCol;
drh75897232000-05-29 14:26:00 +0000911 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000912 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000913 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000914 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000915 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000916 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000917 sqliteFree(z);
918 return;
919 }
920 }
drh75897232000-05-29 14:26:00 +0000921 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000922 Column *aNew;
923 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000924 if( aNew==0 ){
925 sqliteFree(z);
926 return;
927 }
drh6d4abfb2001-10-22 02:58:08 +0000928 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000929 }
drhc9b84a12002-06-20 11:36:48 +0000930 pCol = &p->aCol[p->nCol];
931 memset(pCol, 0, sizeof(p->aCol[0]));
932 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000933
934 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000935 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
936 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000937 */
danielk19774f057f92004-06-08 00:02:33 +0000938 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000939 p->nCol++;
drh75897232000-05-29 14:26:00 +0000940}
941
942/*
drh382c0242001-10-06 16:33:02 +0000943** This routine is called by the parser while in the middle of
944** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
945** been seen on a column. This routine sets the notNull flag on
946** the column currently under construction.
947*/
danielk19774adee202004-05-08 08:23:19 +0000948void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000949 Table *p;
950 int i;
951 if( (p = pParse->pNewTable)==0 ) return;
952 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000953 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000954}
955
956/*
danielk197752a83fb2005-01-31 12:56:44 +0000957** Scan the column type name zType (length nType) and return the
958** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000959**
960** This routine does a case-independent search of zType for the
961** substrings in the following table. If one of the substrings is
962** found, the corresponding affinity is returned. If zType contains
963** more than one of the substrings, entries toward the top of
964** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000965** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000966**
967** Substring | Affinity
968** --------------------------------
969** 'INT' | SQLITE_AFF_INTEGER
970** 'CHAR' | SQLITE_AFF_TEXT
971** 'CLOB' | SQLITE_AFF_TEXT
972** 'TEXT' | SQLITE_AFF_TEXT
973** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000974** 'REAL' | SQLITE_AFF_REAL
975** 'FLOA' | SQLITE_AFF_REAL
976** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000977**
978** If none of the substrings in the above table are found,
979** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000980*/
drh8a512562005-11-14 22:29:05 +0000981char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000982 u32 h = 0;
983 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000984 const unsigned char *zIn = pType->z;
985 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000986
danielk1977b3dff962005-02-01 01:21:55 +0000987 while( zIn!=zEnd ){
988 h = (h<<8) + sqlite3UpperToLower[*zIn];
989 zIn++;
danielk1977201f7162005-02-01 02:13:29 +0000990 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
991 aff = SQLITE_AFF_TEXT;
992 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
993 aff = SQLITE_AFF_TEXT;
994 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
995 aff = SQLITE_AFF_TEXT;
996 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +0000997 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +0000998 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +0000999#ifndef SQLITE_OMIT_FLOATING_POINT
1000 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1001 && aff==SQLITE_AFF_NUMERIC ){
1002 aff = SQLITE_AFF_REAL;
1003 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1004 && aff==SQLITE_AFF_NUMERIC ){
1005 aff = SQLITE_AFF_REAL;
1006 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1007 && aff==SQLITE_AFF_NUMERIC ){
1008 aff = SQLITE_AFF_REAL;
1009#endif
danielk1977201f7162005-02-01 02:13:29 +00001010 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001011 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001012 break;
danielk197752a83fb2005-01-31 12:56:44 +00001013 }
1014 }
danielk1977b3dff962005-02-01 01:21:55 +00001015
1016 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001017}
1018
1019/*
drh382c0242001-10-06 16:33:02 +00001020** This routine is called by the parser while in the middle of
1021** parsing a CREATE TABLE statement. The pFirst token is the first
1022** token in the sequence of tokens that describe the type of the
1023** column currently under construction. pLast is the last token
1024** in the sequence. Use this information to construct a string
1025** that contains the typename of the column and store that string
1026** in zType.
1027*/
drh487e2622005-06-25 18:42:14 +00001028void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001029 Table *p;
drh487e2622005-06-25 18:42:14 +00001030 int i;
drhc9b84a12002-06-20 11:36:48 +00001031 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001032
drh382c0242001-10-06 16:33:02 +00001033 if( (p = pParse->pNewTable)==0 ) return;
1034 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001035 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001036 pCol = &p->aCol[i];
drhd8919672005-09-10 15:35:06 +00001037 sqliteFree(pCol->zType);
drh487e2622005-06-25 18:42:14 +00001038 pCol->zType = sqlite3NameFromToken(pType);
drh8a512562005-11-14 22:29:05 +00001039 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001040}
1041
1042/*
danielk19777977a172004-11-09 12:44:37 +00001043** The expression is the default value for the most recently added column
1044** of the table currently under construction.
1045**
1046** Default value expressions must be constant. Raise an exception if this
1047** is not the case.
drhd9b02572001-04-15 00:37:09 +00001048**
1049** This routine is called by the parser while in the middle of
1050** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001051*/
danielk19777977a172004-11-09 12:44:37 +00001052void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001053 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001054 Column *pCol;
drh42b9d7c2005-08-13 00:56:27 +00001055 if( (p = pParse->pNewTable)!=0 ){
1056 pCol = &(p->aCol[p->nCol-1]);
1057 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1058 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1059 pCol->zName);
1060 }else{
1061 sqlite3ExprDelete(pCol->pDflt);
1062 pCol->pDflt = sqlite3ExprDup(pExpr);
1063 }
danielk19777977a172004-11-09 12:44:37 +00001064 }
1065 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +00001066}
1067
1068/*
drh4a324312001-12-21 14:30:42 +00001069** Designate the PRIMARY KEY for the table. pList is a list of names
1070** of columns that form the primary key. If pList is NULL, then the
1071** most recently added column of the table is the primary key.
1072**
1073** A table can have at most one primary key. If the table already has
1074** a primary key (and this is the second primary key) then create an
1075** error.
1076**
1077** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001078** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001079** field of the table under construction to be the index of the
1080** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1081** no INTEGER PRIMARY KEY.
1082**
1083** If the key is not an INTEGER PRIMARY KEY, then create a unique
1084** index for the key. No index is created for INTEGER PRIMARY KEYs.
1085*/
drh205f48e2004-11-05 00:43:11 +00001086void sqlite3AddPrimaryKey(
1087 Parse *pParse, /* Parsing context */
1088 ExprList *pList, /* List of field names to be indexed */
1089 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001090 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1091 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001092){
drh4a324312001-12-21 14:30:42 +00001093 Table *pTab = pParse->pNewTable;
1094 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001095 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +00001096 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001097 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001098 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001099 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001100 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001101 }
1102 pTab->hasPrimKey = 1;
1103 if( pList==0 ){
1104 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001105 pTab->aCol[iCol].isPrimKey = 1;
1106 }else{
danielk19770202b292004-06-09 09:55:16 +00001107 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001108 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001109 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1110 break;
1111 }
drh78100cc2003-08-23 22:40:53 +00001112 }
drh6e4fc2c2005-09-15 21:24:51 +00001113 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001114 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001115 }
drh4a324312001-12-21 14:30:42 +00001116 }
danielk19770202b292004-06-09 09:55:16 +00001117 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001118 }
1119 if( iCol>=0 && iCol<pTab->nCol ){
1120 zType = pTab->aCol[iCol].zType;
1121 }
drhfdd6e852005-12-16 01:06:16 +00001122 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1123 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001124 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001125 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001126 pTab->autoInc = autoInc;
1127 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001128#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001129 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1130 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001131#endif
drh4a324312001-12-21 14:30:42 +00001132 }else{
drh4d91a702006-01-04 15:54:36 +00001133 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001134 pList = 0;
drh4a324312001-12-21 14:30:42 +00001135 }
drhe0194f22003-02-26 13:52:51 +00001136
1137primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001138 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001139 return;
drh4a324312001-12-21 14:30:42 +00001140}
1141
1142/*
drhffe07b22005-11-03 00:41:17 +00001143** Add a new CHECK constraint to the table currently under construction.
1144*/
1145void sqlite3AddCheckConstraint(
1146 Parse *pParse, /* Parsing context */
1147 Expr *pCheckExpr /* The check expression */
1148){
1149#ifndef SQLITE_OMIT_CHECK
1150 Table *pTab = pParse->pNewTable;
1151 if( pTab ){
1152 /* The CHECK expression must be duplicated so that tokens refer
1153 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1154 ** statement */
1155 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
1156 }
1157#endif
1158 sqlite3ExprDelete(pCheckExpr);
1159}
1160
1161/*
drhd3d39e92004-05-20 22:16:29 +00001162** Set the collation function of the most recently parsed table column
1163** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001164*/
drhd3d39e92004-05-20 22:16:29 +00001165void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001166 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001167 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001168
drhd3d39e92004-05-20 22:16:29 +00001169 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001170 i = p->nCol-1;
1171
danielk1977b3bf5562006-01-10 17:58:23 +00001172 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1173 Index *pIdx;
1174 p->aCol[i].zColl = sqlite3StrNDup(zType, nType);
1175
1176 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1177 ** then an index may have been created on this column before the
1178 ** collation type was added. Correct this if it is the case.
1179 */
1180 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1181 assert( pIdx->nColumn==1 );
1182 if( pIdx->aiColumn[0]==i ){
1183 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001184 }
1185 }
1186 }
danielk19777cedc8d2004-06-10 10:50:08 +00001187}
1188
danielk1977466be562004-06-10 02:16:01 +00001189/*
1190** This function returns the collation sequence for database native text
1191** encoding identified by the string zName, length nName.
1192**
1193** If the requested collation sequence is not available, or not available
1194** in the database native encoding, the collation factory is invoked to
1195** request it. If the collation factory does not supply such a sequence,
1196** and the sequence is available in another text encoding, then that is
1197** returned instead.
1198**
1199** If no versions of the requested collations sequence are available, or
1200** another error occurs, NULL is returned and an error message written into
1201** pParse.
1202*/
danielk19770202b292004-06-09 09:55:16 +00001203CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001204 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001205 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001206 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001207 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001208
danielk1977b3bf5562006-01-10 17:58:23 +00001209 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001210 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001211 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1212 if( !pColl ){
1213 if( nName<0 ){
1214 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001215 }
danielk19774dade032005-05-25 10:45:10 +00001216 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1217 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001218 }
1219 }
1220
danielk19770202b292004-06-09 09:55:16 +00001221 return pColl;
1222}
1223
1224
drh8e2ca022002-06-17 17:07:19 +00001225/*
drh3f7d4e42004-07-24 14:35:58 +00001226** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001227**
1228** The schema cookie is used to determine when the schema for the
1229** database changes. After each schema change, the cookie value
1230** changes. When a process first reads the schema it records the
1231** cookie. Thereafter, whenever it goes to access the database,
1232** it checks the cookie to make sure the schema has not changed
1233** since it was last read.
1234**
1235** This plan is not completely bullet-proof. It is possible for
1236** the schema to change multiple times and for the cookie to be
1237** set back to prior value. But schema changes are infrequent
1238** and the probability of hitting the same cookie value is only
1239** 1 chance in 2^32. So we're safe enough.
1240*/
drh9bb575f2004-09-06 17:24:11 +00001241void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
danielk1977da184232006-01-05 11:34:32 +00001242 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001243 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001244}
1245
1246/*
drh969fa7c2002-02-18 18:30:32 +00001247** Measure the number of characters needed to output the given
1248** identifier. The number returned includes any quotes used
1249** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001250**
1251** The estimate is conservative. It might be larger that what is
1252** really needed.
drh969fa7c2002-02-18 18:30:32 +00001253*/
1254static int identLength(const char *z){
1255 int n;
drh17f71932002-02-21 12:01:27 +00001256 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001257 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001258 }
drh234c39d2004-07-24 03:30:47 +00001259 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001260}
1261
1262/*
1263** Write an identifier onto the end of the given string. Add
1264** quote characters as needed.
1265*/
drh4c755c02004-08-08 20:22:17 +00001266static void identPut(char *z, int *pIdx, char *zSignedIdent){
1267 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001268 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001269 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001270 for(j=0; zIdent[j]; j++){
1271 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1272 }
1273 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001274 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001275 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001276 for(j=0; zIdent[j]; j++){
1277 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001278 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001279 }
drh234c39d2004-07-24 03:30:47 +00001280 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001281 z[i] = 0;
1282 *pIdx = i;
1283}
1284
1285/*
1286** Generate a CREATE TABLE statement appropriate for the given
1287** table. Memory to hold the text of the statement is obtained
1288** from sqliteMalloc() and must be freed by the calling function.
1289*/
danielk1977da184232006-01-05 11:34:32 +00001290static char *createTableStmt(Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001291 int i, k, n;
1292 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001293 char *zSep, *zSep2, *zEnd, *z;
1294 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001295 n = 0;
drh234c39d2004-07-24 03:30:47 +00001296 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1297 n += identLength(pCol->zName);
1298 z = pCol->zType;
1299 if( z ){
1300 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001301 }
drh969fa7c2002-02-18 18:30:32 +00001302 }
1303 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001304 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001305 zSep = "";
1306 zSep2 = ",";
1307 zEnd = ")";
1308 }else{
1309 zSep = "\n ";
1310 zSep2 = ",\n ";
1311 zEnd = "\n)";
1312 }
drhe0bc4042002-06-25 01:09:11 +00001313 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001314 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001315 if( zStmt==0 ) return 0;
danielk1977da184232006-01-05 11:34:32 +00001316 strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001317 k = strlen(zStmt);
1318 identPut(zStmt, &k, p->zName);
1319 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001320 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001321 strcpy(&zStmt[k], zSep);
1322 k += strlen(&zStmt[k]);
1323 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001324 identPut(zStmt, &k, pCol->zName);
1325 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001326 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001327 strcpy(&zStmt[k], z);
1328 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001329 }
drh969fa7c2002-02-18 18:30:32 +00001330 }
1331 strcpy(&zStmt[k], zEnd);
1332 return zStmt;
1333}
1334
1335/*
drh75897232000-05-29 14:26:00 +00001336** This routine is called to report the final ")" that terminates
1337** a CREATE TABLE statement.
1338**
drhf57b3392001-10-08 13:22:32 +00001339** The table structure that other action routines have been building
1340** is added to the internal hash tables, assuming no errors have
1341** occurred.
drh75897232000-05-29 14:26:00 +00001342**
drh1d85d932004-02-14 23:05:52 +00001343** An entry for the table is made in the master table on disk, unless
1344** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001345** it means we are reading the sqlite_master table because we just
1346** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001347** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001348** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001349**
1350** If the pSelect argument is not NULL, it means that this routine
1351** was called to create a table generated from a
1352** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1353** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001354*/
danielk197719a8e7e2005-03-17 05:03:38 +00001355void sqlite3EndTable(
1356 Parse *pParse, /* Parse context */
1357 Token *pCons, /* The ',' token after the last column defn. */
1358 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1359 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1360){
drh75897232000-05-29 14:26:00 +00001361 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001362 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001363 int iDb;
drh75897232000-05-29 14:26:00 +00001364
danielk1977e501b892006-01-09 06:29:47 +00001365 if( (pEnd==0 && pSelect==0) ||
1366 pParse->nErr || sqlite3ThreadData()->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001367 return;
1368 }
drh28037572000-08-02 13:47:41 +00001369 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001370 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001371
danielk1977517eb642004-06-07 10:00:31 +00001372 assert( !db->init.busy || !pSelect );
1373
danielk1977da184232006-01-05 11:34:32 +00001374 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1375
drhffe07b22005-11-03 00:41:17 +00001376#ifndef SQLITE_OMIT_CHECK
1377 /* Resolve names in all CHECK constraint expressions.
1378 */
1379 if( p->pCheck ){
1380 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1381 NameContext sNC; /* Name context for pParse->pNewTable */
1382
1383 memset(&sNC, 0, sizeof(sNC));
1384 memset(&sSrc, 0, sizeof(sSrc));
1385 sSrc.nSrc = 1;
1386 sSrc.a[0].zName = p->zName;
1387 sSrc.a[0].pTab = p;
1388 sSrc.a[0].iCursor = -1;
1389 sNC.pParse = pParse;
1390 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001391 sNC.isCheck = 1;
drhffe07b22005-11-03 00:41:17 +00001392 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1393 return;
1394 }
1395 }
1396#endif /* !defined(SQLITE_OMIT_CHECK) */
1397
drh1d85d932004-02-14 23:05:52 +00001398 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001399 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1400 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001401 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001402 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001403 */
drh1d85d932004-02-14 23:05:52 +00001404 if( db->init.busy ){
1405 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001406 }
1407
drhe3c41372001-09-17 20:25:58 +00001408 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001409 ** in the SQLITE_MASTER table of the database. The record number
1410 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001411 **
drhe0bc4042002-06-25 01:09:11 +00001412 ** If this is a TEMPORARY table, write the entry into the auxiliary
1413 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001414 */
drh1d85d932004-02-14 23:05:52 +00001415 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001416 int n;
drhd8bc7082000-06-07 23:51:50 +00001417 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001418 char *zType; /* "view" or "table" */
1419 char *zType2; /* "VIEW" or "TABLE" */
1420 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001421
danielk19774adee202004-05-08 08:23:19 +00001422 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001423 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001424
danielk1977e6efa742004-11-10 11:55:10 +00001425 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1426
drh4794f732004-11-05 17:17:50 +00001427 /* Create the rootpage for the new table and push it onto the stack.
1428 ** A view has no rootpage, so just push a zero onto the stack for
1429 ** views. Initialize zType at the same time.
1430 */
drh4ff6dfa2002-03-03 23:06:00 +00001431 if( p->pSelect==0 ){
1432 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001433 zType = "table";
1434 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001435#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001436 }else{
1437 /* A view */
drh4794f732004-11-05 17:17:50 +00001438 zType = "view";
1439 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001440#endif
drh4ff6dfa2002-03-03 23:06:00 +00001441 }
danielk1977517eb642004-06-07 10:00:31 +00001442
danielk1977517eb642004-06-07 10:00:31 +00001443 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1444 ** statement to populate the new table. The root-page number for the
1445 ** new table is on the top of the vdbe stack.
1446 **
1447 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1448 ** suitable state to query for the column names and types to be used
1449 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001450 **
1451 ** A shared-cache write-lock is not required to write to the new table,
1452 ** as a schema-lock must have already been obtained to create it. Since
1453 ** a schema-lock excludes all other database users, the write-lock would
1454 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001455 */
1456 if( pSelect ){
1457 Table *pSelTab;
1458 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
danielk1977da184232006-01-05 11:34:32 +00001459 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977517eb642004-06-07 10:00:31 +00001460 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1461 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001462 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001463 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1464 if( pParse->nErr==0 ){
1465 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1466 if( pSelTab==0 ) return;
1467 assert( p->aCol==0 );
1468 p->nCol = pSelTab->nCol;
1469 p->aCol = pSelTab->aCol;
1470 pSelTab->nCol = 0;
1471 pSelTab->aCol = 0;
1472 sqlite3DeleteTable(0, pSelTab);
1473 }
1474 }
drh4794f732004-11-05 17:17:50 +00001475
drh4794f732004-11-05 17:17:50 +00001476 /* Compute the complete text of the CREATE statement */
1477 if( pSelect ){
danielk1977da184232006-01-05 11:34:32 +00001478 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001479 }else{
drh97903fe2005-05-24 20:19:57 +00001480 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001481 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1482 }
1483
1484 /* A slot for the record has already been allocated in the
1485 ** SQLITE_MASTER table. We just need to update that slot with all
1486 ** the information we've collected. The rowid for the preallocated
1487 ** slot is the 2nd item on the stack. The top of the stack is the
1488 ** root page for the new table (or a 0 if this is a view).
1489 */
1490 sqlite3NestedParse(pParse,
1491 "UPDATE %Q.%s "
1492 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1493 "WHERE rowid=#1",
danielk1977da184232006-01-05 11:34:32 +00001494 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001495 zType,
1496 p->zName,
1497 p->zName,
1498 zStmt
1499 );
1500 sqliteFree(zStmt);
danielk1977da184232006-01-05 11:34:32 +00001501 sqlite3ChangeCookie(db, v, iDb);
drh2958a4e2004-11-12 03:56:15 +00001502
1503#ifndef SQLITE_OMIT_AUTOINCREMENT
1504 /* Check to see if we need to create an sqlite_sequence table for
1505 ** keeping track of autoincrement keys.
1506 */
1507 if( p->autoInc ){
danielk1977da184232006-01-05 11:34:32 +00001508 Db *pDb = &db->aDb[iDb];
1509 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001510 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001511 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1512 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001513 );
1514 }
1515 }
1516#endif
drh4794f732004-11-05 17:17:50 +00001517
1518 /* Reparse everything to update our internal data structures */
danielk1977da184232006-01-05 11:34:32 +00001519 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
drh234c39d2004-07-24 03:30:47 +00001520 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001521 }
drh17e9e292003-02-01 13:53:28 +00001522
drh2958a4e2004-11-12 03:56:15 +00001523
drh17e9e292003-02-01 13:53:28 +00001524 /* Add the table to the in-memory representation of the database.
1525 */
drh234c39d2004-07-24 03:30:47 +00001526 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001527 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001528 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001529 Schema *pSchema = p->pSchema;
danielk1977da184232006-01-05 11:34:32 +00001530 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001531 if( pOld ){
1532 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1533 return;
1534 }
danielk1977576ec6b2005-01-21 11:55:25 +00001535#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001536 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1537 int nTo = strlen(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001538 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1539 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001540 }
danielk1977576ec6b2005-01-21 11:55:25 +00001541#endif
drh17e9e292003-02-01 13:53:28 +00001542 pParse->pNewTable = 0;
1543 db->nTable++;
1544 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001545
1546#ifndef SQLITE_OMIT_ALTERTABLE
1547 if( !p->pSelect ){
1548 assert( !pSelect && pCons && pEnd );
1549 if( pCons->z==0 ) pCons = pEnd;
1550 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1551 }
1552#endif
drh17e9e292003-02-01 13:53:28 +00001553 }
drh75897232000-05-29 14:26:00 +00001554}
1555
drhb7f91642004-10-31 02:22:47 +00001556#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001557/*
drha76b5df2002-02-23 02:32:10 +00001558** The parser calls this routine in order to create a new VIEW
1559*/
danielk19774adee202004-05-08 08:23:19 +00001560void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001561 Parse *pParse, /* The parsing context */
1562 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001563 Token *pName1, /* The token that holds the name of the view */
1564 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001565 Select *pSelect, /* A SELECT statement that will become the new view */
1566 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001567){
drha76b5df2002-02-23 02:32:10 +00001568 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001569 int n;
drh4c755c02004-08-08 20:22:17 +00001570 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001571 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001572 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001573 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001574 int iDb;
drha76b5df2002-02-23 02:32:10 +00001575
drh7c3d64f2005-06-06 15:32:08 +00001576 if( pParse->nVar>0 ){
1577 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1578 sqlite3SelectDelete(pSelect);
1579 return;
1580 }
drhfaa59552005-12-29 23:33:54 +00001581 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1, 0);
drha76b5df2002-02-23 02:32:10 +00001582 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001583 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001584 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001585 return;
1586 }
danielk1977ef2cb632004-05-29 02:37:19 +00001587 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977da184232006-01-05 11:34:32 +00001588 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1589 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001590 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001591 ){
danielk19774adee202004-05-08 08:23:19 +00001592 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001593 return;
1594 }
drh174b6192002-12-03 02:22:52 +00001595
drh4b59ab52002-08-24 18:24:51 +00001596 /* Make a copy of the entire SELECT statement that defines the view.
1597 ** This will force all the Expr.token.z values to be dynamically
1598 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001599 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001600 */
danielk19774adee202004-05-08 08:23:19 +00001601 p->pSelect = sqlite3SelectDup(pSelect);
1602 sqlite3SelectDelete(pSelect);
danielk1977e501b892006-01-09 06:29:47 +00001603 if( sqlite3ThreadData()->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001604 return;
1605 }
drh1d85d932004-02-14 23:05:52 +00001606 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001607 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001608 }
drh4b59ab52002-08-24 18:24:51 +00001609
1610 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1611 ** the end.
1612 */
drha76b5df2002-02-23 02:32:10 +00001613 sEnd = pParse->sLastToken;
1614 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1615 sEnd.z += sEnd.n;
1616 }
1617 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001618 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001619 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001620 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1621 sEnd.z = &z[n-1];
1622 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001623
danielk19774adee202004-05-08 08:23:19 +00001624 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001625 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001626 return;
drh417be792002-03-03 18:59:40 +00001627}
drhb7f91642004-10-31 02:22:47 +00001628#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001629
drhb7f91642004-10-31 02:22:47 +00001630#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001631/*
1632** The Table structure pTable is really a VIEW. Fill in the names of
1633** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001634** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001635*/
danielk19774adee202004-05-08 08:23:19 +00001636int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001637 Table *pSelTab; /* A fake table from which we get the result set */
1638 Select *pSel; /* Copy of the SELECT that implements the view */
1639 int nErr = 0; /* Number of errors encountered */
1640 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001641
1642 assert( pTable );
1643
1644 /* A positive nCol means the columns names for this view are
1645 ** already known.
1646 */
1647 if( pTable->nCol>0 ) return 0;
1648
1649 /* A negative nCol is a special marker meaning that we are currently
1650 ** trying to compute the column names. If we enter this routine with
1651 ** a negative nCol, it means two or more views form a loop, like this:
1652 **
1653 ** CREATE VIEW one AS SELECT * FROM two;
1654 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001655 **
1656 ** Actually, this error is caught previously and so the following test
1657 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001658 */
drh85c23c62005-08-20 03:03:04 +00001659#if 0
drh417be792002-03-03 18:59:40 +00001660 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001661 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001662 return 1;
1663 }
drh85c23c62005-08-20 03:03:04 +00001664#endif
1665 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001666
1667 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001668 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1669 ** "*" elements in the results set of the view and will assign cursors
1670 ** to the elements of the FROM clause. But we do not want these changes
1671 ** to be permanent. So the computation is done on a copy of the SELECT
1672 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001673 */
drh9b3187e2005-01-18 14:45:47 +00001674 assert( pTable->pSelect );
1675 pSel = sqlite3SelectDup(pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001676 if( pSel ){
1677 n = pParse->nTab;
1678 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1679 pTable->nCol = -1;
1680 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1681 pParse->nTab = n;
1682 if( pSelTab ){
1683 assert( pTable->aCol==0 );
1684 pTable->nCol = pSelTab->nCol;
1685 pTable->aCol = pSelTab->aCol;
1686 pSelTab->nCol = 0;
1687 pSelTab->aCol = 0;
1688 sqlite3DeleteTable(0, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001689 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001690 }else{
1691 pTable->nCol = 0;
1692 nErr++;
1693 }
1694 sqlite3SelectDelete(pSel);
1695 } else {
drh417be792002-03-03 18:59:40 +00001696 nErr++;
1697 }
drh417be792002-03-03 18:59:40 +00001698 return nErr;
1699}
drhb7f91642004-10-31 02:22:47 +00001700#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001701
drhb7f91642004-10-31 02:22:47 +00001702#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001703/*
drh8bf8dc92003-05-17 17:35:10 +00001704** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001705*/
drh9bb575f2004-09-06 17:24:11 +00001706static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001707 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001708 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001709 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001710 Table *pTab = sqliteHashData(i);
1711 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001712 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001713 }
1714 }
drh8bf8dc92003-05-17 17:35:10 +00001715 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001716}
drhb7f91642004-10-31 02:22:47 +00001717#else
1718# define sqliteViewResetAll(A,B)
1719#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001720
drh75897232000-05-29 14:26:00 +00001721/*
danielk1977a0bf2652004-11-04 14:30:04 +00001722** This function is called by the VDBE to adjust the internal schema
1723** used by SQLite when the btree layer moves a table root page. The
1724** root-page of a table or index in database iDb has changed from iFrom
1725** to iTo.
1726*/
1727#ifndef SQLITE_OMIT_AUTOVACUUM
1728void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1729 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001730 Hash *pHash;
1731
1732 pHash = &pDb->pSchema->tblHash;
1733 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001734 Table *pTab = sqliteHashData(pElem);
1735 if( pTab->tnum==iFrom ){
1736 pTab->tnum = iTo;
1737 return;
1738 }
1739 }
danielk1977da184232006-01-05 11:34:32 +00001740 pHash = &pDb->pSchema->idxHash;
1741 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001742 Index *pIdx = sqliteHashData(pElem);
1743 if( pIdx->tnum==iFrom ){
1744 pIdx->tnum = iTo;
1745 return;
1746 }
1747 }
1748 assert(0);
1749}
1750#endif
1751
1752/*
1753** Write code to erase the table with root-page iTable from database iDb.
1754** Also write code to modify the sqlite_master table and internal schema
1755** if a root-page of another table is moved by the btree-layer whilst
1756** erasing iTable (this can happen with an auto-vacuum database).
1757*/
drh4e0cff62004-11-05 05:10:28 +00001758static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1759 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001760 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1761#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001762 /* OP_Destroy pushes an integer onto the stack. If this integer
1763 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001764 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001765 ** reflect this.
1766 **
1767 ** The "#0" in the SQL is a special constant that means whatever value
1768 ** is on the top of the stack. See sqlite3RegisterExpr().
1769 */
danielk197763e3e9f2004-11-05 09:19:27 +00001770 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001771 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001772 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001773#endif
1774}
1775
1776/*
1777** Write VDBE code to erase table pTab and all associated indices on disk.
1778** Code to update the sqlite_master tables and internal schema definitions
1779** in case a root-page belonging to another table is moved by the btree layer
1780** is also added (this can happen with an auto-vacuum database).
1781*/
drh4e0cff62004-11-05 05:10:28 +00001782static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001783#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001784 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001785 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1786 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001787 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001788 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001789 }
1790#else
1791 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1792 ** is not defined), then it is important to call OP_Destroy on the
1793 ** table and index root-pages in order, starting with the numerically
1794 ** largest root-page number. This guarantees that none of the root-pages
1795 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1796 ** following were coded:
1797 **
1798 ** OP_Destroy 4 0
1799 ** ...
1800 ** OP_Destroy 5 0
1801 **
1802 ** and root page 5 happened to be the largest root-page number in the
1803 ** database, then root page 5 would be moved to page 4 by the
1804 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1805 ** a free-list page.
1806 */
1807 int iTab = pTab->tnum;
1808 int iDestroyed = 0;
1809
1810 while( 1 ){
1811 Index *pIdx;
1812 int iLargest = 0;
1813
1814 if( iDestroyed==0 || iTab<iDestroyed ){
1815 iLargest = iTab;
1816 }
1817 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1818 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001819 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001820 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1821 iLargest = iIdx;
1822 }
1823 }
danielk1977da184232006-01-05 11:34:32 +00001824 if( iLargest==0 ){
1825 return;
1826 }else{
1827 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1828 destroyRootPage(pParse, iLargest, iDb);
1829 iDestroyed = iLargest;
1830 }
danielk1977a0bf2652004-11-04 14:30:04 +00001831 }
1832#endif
1833}
1834
1835/*
drh75897232000-05-29 14:26:00 +00001836** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001837** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001838*/
drha0733842005-12-29 01:11:36 +00001839void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001840 Table *pTab;
drh75897232000-05-29 14:26:00 +00001841 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001842 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001843 int iDb;
drh75897232000-05-29 14:26:00 +00001844
danielk1977e501b892006-01-09 06:29:47 +00001845 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) goto exit_drop_table;
danielk1977a8858102004-05-28 12:11:21 +00001846 assert( pName->nSrc==1 );
1847 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1848
drha0733842005-12-29 01:11:36 +00001849 if( pTab==0 ){
1850 if( noErr ){
1851 sqlite3ErrorClear(pParse);
1852 }
1853 goto exit_drop_table;
1854 }
danielk1977da184232006-01-05 11:34:32 +00001855 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001856 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001857#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001858 {
1859 int code;
danielk1977da184232006-01-05 11:34:32 +00001860 const char *zTab = SCHEMA_TABLE(iDb);
1861 const char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001862 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001863 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001864 }
drhe5f9c642003-01-13 23:27:31 +00001865 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001866 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001867 code = SQLITE_DROP_TEMP_VIEW;
1868 }else{
1869 code = SQLITE_DROP_VIEW;
1870 }
1871 }else{
danielk197753c0f742005-03-29 03:10:59 +00001872 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001873 code = SQLITE_DROP_TEMP_TABLE;
1874 }else{
1875 code = SQLITE_DROP_TABLE;
1876 }
1877 }
danielk1977a8858102004-05-28 12:11:21 +00001878 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1879 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001880 }
danielk1977a8858102004-05-28 12:11:21 +00001881 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1882 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001883 }
drhe5f9c642003-01-13 23:27:31 +00001884 }
1885#endif
danielk1977da184232006-01-05 11:34:32 +00001886 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001887 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001888 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001889 }
danielk1977576ec6b2005-01-21 11:55:25 +00001890
1891#ifndef SQLITE_OMIT_VIEW
1892 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1893 ** on a table.
1894 */
danielk1977a8858102004-05-28 12:11:21 +00001895 if( isView && pTab->pSelect==0 ){
1896 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1897 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001898 }
danielk1977a8858102004-05-28 12:11:21 +00001899 if( !isView && pTab->pSelect ){
1900 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1901 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001902 }
danielk1977576ec6b2005-01-21 11:55:25 +00001903#endif
drh75897232000-05-29 14:26:00 +00001904
drh1ccde152000-06-17 13:12:39 +00001905 /* Generate code to remove the table from the master table
1906 ** on disk.
1907 */
danielk19774adee202004-05-08 08:23:19 +00001908 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001909 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001910 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001911 Db *pDb = &db->aDb[iDb];
1912 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001913
danielk19778e227872004-06-07 07:52:17 +00001914 /* Drop all triggers associated with the table being dropped. Code
1915 ** is generated to remove entries from sqlite_master and/or
1916 ** sqlite_temp_master if required.
1917 */
danielk1977a8858102004-05-28 12:11:21 +00001918 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001919 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00001920 assert( pTrigger->pSchema==pTab->pSchema ||
1921 pTrigger->pSchema==db->aDb[1].pSchema );
danielk19774adee202004-05-08 08:23:19 +00001922 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001923 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001924 }
drh8bf8dc92003-05-17 17:35:10 +00001925
danielk19774d36b812004-11-19 07:07:30 +00001926#ifndef SQLITE_OMIT_AUTOINCREMENT
1927 /* Remove any entries of the sqlite_sequence table associated with
1928 ** the table being dropped. This is done before the table is dropped
1929 ** at the btree level, in case the sqlite_sequence table needs to
1930 ** move as a result of the drop (can happen in auto-vacuum mode).
1931 */
1932 if( pTab->autoInc ){
1933 sqlite3NestedParse(pParse,
1934 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1935 pDb->zName, pTab->zName
1936 );
1937 }
1938#endif
1939
danielk19778e227872004-06-07 07:52:17 +00001940 /* Drop all SQLITE_MASTER table and index entries that refer to the
1941 ** table. The program name loops through the master table and deletes
1942 ** every row that refers to a table of the same name as the one being
1943 ** dropped. Triggers are handled seperately because a trigger can be
1944 ** created in the temp database that refers to a table in another
1945 ** database.
1946 */
drhf1974842004-11-05 03:56:00 +00001947 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001948 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001949 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001950 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001951 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001952 }
drh2958a4e2004-11-12 03:56:15 +00001953
danielk1977a21c6b62005-01-24 10:25:59 +00001954 /* Remove the table entry from SQLite's internal schema and modify
1955 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001956 */
1957 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00001958 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00001959 }
drhd24cc422003-03-27 12:51:24 +00001960 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001961
1962exit_drop_table:
1963 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001964}
1965
1966/*
drhc2eef3b2002-08-31 18:53:06 +00001967** This routine is called to create a new foreign key on the table
1968** currently under construction. pFromCol determines which columns
1969** in the current table point to the foreign key. If pFromCol==0 then
1970** connect the key to the last column inserted. pTo is the name of
1971** the table referred to. pToCol is a list of tables in the other
1972** pTo table that the foreign key points to. flags contains all
1973** information about the conflict resolution algorithms specified
1974** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1975**
1976** An FKey structure is created and added to the table currently
1977** under construction in the pParse->pNewTable field. The new FKey
1978** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001979** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001980**
1981** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001982** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001983*/
danielk19774adee202004-05-08 08:23:19 +00001984void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001985 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001986 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001987 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001988 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001989 int flags /* Conflict resolution algorithms. */
1990){
drhb7f91642004-10-31 02:22:47 +00001991#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001992 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001993 Table *p = pParse->pNewTable;
1994 int nByte;
1995 int i;
1996 int nCol;
1997 char *z;
drhc2eef3b2002-08-31 18:53:06 +00001998
1999 assert( pTo!=0 );
2000 if( p==0 || pParse->nErr ) goto fk_end;
2001 if( pFromCol==0 ){
2002 int iCol = p->nCol-1;
2003 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002004 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002005 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002006 " should reference only one column of table %T",
2007 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002008 goto fk_end;
2009 }
2010 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002011 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002012 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002013 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002014 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002015 goto fk_end;
2016 }else{
danielk19770202b292004-06-09 09:55:16 +00002017 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002018 }
2019 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2020 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002021 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00002022 nByte += strlen(pToCol->a[i].zName) + 1;
2023 }
2024 }
2025 pFKey = sqliteMalloc( nByte );
2026 if( pFKey==0 ) goto fk_end;
2027 pFKey->pFrom = p;
2028 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002029 z = (char*)&pFKey[1];
2030 pFKey->aCol = (struct sColMap*)z;
2031 z += sizeof(struct sColMap)*nCol;
2032 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002033 memcpy(z, pTo->z, pTo->n);
2034 z[pTo->n] = 0;
2035 z += pTo->n+1;
2036 pFKey->pNextTo = 0;
2037 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002038 if( pFromCol==0 ){
2039 pFKey->aCol[0].iFrom = p->nCol-1;
2040 }else{
2041 for(i=0; i<nCol; i++){
2042 int j;
2043 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002044 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002045 pFKey->aCol[i].iFrom = j;
2046 break;
2047 }
2048 }
2049 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002050 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002051 "unknown column \"%s\" in foreign key definition",
2052 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002053 goto fk_end;
2054 }
2055 }
2056 }
2057 if( pToCol ){
2058 for(i=0; i<nCol; i++){
2059 int n = strlen(pToCol->a[i].zName);
2060 pFKey->aCol[i].zCol = z;
2061 memcpy(z, pToCol->a[i].zName, n);
2062 z[n] = 0;
2063 z += n+1;
2064 }
2065 }
2066 pFKey->isDeferred = 0;
2067 pFKey->deleteConf = flags & 0xff;
2068 pFKey->updateConf = (flags >> 8 ) & 0xff;
2069 pFKey->insertConf = (flags >> 16 ) & 0xff;
2070
2071 /* Link the foreign key to the table as the last step.
2072 */
2073 p->pFKey = pFKey;
2074 pFKey = 0;
2075
2076fk_end:
2077 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00002078#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00002079 sqlite3ExprListDelete(pFromCol);
2080 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002081}
2082
2083/*
2084** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2085** clause is seen as part of a foreign key definition. The isDeferred
2086** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2087** The behavior of the most recently created foreign key is adjusted
2088** accordingly.
2089*/
danielk19774adee202004-05-08 08:23:19 +00002090void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002091#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002092 Table *pTab;
2093 FKey *pFKey;
2094 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2095 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002096#endif
drhc2eef3b2002-08-31 18:53:06 +00002097}
2098
2099/*
drh063336a2004-11-05 20:58:39 +00002100** Generate code that will erase and refill index *pIdx. This is
2101** used to initialize a newly created index or to recompute the
2102** content of an index in response to a REINDEX command.
2103**
2104** if memRootPage is not negative, it means that the index is newly
2105** created. The memory cell specified by memRootPage contains the
2106** root page number of the index. If memRootPage is negative, then
2107** the index already exists and must be cleared before being refilled and
2108** the root page number of the index is taken from pIndex->tnum.
2109*/
2110static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2111 Table *pTab = pIndex->pTable; /* The table that is indexed */
2112 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2113 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2114 int addr1; /* Address of top of loop */
2115 int tnum; /* Root page of index */
2116 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002117 KeyInfo *pKey; /* KeyInfo for index */
danielk1977da184232006-01-05 11:34:32 +00002118 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002119
danielk19771d54df82004-11-23 15:41:16 +00002120#ifndef SQLITE_OMIT_AUTHORIZATION
2121 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
danielk1977da184232006-01-05 11:34:32 +00002122 pParse->db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002123 return;
2124 }
2125#endif
2126
danielk1977c00da102006-01-07 13:21:04 +00002127 /* Require a write-lock on the table to perform this operation */
2128 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2129
drh063336a2004-11-05 20:58:39 +00002130 v = sqlite3GetVdbe(pParse);
2131 if( v==0 ) return;
2132 if( memRootPage>=0 ){
2133 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2134 tnum = 0;
2135 }else{
2136 tnum = pIndex->tnum;
danielk1977da184232006-01-05 11:34:32 +00002137 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002138 }
danielk1977da184232006-01-05 11:34:32 +00002139 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977b3bf5562006-01-10 17:58:23 +00002140 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2141 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
danielk1977c00da102006-01-07 13:21:04 +00002142 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh063336a2004-11-05 20:58:39 +00002143 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2144 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00002145 if( pIndex->onError!=OE_None ){
2146 int curaddr = sqlite3VdbeCurrentAddr(v);
2147 int addr2 = curaddr+4;
2148 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2149 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2150 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2151 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2152 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2153 "indexed columns are not unique", P3_STATIC);
2154 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002155 }
drh7f057c92005-06-24 03:53:06 +00002156 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002157 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002158 sqlite3VdbeJumpHere(v, addr1);
drh063336a2004-11-05 20:58:39 +00002159 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2160 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2161}
2162
2163/*
drh23bf66d2004-12-14 03:34:34 +00002164** Create a new index for an SQL table. pName1.pName2 is the name of the index
2165** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002166** be NULL for a primary key or an index that is created to satisfy a
2167** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002168** as the table to be indexed. pParse->pNewTable is a table that is
2169** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002170**
drh382c0242001-10-06 16:33:02 +00002171** pList is a list of columns to be indexed. pList will be NULL if this
2172** is a primary key or unique-constraint on the most recent column added
2173** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002174*/
danielk19774adee202004-05-08 08:23:19 +00002175void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002176 Parse *pParse, /* All information about this parse */
2177 Token *pName1, /* First part of index name. May be NULL */
2178 Token *pName2, /* Second part of index name. May be NULL */
2179 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002180 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002181 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2182 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
drhfdd6e852005-12-16 01:06:16 +00002183 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002184 int sortOrder, /* Sort order of primary key when pList==NULL */
2185 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002186){
drhfdd6e852005-12-16 01:06:16 +00002187 Table *pTab = 0; /* Table to be indexed */
2188 Index *pIndex = 0; /* The index to be created */
2189 char *zName = 0; /* Name of the index */
2190 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002191 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002192 Token nullId; /* Fake token for an empty ID list */
2193 DbFixer sFix; /* For assigning database names to pTable */
2194 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002195 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002196 Db *pDb; /* The specific table containing the indexed database */
2197 int iDb; /* Index of the database that is being written */
2198 Token *pName = 0; /* Unqualified name of the index to create */
2199 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002200 int nCol;
2201 int nExtra = 0;
2202 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002203
danielk1977e501b892006-01-09 06:29:47 +00002204 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ){
2205 goto exit_create_index;
2206 }
drhdaffd0e2001-04-11 14:28:42 +00002207
drh75897232000-05-29 14:26:00 +00002208 /*
2209 ** Find the table that is to be indexed. Return early if not found.
2210 */
danielk1977cbb18d22004-05-28 11:37:27 +00002211 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002212
2213 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002214 ** to search for the table. 'Fix' the table name to this db
2215 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002216 */
2217 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002218 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002219 if( iDb<0 ) goto exit_create_index;
2220
danielk197753c0f742005-03-29 03:10:59 +00002221#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002222 /* If the index name was unqualified, check if the the table
2223 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002224 */
danielk1977ef2cb632004-05-29 02:37:19 +00002225 pTab = sqlite3SrcListLookup(pParse, pTblName);
danielk1977da184232006-01-05 11:34:32 +00002226 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977ef2cb632004-05-29 02:37:19 +00002227 iDb = 1;
2228 }
danielk197753c0f742005-03-29 03:10:59 +00002229#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002230
2231 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2232 sqlite3FixSrcList(&sFix, pTblName)
2233 ){
drh85c23c62005-08-20 03:03:04 +00002234 /* Because the parser constructs pTblName from a single identifier,
2235 ** sqlite3FixSrcList can never fail. */
2236 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002237 }
danielk1977ef2cb632004-05-29 02:37:19 +00002238 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2239 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002240 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002241 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002242 }else{
drhe3c41372001-09-17 20:25:58 +00002243 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002244 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002245 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002246 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002247 }
drhfdd6e852005-12-16 01:06:16 +00002248 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002249
drh75897232000-05-29 14:26:00 +00002250 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002251 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002252 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002253 goto exit_create_index;
2254 }
danielk1977576ec6b2005-01-21 11:55:25 +00002255#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002256 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002257 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002258 goto exit_create_index;
2259 }
danielk1977576ec6b2005-01-21 11:55:25 +00002260#endif
drh75897232000-05-29 14:26:00 +00002261
2262 /*
2263 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002264 ** index or table with the same name.
2265 **
2266 ** Exception: If we are reading the names of permanent indices from the
2267 ** sqlite_master table (because some other process changed the schema) and
2268 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002269 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002270 **
2271 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002272 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2273 ** own name.
drh75897232000-05-29 14:26:00 +00002274 */
danielk1977d8123362004-06-12 09:25:12 +00002275 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002276 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002277 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002278 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002279 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002280 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002281 }
danielk1977d8123362004-06-12 09:25:12 +00002282 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002283 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002284 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
drh4d91a702006-01-04 15:54:36 +00002285 if( !ifNotExist ){
2286 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2287 }
danielk1977d8123362004-06-12 09:25:12 +00002288 goto exit_create_index;
2289 }
drh4f26bb62005-09-08 14:17:20 +00002290 if( sqlite3FindTable(db, zName, 0)!=0 ){
danielk1977d8123362004-06-12 09:25:12 +00002291 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2292 goto exit_create_index;
2293 }
drhe3c41372001-09-17 20:25:58 +00002294 }
danielk1977a21c6b62005-01-24 10:25:59 +00002295 }else{
drhadbca9c2001-09-27 15:11:53 +00002296 char zBuf[30];
2297 int n;
2298 Index *pLoop;
2299 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002300 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002301 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002302 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002303 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002304 }
2305
drhe5f9c642003-01-13 23:27:31 +00002306 /* Check for authorization to create an index.
2307 */
2308#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002309 {
drhfdd6e852005-12-16 01:06:16 +00002310 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002311 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002312 goto exit_create_index;
2313 }
2314 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002315 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002316 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002317 goto exit_create_index;
2318 }
drhe5f9c642003-01-13 23:27:31 +00002319 }
2320#endif
2321
drh75897232000-05-29 14:26:00 +00002322 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002323 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002324 ** So create a fake list to simulate this.
2325 */
2326 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002327 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2328 nullId.n = strlen((char*)nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002329 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002330 if( pList==0 ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002331 pList->a[0].sortOrder = sortOrder;
drh75897232000-05-29 14:26:00 +00002332 }
2333
danielk1977b3bf5562006-01-10 17:58:23 +00002334 /* Figure out how many bytes of space are required to store explicitly
2335 ** specified collation sequence names.
2336 */
2337 for(i=0; i<pList->nExpr; i++){
2338 Expr *pExpr = pList->a[i].pExpr;
2339 if( pExpr ){
2340 nExtra += (1 + strlen(pExpr->pColl->zName));
2341 }
2342 }
2343
drh75897232000-05-29 14:26:00 +00002344 /*
2345 ** Allocate the index structure.
2346 */
drhfdd6e852005-12-16 01:06:16 +00002347 nName = strlen(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002348 nCol = pList->nExpr;
2349 pIndex = sqliteMalloc(
2350 sizeof(Index) + /* Index structure */
2351 sizeof(int)*nCol + /* Index.aiColumn */
2352 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2353 sizeof(char *)*nCol + /* Index.azColl */
2354 sizeof(u8)*nCol + /* Index.aSortOrder */
2355 nName + 1 + /* Index.zName */
2356 nExtra /* Collation sequence names */
2357 );
danielk1977e501b892006-01-09 06:29:47 +00002358 if( sqlite3ThreadData()->mallocFailed ) goto exit_create_index;
danielk1977b3bf5562006-01-10 17:58:23 +00002359 pIndex->aiColumn = (int *)(&pIndex[1]);
2360 pIndex->aiRowEst = (int *)(&pIndex->aiColumn[nCol]);
2361 pIndex->azColl = (char **)(&pIndex->aiRowEst[nCol+1]);
2362 pIndex->aSortOrder = (u8 *)(&pIndex->azColl[nCol]);
2363 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2364 zExtra = (char *)(&pIndex->zName[nName+1]);
drh75897232000-05-29 14:26:00 +00002365 strcpy(pIndex->zName, zName);
2366 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002367 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002368 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002369 pIndex->autoIndex = pName==0;
danielk1977da184232006-01-05 11:34:32 +00002370 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002371
drhfdd6e852005-12-16 01:06:16 +00002372 /* Check to see if we should honor DESC requests on index columns
2373 */
danielk1977da184232006-01-05 11:34:32 +00002374 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002375 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002376 }else{
2377 sortOrderMask = 0; /* Ignore DESC */
2378 }
2379
drh1ccde152000-06-17 13:12:39 +00002380 /* Scan the names of the columns of the table to be indexed and
2381 ** load the column indices into the Index structure. Report an error
2382 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002383 */
drhfdd6e852005-12-16 01:06:16 +00002384 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2385 const char *zColName = pListItem->zName;
2386 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002387 int requestedSortOrder;
danielk1977b3bf5562006-01-10 17:58:23 +00002388 char *zColl; /* Collation sequence */
2389
drhfdd6e852005-12-16 01:06:16 +00002390 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2391 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002392 }
2393 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002394 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002395 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002396 goto exit_create_index;
2397 }
drh967e8b72000-06-21 13:59:10 +00002398 pIndex->aiColumn[i] = j;
drhfdd6e852005-12-16 01:06:16 +00002399 if( pListItem->pExpr ){
2400 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002401 zColl = zExtra;
2402 strcpy(zExtra, pListItem->pExpr->pColl->zName);
2403 zExtra += (strlen(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002404 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002405 zColl = pTab->aCol[j].zColl;
2406 if( !zColl ){
2407 zColl = db->pDfltColl->zName;
2408 }
danielk19770202b292004-06-09 09:55:16 +00002409 }
danielk1977b3bf5562006-01-10 17:58:23 +00002410 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002411 goto exit_create_index;
2412 }
danielk1977b3bf5562006-01-10 17:58:23 +00002413 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002414 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
danielk1977b3bf5562006-01-10 17:58:23 +00002415 pIndex->aSortOrder[i] = requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002416 }
drh51147ba2005-07-23 22:59:55 +00002417 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002418
danielk1977d8123362004-06-12 09:25:12 +00002419 if( pTab==pParse->pNewTable ){
2420 /* This routine has been called to create an automatic index as a
2421 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2422 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2423 ** i.e. one of:
2424 **
2425 ** CREATE TABLE t(x PRIMARY KEY, y);
2426 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2427 **
2428 ** Either way, check to see if the table already has such an index. If
2429 ** so, don't bother creating this one. This only applies to
2430 ** automatically created indices. Users can do as they wish with
2431 ** explicit indices.
2432 */
2433 Index *pIdx;
2434 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2435 int k;
2436 assert( pIdx->onError!=OE_None );
2437 assert( pIdx->autoIndex );
2438 assert( pIndex->onError!=OE_None );
2439
2440 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2441 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002442 const char *z1 = pIdx->azColl[k];
2443 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002444 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002445 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2446 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002447 }
2448 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002449 if( pIdx->onError!=pIndex->onError ){
2450 /* This constraint creates the same index as a previous
2451 ** constraint specified somewhere in the CREATE TABLE statement.
2452 ** However the ON CONFLICT clauses are different. If both this
2453 ** constraint and the previous equivalent constraint have explicit
2454 ** ON CONFLICT clauses this is an error. Otherwise, use the
2455 ** explicitly specified behaviour for the index.
2456 */
2457 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2458 sqlite3ErrorMsg(pParse,
2459 "conflicting ON CONFLICT clauses specified", 0);
2460 }
2461 if( pIdx->onError==OE_Default ){
2462 pIdx->onError = pIndex->onError;
2463 }
2464 }
danielk1977d8123362004-06-12 09:25:12 +00002465 goto exit_create_index;
2466 }
2467 }
2468 }
2469
drh75897232000-05-29 14:26:00 +00002470 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002471 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002472 */
drh234c39d2004-07-24 03:30:47 +00002473 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002474 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002475 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drh3c8bf552003-07-01 18:13:14 +00002476 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002477 if( p ){
2478 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002479 goto exit_create_index;
2480 }
drh5e00f6c2001-09-13 13:46:56 +00002481 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002482 if( pTblName!=0 ){
2483 pIndex->tnum = db->init.newTnum;
2484 }
drhd78eeee2001-09-13 16:18:53 +00002485 }
2486
drh1d85d932004-02-14 23:05:52 +00002487 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002488 ** involves writing the index into the master table and filling in the
2489 ** index with the current table contents.
2490 **
drh1d85d932004-02-14 23:05:52 +00002491 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2492 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002493 ** CREATE INDEX statements are read out of the master table. In
2494 ** the latter case the index already exists on disk, which is why
2495 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002496 **
danielk1977cbb18d22004-05-28 11:37:27 +00002497 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002498 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2499 ** has just been created, it contains no data and the index initialization
2500 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002501 */
drh1d85d932004-02-14 23:05:52 +00002502 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002503 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002504 char *zStmt;
2505 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002506
danielk19774adee202004-05-08 08:23:19 +00002507 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002508 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002509
drhfdd6e852005-12-16 01:06:16 +00002510
drh063336a2004-11-05 20:58:39 +00002511 /* Create the rootpage for the index
2512 */
drhaee128d2005-02-14 20:48:18 +00002513 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002514 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002515 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2516
2517 /* Gather the complete text of the CREATE INDEX statement into
2518 ** the zStmt variable
2519 */
drhe0bc4042002-06-25 01:09:11 +00002520 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002521 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002522 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002523 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002524 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002525 pName->z);
2526 }else{
2527 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002528 /* zStmt = sqlite3MPrintf(""); */
2529 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002530 }
drh063336a2004-11-05 20:58:39 +00002531
2532 /* Add an entry in sqlite_master for this index
2533 */
2534 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002535 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002536 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2537 pIndex->zName,
2538 pTab->zName,
2539 zStmt
2540 );
2541 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2542 sqliteFree(zStmt);
2543
danielk1977a21c6b62005-01-24 10:25:59 +00002544 /* Fill the index with data and reparse the schema. Code an OP_Expire
2545 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002546 */
danielk1977cbb18d22004-05-28 11:37:27 +00002547 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002548 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002549 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002550 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2551 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002552 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002553 }
drh75897232000-05-29 14:26:00 +00002554 }
2555
danielk1977d8123362004-06-12 09:25:12 +00002556 /* When adding an index to the list of indices for a table, make
2557 ** sure all indices labeled OE_Replace come after all those labeled
2558 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2559 ** and INSERT.
2560 */
drh234c39d2004-07-24 03:30:47 +00002561 if( db->init.busy || pTblName==0 ){
2562 if( onError!=OE_Replace || pTab->pIndex==0
2563 || pTab->pIndex->onError==OE_Replace){
2564 pIndex->pNext = pTab->pIndex;
2565 pTab->pIndex = pIndex;
2566 }else{
2567 Index *pOther = pTab->pIndex;
2568 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2569 pOther = pOther->pNext;
2570 }
2571 pIndex->pNext = pOther->pNext;
2572 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002573 }
drh234c39d2004-07-24 03:30:47 +00002574 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002575 }
danielk1977d8123362004-06-12 09:25:12 +00002576
drh75897232000-05-29 14:26:00 +00002577 /* Clean up before exiting */
2578exit_create_index:
drh956bc922004-07-24 17:38:29 +00002579 if( pIndex ){
2580 freeIndex(pIndex);
2581 }
danielk19770202b292004-06-09 09:55:16 +00002582 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002583 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002584 sqliteFree(zName);
2585 return;
2586}
2587
2588/*
drhd28bcb32005-12-21 14:43:11 +00002589** Generate code to make sure the file format number is at least minFormat.
2590** The generated code will increase the file format number if necessary.
2591*/
2592void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2593 Vdbe *v;
2594 v = sqlite3GetVdbe(pParse);
2595 if( v ){
2596 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
2597 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2598 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
2599 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2600 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
2601 }
2602}
2603
2604/*
drh51147ba2005-07-23 22:59:55 +00002605** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002606** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002607**
2608** aiRowEst[0] is suppose to contain the number of elements in the index.
2609** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2610** number of rows in the table that match any particular value of the
2611** first column of the index. aiRowEst[2] is an estimate of the number
2612** of rows that match any particular combiniation of the first 2 columns
2613** of the index. And so forth. It must always be the case that
2614*
2615** aiRowEst[N]<=aiRowEst[N-1]
2616** aiRowEst[N]>=1
2617**
2618** Apart from that, we have little to go on besides intuition as to
2619** how aiRowEst[] should be initialized. The numbers generated here
2620** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002621*/
2622void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002623 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002624 int i;
drh28c4cf42005-07-27 20:41:43 +00002625 assert( a!=0 );
2626 a[0] = 1000000;
drh3adc9ce2005-07-28 16:51:51 +00002627 for(i=pIdx->nColumn; i>=1; i--){
2628 a[i] = 10;
drh28c4cf42005-07-27 20:41:43 +00002629 }
2630 if( pIdx->onError!=OE_None ){
2631 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002632 }
2633}
2634
2635/*
drh74e24cd2002-01-09 03:19:59 +00002636** This routine will drop an existing named index. This routine
2637** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002638*/
drh4d91a702006-01-04 15:54:36 +00002639void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002640 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002641 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002642 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002643 int iDb;
drh75897232000-05-29 14:26:00 +00002644
danielk1977e501b892006-01-09 06:29:47 +00002645 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002646 goto exit_drop_index;
2647 }
drhd24cc422003-03-27 12:51:24 +00002648 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002649 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2650 goto exit_drop_index;
2651 }
danielk19774adee202004-05-08 08:23:19 +00002652 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002653 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002654 if( !ifExists ){
2655 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2656 }
drha6ecd332004-06-10 00:29:09 +00002657 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002658 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002659 }
drh485b39b2002-07-13 03:11:52 +00002660 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002661 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002662 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002663 goto exit_drop_index;
2664 }
danielk1977da184232006-01-05 11:34:32 +00002665 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002666#ifndef SQLITE_OMIT_AUTHORIZATION
2667 {
2668 int code = SQLITE_DROP_INDEX;
2669 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002670 const char *zDb = db->aDb[iDb].zName;
2671 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002672 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002673 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002674 }
danielk1977da184232006-01-05 11:34:32 +00002675 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002676 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002677 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002678 }
drhed6c8672003-01-12 18:02:16 +00002679 }
drhe5f9c642003-01-13 23:27:31 +00002680#endif
drh75897232000-05-29 14:26:00 +00002681
2682 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002683 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002684 if( v ){
drhb17131a2004-11-05 22:18:49 +00002685 sqlite3NestedParse(pParse,
2686 "DELETE FROM %Q.%s WHERE name=%Q",
2687 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2688 pIndex->zName
2689 );
2690 sqlite3ChangeCookie(db, v, iDb);
2691 destroyRootPage(pParse, pIndex->tnum, iDb);
2692 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002693 }
2694
drhd24cc422003-03-27 12:51:24 +00002695exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002696 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002697}
2698
2699/*
drh13449892005-09-07 21:22:45 +00002700** ppArray points into a structure where there is an array pointer
2701** followed by two integers. The first integer is the
2702** number of elements in the structure array. The second integer
2703** is the number of allocated slots in the array.
2704**
2705** In other words, the structure looks something like this:
2706**
2707** struct Example1 {
2708** struct subElem *aEntry;
2709** int nEntry;
2710** int nAlloc;
2711** }
2712**
2713** The pnEntry parameter points to the equivalent of Example1.nEntry.
2714**
2715** This routine allocates a new slot in the array, zeros it out,
2716** and returns its index. If malloc fails a negative number is returned.
2717**
2718** szEntry is the sizeof of a single array entry. initSize is the
2719** number of array entries allocated on the initial allocation.
2720*/
2721int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
2722 char *p;
2723 int *an = (int*)&ppArray[1];
2724 if( an[0]>=an[1] ){
2725 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002726 int newSize;
2727 newSize = an[1]*2 + initSize;
2728 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002729 if( pNew==0 ){
2730 return -1;
2731 }
drh5360ad32005-09-08 00:13:27 +00002732 an[1] = newSize;
drh13449892005-09-07 21:22:45 +00002733 *ppArray = pNew;
2734 }
2735 p = *ppArray;
2736 memset(&p[an[0]*szEntry], 0, szEntry);
2737 return an[0]++;
2738}
2739
2740/*
drh75897232000-05-29 14:26:00 +00002741** Append a new element to the given IdList. Create a new IdList if
2742** need be.
drhdaffd0e2001-04-11 14:28:42 +00002743**
2744** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002745*/
danielk19774adee202004-05-08 08:23:19 +00002746IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002747 int i;
drh75897232000-05-29 14:26:00 +00002748 if( pList==0 ){
2749 pList = sqliteMalloc( sizeof(IdList) );
2750 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002751 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002752 }
drh13449892005-09-07 21:22:45 +00002753 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
2754 if( i<0 ){
2755 sqlite3IdListDelete(pList);
2756 return 0;
drh75897232000-05-29 14:26:00 +00002757 }
drh13449892005-09-07 21:22:45 +00002758 pList->a[i].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002759 return pList;
2760}
2761
2762/*
drhfe05af82005-07-21 03:14:59 +00002763** Delete an IdList.
2764*/
2765void sqlite3IdListDelete(IdList *pList){
2766 int i;
2767 if( pList==0 ) return;
2768 for(i=0; i<pList->nId; i++){
2769 sqliteFree(pList->a[i].zName);
2770 }
2771 sqliteFree(pList->a);
2772 sqliteFree(pList);
2773}
2774
2775/*
2776** Return the index in pList of the identifier named zId. Return -1
2777** if not found.
2778*/
2779int sqlite3IdListIndex(IdList *pList, const char *zName){
2780 int i;
2781 if( pList==0 ) return -1;
2782 for(i=0; i<pList->nId; i++){
2783 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2784 }
2785 return -1;
2786}
2787
2788/*
drhad3cab52002-05-24 02:04:32 +00002789** Append a new table name to the given SrcList. Create a new SrcList if
2790** need be. A new entry is created in the SrcList even if pToken is NULL.
2791**
2792** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002793**
2794** If pDatabase is not null, it means that the table has an optional
2795** database name prefix. Like this: "database.table". The pDatabase
2796** points to the table name and the pTable points to the database name.
2797** The SrcList.a[].zName field is filled with the table name which might
2798** come from pTable (if pDatabase is NULL) or from pDatabase.
2799** SrcList.a[].zDatabase is filled with the database name from pTable,
2800** or with NULL if no database is specified.
2801**
2802** In other words, if call like this:
2803**
danielk19774adee202004-05-08 08:23:19 +00002804** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002805**
2806** Then B is a table name and the database name is unspecified. If called
2807** like this:
2808**
danielk19774adee202004-05-08 08:23:19 +00002809** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002810**
2811** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002812*/
danielk19774adee202004-05-08 08:23:19 +00002813SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002814 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002815 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002816 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002817 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002818 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002819 }
drh4305d102003-07-30 12:34:12 +00002820 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002821 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002822 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002823 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002824 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002825 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002826 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002827 return 0;
2828 }
drh113088e2003-03-20 01:16:58 +00002829 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002830 }
drha99db3b2004-06-19 14:49:12 +00002831 pItem = &pList->a[pList->nSrc];
2832 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002833 if( pDatabase && pDatabase->z==0 ){
2834 pDatabase = 0;
2835 }
2836 if( pDatabase && pTable ){
2837 Token *pTemp = pDatabase;
2838 pDatabase = pTable;
2839 pTable = pTemp;
2840 }
drha99db3b2004-06-19 14:49:12 +00002841 pItem->zName = sqlite3NameFromToken(pTable);
2842 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2843 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002844 pList->nSrc++;
2845 return pList;
2846}
2847
2848/*
drh63eb5f22003-04-29 16:20:44 +00002849** Assign cursors to all tables in a SrcList
2850*/
danielk19774adee202004-05-08 08:23:19 +00002851void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002852 int i;
drh9b3187e2005-01-18 14:45:47 +00002853 struct SrcList_item *pItem;
danielk1977e501b892006-01-09 06:29:47 +00002854 assert(pList || sqlite3ThreadData()->mallocFailed);
danielk1977261919c2005-12-06 12:52:59 +00002855 if( pList ){
2856 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2857 if( pItem->iCursor>=0 ) break;
2858 pItem->iCursor = pParse->nTab++;
2859 if( pItem->pSelect ){
2860 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2861 }
drh63eb5f22003-04-29 16:20:44 +00002862 }
2863 }
2864}
2865
2866/*
drh75897232000-05-29 14:26:00 +00002867** Add an alias to the last identifier on the given identifier list.
2868*/
danielk19774adee202004-05-08 08:23:19 +00002869void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002870 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002871 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002872 }
2873}
2874
2875/*
drhad3cab52002-05-24 02:04:32 +00002876** Delete an entire SrcList including all its substructure.
2877*/
danielk19774adee202004-05-08 08:23:19 +00002878void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002879 int i;
drhbe5c89a2004-07-26 00:31:09 +00002880 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002881 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002882 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2883 sqliteFree(pItem->zDatabase);
2884 sqliteFree(pItem->zName);
2885 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002886 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002887 sqlite3SelectDelete(pItem->pSelect);
2888 sqlite3ExprDelete(pItem->pOn);
2889 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002890 }
drh75897232000-05-29 14:26:00 +00002891 sqliteFree(pList);
2892}
2893
drh982cef72000-05-30 16:27:03 +00002894/*
drhc4a3c772001-04-04 11:48:57 +00002895** Begin a transaction
2896*/
drh684917c2004-10-05 02:41:42 +00002897void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002898 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002899 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002900 int i;
drh5e00f6c2001-09-13 13:46:56 +00002901
drh001bbcb2003-03-19 03:14:00 +00002902 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk1977e501b892006-01-09 06:29:47 +00002903 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002904 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002905
2906 v = sqlite3GetVdbe(pParse);
2907 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002908 if( type!=TK_DEFERRED ){
2909 for(i=0; i<db->nDb; i++){
2910 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2911 }
2912 }
danielk19771d850a72004-05-31 08:26:49 +00002913 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002914}
2915
2916/*
2917** Commit a transaction
2918*/
danielk19774adee202004-05-08 08:23:19 +00002919void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002920 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002921 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002922
drh001bbcb2003-03-19 03:14:00 +00002923 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk1977e501b892006-01-09 06:29:47 +00002924 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002925 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002926
2927 v = sqlite3GetVdbe(pParse);
2928 if( v ){
2929 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002930 }
drhc4a3c772001-04-04 11:48:57 +00002931}
2932
2933/*
2934** Rollback a transaction
2935*/
danielk19774adee202004-05-08 08:23:19 +00002936void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002937 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002938 Vdbe *v;
2939
drh001bbcb2003-03-19 03:14:00 +00002940 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk1977e501b892006-01-09 06:29:47 +00002941 if( pParse->nErr || sqlite3ThreadData()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002942 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002943
danielk19774adee202004-05-08 08:23:19 +00002944 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002945 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002946 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002947 }
drhc4a3c772001-04-04 11:48:57 +00002948}
drhf57b14a2001-09-14 18:54:08 +00002949
2950/*
drhdc3ff9c2004-08-18 02:10:15 +00002951** Make sure the TEMP database is open and available for use. Return
2952** the number of errors. Leave any error messages in the pParse structure.
2953*/
2954static int sqlite3OpenTempDatabase(Parse *pParse){
2955 sqlite3 *db = pParse->db;
2956 if( db->aDb[1].pBt==0 && !pParse->explain ){
2957 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2958 if( rc!=SQLITE_OK ){
2959 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2960 "file for storing temporary tables");
2961 pParse->rc = rc;
2962 return 1;
2963 }
2964 if( db->flags & !db->autoCommit ){
2965 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2966 if( rc!=SQLITE_OK ){
2967 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2968 "the temporary database file");
2969 pParse->rc = rc;
2970 return 1;
2971 }
2972 }
danielk197714db2662006-01-09 16:12:04 +00002973 assert( db->aDb[1].pSchema );
drhdc3ff9c2004-08-18 02:10:15 +00002974 }
2975 return 0;
2976}
2977
2978/*
drh80242052004-06-09 00:48:12 +00002979** Generate VDBE code that will verify the schema cookie and start
2980** a read-transaction for all named database files.
2981**
2982** It is important that all schema cookies be verified and all
2983** read transactions be started before anything else happens in
2984** the VDBE program. But this routine can be called after much other
2985** code has been generated. So here is what we do:
2986**
drhc275b4e2004-07-19 17:25:24 +00002987** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002988** will jump to a subroutine at the end of the program. Then we
2989** record every database that needs its schema verified in the
2990** pParse->cookieMask field. Later, after all other code has been
2991** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002992** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002993** will be made to point to that subroutine. The generation of the
2994** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002995**
2996** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2997** schema on any databases. This can be used to position the OP_Goto
2998** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00002999*/
danielk19774adee202004-05-08 08:23:19 +00003000void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003001 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003002 Vdbe *v;
3003 int mask;
3004
3005 v = sqlite3GetVdbe(pParse);
3006 if( v==0 ) return; /* This only happens if there was a prior error */
3007 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003008 if( pParse->cookieGoto==0 ){
3009 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003010 }
drhc275b4e2004-07-19 17:25:24 +00003011 if( iDb>=0 ){
3012 assert( iDb<db->nDb );
3013 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3014 assert( iDb<32 );
3015 mask = 1<<iDb;
3016 if( (pParse->cookieMask & mask)==0 ){
3017 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003018 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003019 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003020 sqlite3OpenTempDatabase(pParse);
3021 }
drhc275b4e2004-07-19 17:25:24 +00003022 }
drh001bbcb2003-03-19 03:14:00 +00003023 }
drh001bbcb2003-03-19 03:14:00 +00003024}
3025
3026/*
drh1c928532002-01-31 15:54:21 +00003027** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003028** might change the database.
3029**
3030** This routine starts a new transaction if we are not already within
3031** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003032** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003033** be set for operations that might fail (due to a constraint) part of
3034** the way through and which will need to undo some writes without having to
3035** rollback the whole transaction. For operations where all constraints
3036** can be checked before any changes are made to the database, it is never
3037** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003038**
drh8bf8dc92003-05-17 17:35:10 +00003039** Only database iDb and the temp database are made writable by this call.
3040** If iDb==0, then the main and temp databases are made writable. If
3041** iDb==1 then only the temp database is made writable. If iDb>1 then the
3042** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003043*/
drh7f0f12e2004-05-21 13:39:50 +00003044void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003045 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003046 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003047 sqlite3CodeVerifySchema(pParse, iDb);
3048 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003049 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00003050 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00003051 }
danielk197753c0f742005-03-29 03:10:59 +00003052 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003053 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003054 }
3055}
3056
drh4343fea2004-11-05 23:46:15 +00003057/*
3058** Check to see if pIndex uses the collating sequence pColl. Return
3059** true if it does and false if it does not.
3060*/
3061#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003062static int collationMatch(const char *zColl, Index *pIndex){
3063 int i;
3064 for(i=0; i<pIndex->nColumn; i++){
3065 const char *z = pIndex->azColl[i];
3066 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3067 return 1;
3068 }
drh4343fea2004-11-05 23:46:15 +00003069 }
3070 return 0;
3071}
3072#endif
3073
3074/*
3075** Recompute all indices of pTab that use the collating sequence pColl.
3076** If pColl==0 then recompute all indices of pTab.
3077*/
3078#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003079static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003080 Index *pIndex; /* An index associated with pTab */
3081
3082 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003083 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003084 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3085 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003086 sqlite3RefillIndex(pParse, pIndex, -1);
3087 }
3088 }
3089}
3090#endif
3091
3092/*
3093** Recompute all indices of all tables in all databases where the
3094** indices use the collating sequence pColl. If pColl==0 then recompute
3095** all indices everywhere.
3096*/
3097#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003098static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003099 Db *pDb; /* A single database */
3100 int iDb; /* The database index number */
3101 sqlite3 *db = pParse->db; /* The database connection */
3102 HashElem *k; /* For looping over tables in pDb */
3103 Table *pTab; /* A table in the database */
3104
3105 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3106 if( pDb==0 ) continue;
danielk1977da184232006-01-05 11:34:32 +00003107 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003108 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003109 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003110 }
3111 }
3112}
3113#endif
3114
3115/*
drheee46cf2004-11-06 00:02:48 +00003116** Generate code for the REINDEX command.
3117**
3118** REINDEX -- 1
3119** REINDEX <collation> -- 2
3120** REINDEX ?<database>.?<tablename> -- 3
3121** REINDEX ?<database>.?<indexname> -- 4
3122**
3123** Form 1 causes all indices in all attached databases to be rebuilt.
3124** Form 2 rebuilds all indices in all databases that use the named
3125** collating function. Forms 3 and 4 rebuild the named index or all
3126** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003127*/
3128#ifndef SQLITE_OMIT_REINDEX
3129void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3130 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3131 char *z; /* Name of a table or index */
3132 const char *zDb; /* Name of the database */
3133 Table *pTab; /* A table in the database */
3134 Index *pIndex; /* An index associated with pTab */
3135 int iDb; /* The database index number */
3136 sqlite3 *db = pParse->db; /* The database connection */
3137 Token *pObjName; /* Name of the table or index to be reindexed */
3138
danielk197733a5edc2005-01-27 00:22:02 +00003139 /* Read the database schema. If an error occurs, leave an error message
3140 ** and code in pParse and return NULL. */
3141 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003142 return;
danielk197733a5edc2005-01-27 00:22:02 +00003143 }
3144
drhe497f002004-11-07 13:01:49 +00003145 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003146 reindexDatabases(pParse, 0);
3147 return;
drhe497f002004-11-07 13:01:49 +00003148 }else if( pName2==0 || pName2->z==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003149 assert( pName1->z );
danielk197714db2662006-01-09 16:12:04 +00003150 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
drh4343fea2004-11-05 23:46:15 +00003151 if( pColl ){
danielk1977b3bf5562006-01-10 17:58:23 +00003152 char *z = sqlite3StrNDup(pName1->z, pName1->n);
3153 if( z ){
3154 reindexDatabases(pParse, z);
3155 sqliteFree(z);
3156 }
drh4343fea2004-11-05 23:46:15 +00003157 return;
3158 }
3159 }
3160 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3161 if( iDb<0 ) return;
3162 z = sqlite3NameFromToken(pObjName);
3163 zDb = db->aDb[iDb].zName;
3164 pTab = sqlite3FindTable(db, z, zDb);
3165 if( pTab ){
3166 reindexTable(pParse, pTab, 0);
3167 sqliteFree(z);
3168 return;
3169 }
3170 pIndex = sqlite3FindIndex(db, z, zDb);
3171 sqliteFree(z);
3172 if( pIndex ){
3173 sqlite3BeginWriteOperation(pParse, 0, iDb);
3174 sqlite3RefillIndex(pParse, pIndex, -1);
3175 return;
3176 }
3177 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3178}
3179#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003180
3181/*
3182** Return a dynamicly allocated KeyInfo structure that can be used
3183** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3184**
3185** If successful, a pointer to the new structure is returned. In this case
3186** the caller is responsible for calling sqliteFree() on the returned
3187** pointer. If an error occurs (out of memory or missing collation
3188** sequence), NULL is returned and the state of pParse updated to reflect
3189** the error.
3190*/
3191KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3192 int i;
3193 int nCol = pIdx->nColumn;
3194 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3195 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
3196
3197 if( pKey ){
3198 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3199 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3200 for(i=0; i<nCol; i++){
3201 char *zColl = pIdx->azColl[i];
3202 assert( zColl );
3203 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3204 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3205 }
3206 pKey->nField = nCol;
3207 }
3208
3209 if( pParse->nErr ){
3210 sqliteFree(pKey);
3211 pKey = 0;
3212 }
3213 return pKey;
3214}
3215