blob: ee39910182154d2774d58809ae92ace0c499405b [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**
drh6f7adc82006-01-11 21:41:20 +000025** $Id: build.c,v 1.377 2006/01/11 21:41:22 drh Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
drhf57b14a2001-09-14 18:54:08 +000028#include <ctype.h>
drh75897232000-05-29 14:26:00 +000029
30/*
drhe0bc4042002-06-25 01:09:11 +000031** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000032** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000033*/
danielk19774adee202004-05-08 08:23:19 +000034void sqlite3BeginParse(Parse *pParse, int explainFlag){
drhe0bc4042002-06-25 01:09:11 +000035 pParse->explain = explainFlag;
drh7c972de2003-09-06 22:18:07 +000036 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000037}
38
danielk1977c00da102006-01-07 13:21:04 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
41** The TableLock structure is only used by the sqlite3TableLock() and
42** codeTableLocks() functions.
43*/
44struct TableLock {
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;
danielk1977c00da102006-01-07 13:21:04 +000069
drh6f7adc82006-01-11 21:41:20 +000070 if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
danielk1977c00da102006-01-07 13:21:04 +000071 return;
72 }
73
74 for(i=0; i<pParse->nTableLock; i++){
75 p = &pParse->aTableLock[i];
76 if( p->iDb==iDb && p->iTab==iTab ){
77 p->isWriteLock = (p->isWriteLock || isWriteLock);
78 return;
79 }
80 }
81
82 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
83 sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
84 if( pParse->aTableLock ){
85 p = &pParse->aTableLock[pParse->nTableLock++];
86 p->iDb = iDb;
87 p->iTab = iTab;
88 p->isWriteLock = isWriteLock;
89 p->zName = zName;
90 }
91}
92
93/*
94** Code an OP_TableLock instruction for each table locked by the
95** statement (configured by calls to sqlite3TableLock()).
96*/
97static void codeTableLocks(Parse *pParse){
98 int i;
99 Vdbe *pVdbe;
drh6f7adc82006-01-11 21:41:20 +0000100 assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
danielk1977c00da102006-01-07 13:21:04 +0000101
102 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
103 return;
104 }
105
106 for(i=0; i<pParse->nTableLock; i++){
107 TableLock *p = &pParse->aTableLock[i];
108 int p1 = p->iDb;
109 if( p->isWriteLock ){
110 p1 = -1*(p1+1);
111 }
112 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
113 }
114}
115#else
116 #define codeTableLocks(x)
117#endif
118
drhe0bc4042002-06-25 01:09:11 +0000119/*
drh75897232000-05-29 14:26:00 +0000120** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000121** parsed and a VDBE program to execute that statement has been
122** prepared. This routine puts the finishing touches on the
123** VDBE program and resets the pParse structure for the next
124** parse.
drh75897232000-05-29 14:26:00 +0000125**
126** Note that if an error occurred, it might be the case that
127** no VDBE code was generated.
128*/
drh80242052004-06-09 00:48:12 +0000129void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000130 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000131 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000132
drh6f7adc82006-01-11 21:41:20 +0000133 if( sqlite3ThreadDataReadOnly()->mallocFailed ) return;
drh205f48e2004-11-05 00:43:11 +0000134 if( pParse->nested ) return;
danielk1977441daf62005-02-01 03:46:43 +0000135 if( !pParse->pVdbe ){
danielk1977c30f9e72005-02-09 07:05:46 +0000136 if( pParse->rc==SQLITE_OK && pParse->nErr ){
137 pParse->rc = SQLITE_ERROR;
138 }
danielk1977441daf62005-02-01 03:46:43 +0000139 return;
140 }
danielk197748d0d862005-02-01 03:09:52 +0000141
drh80242052004-06-09 00:48:12 +0000142 /* Begin by generating some termination code at the end of the
143 ** vdbe program
144 */
145 db = pParse->db;
146 v = sqlite3GetVdbe(pParse);
147 if( v ){
148 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
drh0e3d7472004-06-19 17:33:07 +0000149
150 /* The cookie mask contains one bit for each database file open.
151 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
152 ** set for each database that is used. Generate code to start a
153 ** transaction on each used database and to verify the schema cookie
154 ** on each used database.
155 */
drhc275b4e2004-07-19 17:25:24 +0000156 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000157 u32 mask;
158 int iDb;
drhd654be82005-09-20 17:42:23 +0000159 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000160 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
161 if( (mask & pParse->cookieMask)==0 ) continue;
162 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drhc275b4e2004-07-19 17:25:24 +0000163 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +0000164 }
danielk1977c00da102006-01-07 13:21:04 +0000165
166 /* Once all the cookies have been verified and transactions opened,
167 ** obtain the required table-locks. This is a no-op unless the
168 ** shared-cache feature is enabled.
169 */
170 codeTableLocks(pParse);
drhc275b4e2004-07-19 17:25:24 +0000171 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000172 }
drh80242052004-06-09 00:48:12 +0000173
drh19e2d372005-08-29 23:00:03 +0000174#ifndef SQLITE_OMIT_TRACE
drh71c697e2004-08-08 23:39:19 +0000175 /* Add a No-op that contains the complete text of the compiled SQL
176 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +0000177 ** of the program.
178 **
drh23bf66d2004-12-14 03:34:34 +0000179 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +0000180 */
181 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh19e2d372005-08-29 23:00:03 +0000182#endif /* SQLITE_OMIT_TRACE */
drh71c697e2004-08-08 23:39:19 +0000183 }
184
drh3f7d4e42004-07-24 14:35:58 +0000185
drh80242052004-06-09 00:48:12 +0000186 /* Get the VDBE program ready for execution
187 */
drhb86ccfb2003-01-28 23:13:10 +0000188 if( v && pParse->nErr==0 ){
189 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000190 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +0000191 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
drh13449892005-09-07 21:22:45 +0000192 pParse->nTab+3, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000193 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000194 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000195 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000196 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000197 }
drha226d052002-09-25 19:04:07 +0000198 pParse->nTab = 0;
199 pParse->nMem = 0;
200 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000201 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000202 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000203 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000204}
205
206/*
drh205f48e2004-11-05 00:43:11 +0000207** Run the parser and code generator recursively in order to generate
208** code for the SQL statement given onto the end of the pParse context
209** currently under construction. When the parser is run recursively
210** this way, the final OP_Halt is not appended and other initialization
211** and finalization steps are omitted because those are handling by the
212** outermost parser.
213**
214** Not everything is nestable. This facility is designed to permit
215** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000216** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000217*/
218void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
219 va_list ap;
220 char *zSql;
drhf1974842004-11-05 03:56:00 +0000221# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
222 char saveBuf[SAVE_SZ];
223
drh205f48e2004-11-05 00:43:11 +0000224 if( pParse->nErr ) return;
225 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
226 va_start(ap, zFormat);
227 zSql = sqlite3VMPrintf(zFormat, ap);
228 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000229 if( zSql==0 ){
230 return; /* A malloc must have failed */
231 }
drh205f48e2004-11-05 00:43:11 +0000232 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000233 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
234 memset(&pParse->nVar, 0, SAVE_SZ);
drh4f26bb62005-09-08 14:17:20 +0000235 sqlite3RunParser(pParse, zSql, 0);
drh205f48e2004-11-05 00:43:11 +0000236 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000237 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000238 pParse->nested--;
239}
240
241/*
danielk19778a414492004-06-29 08:59:35 +0000242** Locate the in-memory structure that describes a particular database
243** table given the name of that table and (optionally) the name of the
244** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000245**
danielk19778a414492004-06-29 08:59:35 +0000246** If zDatabase is 0, all databases are searched for the table and the
247** first matching table is returned. (No checking for duplicate table
248** names is done.) The search order is TEMP first, then MAIN, then any
249** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000250**
danielk19774adee202004-05-08 08:23:19 +0000251** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000252*/
drh9bb575f2004-09-06 17:24:11 +0000253Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000254 Table *p = 0;
255 int i;
drh645f63e2004-06-22 13:22:40 +0000256 assert( zName!=0 );
danielk197753c0f742005-03-29 03:10:59 +0000257 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000258 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000259 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000260 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000261 if( p ) break;
262 }
drh74e24cd2002-01-09 03:19:59 +0000263 return p;
drh75897232000-05-29 14:26:00 +0000264}
265
266/*
danielk19778a414492004-06-29 08:59:35 +0000267** Locate the in-memory structure that describes a particular database
268** table given the name of that table and (optionally) the name of the
269** database containing the table. Return NULL if not found. Also leave an
270** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000271**
danielk19778a414492004-06-29 08:59:35 +0000272** The difference between this routine and sqlite3FindTable() is that this
273** routine leaves an error message in pParse->zErrMsg where
274** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000275*/
danielk19774adee202004-05-08 08:23:19 +0000276Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000277 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000278
danielk19778a414492004-06-29 08:59:35 +0000279 /* Read the database schema. If an error occurs, leave an error message
280 ** and code in pParse and return NULL. */
281 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
282 return 0;
283 }
284
danielk19774adee202004-05-08 08:23:19 +0000285 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000286 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000287 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000288 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000289 }else{
danielk19774adee202004-05-08 08:23:19 +0000290 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000291 }
drha6ecd332004-06-10 00:29:09 +0000292 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000293 }
294 return p;
295}
296
297/*
298** Locate the in-memory structure that describes
299** a particular index given the name of that index
300** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000301** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000302**
303** If zDatabase is 0, all databases are searched for the
304** table and the first matching index is returned. (No checking
305** for duplicate index names is done.) The search order is
306** TEMP first, then MAIN, then any auxiliary databases added
307** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000308*/
drh9bb575f2004-09-06 17:24:11 +0000309Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000310 Index *p = 0;
311 int i;
danielk197753c0f742005-03-29 03:10:59 +0000312 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000313 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000314 Schema *pSchema = db->aDb[j].pSchema;
danielk19774adee202004-05-08 08:23:19 +0000315 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000316 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
317 if( pSchema ){
318 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
319 }
drhd24cc422003-03-27 12:51:24 +0000320 if( p ) break;
321 }
drh74e24cd2002-01-09 03:19:59 +0000322 return p;
drh75897232000-05-29 14:26:00 +0000323}
324
325/*
drh956bc922004-07-24 17:38:29 +0000326** Reclaim the memory used by an index
327*/
328static void freeIndex(Index *p){
329 sqliteFree(p->zColAff);
330 sqliteFree(p);
331}
332
333/*
drh75897232000-05-29 14:26:00 +0000334** Remove the given index from the index hash table, and free
335** its memory structures.
336**
drhd229ca92002-01-09 13:30:41 +0000337** The index is removed from the database hash tables but
338** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000339** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000340*/
drh9bb575f2004-09-06 17:24:11 +0000341static void sqliteDeleteIndex(sqlite3 *db, Index *p){
drhd229ca92002-01-09 13:30:41 +0000342 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000343 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000344
danielk1977da184232006-01-05 11:34:32 +0000345 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000346 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000347 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000348}
349
350/*
drhc96d8532005-05-03 12:30:33 +0000351** For the index called zIdxName which is found in the database iDb,
352** unlike that index from its Table then remove the index from
353** the index hash table and free all memory structures associated
354** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000355*/
drh9bb575f2004-09-06 17:24:11 +0000356void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000357 Index *pIndex;
358 int len;
danielk1977da184232006-01-05 11:34:32 +0000359 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000360
361 len = strlen(zIdxName);
danielk1977da184232006-01-05 11:34:32 +0000362 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
drh956bc922004-07-24 17:38:29 +0000363 if( pIndex ){
364 if( pIndex->pTable->pIndex==pIndex ){
365 pIndex->pTable->pIndex = pIndex->pNext;
366 }else{
367 Index *p;
368 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
369 if( p && p->pNext==pIndex ){
370 p->pNext = pIndex->pNext;
371 }
drh5e00f6c2001-09-13 13:46:56 +0000372 }
drh956bc922004-07-24 17:38:29 +0000373 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000374 }
drh956bc922004-07-24 17:38:29 +0000375 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000376}
377
378/*
drhe0bc4042002-06-25 01:09:11 +0000379** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000380** a single database. This routine is called to reclaim memory
381** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000382** if there were schema changes during the transaction or if a
383** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000384**
385** If iDb<=0 then reset the internal schema tables for all database
386** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000387** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000388*/
drh9bb575f2004-09-06 17:24:11 +0000389void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000390 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000391
drh1c2d8412003-03-31 00:30:47 +0000392 assert( iDb>=0 && iDb<db->nDb );
drh1c2d8412003-03-31 00:30:47 +0000393 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000394 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000395 if( pDb->pSchema ){
danielk1977de0fe3e2006-01-06 06:33:12 +0000396 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000397 }
drh1c2d8412003-03-31 00:30:47 +0000398 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000399 }
drh1c2d8412003-03-31 00:30:47 +0000400 assert( iDb==0 );
401 db->flags &= ~SQLITE_InternChanges;
402
403 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000404 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000405 ** opportunity to do this here since we have just deleted all of the
406 ** schema hash tables and therefore do not have to make any changes
407 ** to any of those tables.
408 */
drh4d189ca2004-02-12 18:46:38 +0000409 for(i=0; i<db->nDb; i++){
410 struct Db *pDb = &db->aDb[i];
411 if( pDb->pBt==0 ){
412 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
413 pDb->pAux = 0;
414 }
415 }
drh1c2d8412003-03-31 00:30:47 +0000416 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000417 struct Db *pDb = &db->aDb[i];
418 if( pDb->pBt==0 ){
419 sqliteFree(pDb->zName);
420 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000421 continue;
422 }
423 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000424 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000425 }
drh8bf8dc92003-05-17 17:35:10 +0000426 j++;
drh1c2d8412003-03-31 00:30:47 +0000427 }
428 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
429 db->nDb = j;
430 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
431 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
432 sqliteFree(db->aDb);
433 db->aDb = db->aDbStatic;
434 }
drhe0bc4042002-06-25 01:09:11 +0000435}
436
437/*
438** This routine is called whenever a rollback occurs. If there were
439** schema changes during the transaction, then we have to reset the
440** internal hash tables and reload them from disk.
441*/
drh9bb575f2004-09-06 17:24:11 +0000442void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000443 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000444 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000445 }
446}
447
448/*
449** This routine is called when a commit occurs.
450*/
drh9bb575f2004-09-06 17:24:11 +0000451void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000452 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000453}
454
455/*
drh956bc922004-07-24 17:38:29 +0000456** Clear the column names from a table or view.
457*/
458static void sqliteResetColumnNames(Table *pTable){
459 int i;
460 Column *pCol;
461 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000462 if( (pCol = pTable->aCol)!=0 ){
463 for(i=0; i<pTable->nCol; i++, pCol++){
464 sqliteFree(pCol->zName);
465 sqlite3ExprDelete(pCol->pDflt);
466 sqliteFree(pCol->zType);
danielk1977b3bf5562006-01-10 17:58:23 +0000467 sqliteFree(pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000468 }
469 sqliteFree(pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000470 }
drh956bc922004-07-24 17:38:29 +0000471 pTable->aCol = 0;
472 pTable->nCol = 0;
473}
474
475/*
drh75897232000-05-29 14:26:00 +0000476** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000477** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000478**
479** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000480** the table data structure from the hash table. Nor does it remove
481** foreign keys from the sqlite.aFKey hash table. But it does destroy
482** memory structures of the indices and foreign keys associated with
483** the table.
drhdaffd0e2001-04-11 14:28:42 +0000484**
485** Indices associated with the table are unlinked from the "db"
486** data structure if db!=NULL. If db==NULL, indices attached to
487** the table are deleted, but it is assumed they have already been
488** unlinked.
drh75897232000-05-29 14:26:00 +0000489*/
drh9bb575f2004-09-06 17:24:11 +0000490void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000491 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000492 FKey *pFKey, *pNextFKey;
493
danielk1977de0fe3e2006-01-06 06:33:12 +0000494 db = 0;
495
drh75897232000-05-29 14:26:00 +0000496 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000497
drhed8a3bb2005-06-06 21:19:56 +0000498 /* Do not delete the table until the reference count reaches zero. */
499 pTable->nRef--;
500 if( pTable->nRef>0 ){
501 return;
502 }
503 assert( pTable->nRef==0 );
504
drhc2eef3b2002-08-31 18:53:06 +0000505 /* Delete all indices associated with this table
506 */
507 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
508 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000509 assert( pIndex->pSchema==pTable->pSchema );
drhc2eef3b2002-08-31 18:53:06 +0000510 sqliteDeleteIndex(db, pIndex);
511 }
512
danielk1977576ec6b2005-01-21 11:55:25 +0000513#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000514 /* Delete all foreign keys associated with this table. The keys
515 ** should have already been unlinked from the db->aFKey hash table
516 */
517 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
518 pNextFKey = pFKey->pNextFrom;
danielk1977da184232006-01-05 11:34:32 +0000519 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
drhd24cc422003-03-27 12:51:24 +0000520 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000521 sqliteFree(pFKey);
522 }
danielk1977576ec6b2005-01-21 11:55:25 +0000523#endif
drhc2eef3b2002-08-31 18:53:06 +0000524
525 /* Delete the Table structure itself.
526 */
drh956bc922004-07-24 17:38:29 +0000527 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000528 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000529 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000530 sqlite3SelectDelete(pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000531#ifndef SQLITE_OMIT_CHECK
532 sqlite3ExprDelete(pTable->pCheck);
533#endif
drh75897232000-05-29 14:26:00 +0000534 sqliteFree(pTable);
535}
536
537/*
drh5edc3122001-09-13 21:53:09 +0000538** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000539** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000540*/
drh9bb575f2004-09-06 17:24:11 +0000541void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000542 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000543 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000544 Db *pDb;
545
drhd229ca92002-01-09 13:30:41 +0000546 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000547 assert( iDb>=0 && iDb<db->nDb );
548 assert( zTabName && zTabName[0] );
549 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +0000550 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
drh956bc922004-07-24 17:38:29 +0000551 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000552#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000553 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
554 int nTo = strlen(pF1->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +0000555 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
drh956bc922004-07-24 17:38:29 +0000556 if( pF2==pF1 ){
danielk1977da184232006-01-05 11:34:32 +0000557 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
drh956bc922004-07-24 17:38:29 +0000558 }else{
559 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
560 if( pF2 ){
561 pF2->pNextTo = pF1->pNextTo;
562 }
drhc2eef3b2002-08-31 18:53:06 +0000563 }
564 }
danielk1977576ec6b2005-01-21 11:55:25 +0000565#endif
drh956bc922004-07-24 17:38:29 +0000566 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000567 }
drh956bc922004-07-24 17:38:29 +0000568 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000569}
570
571/*
drha99db3b2004-06-19 14:49:12 +0000572** Given a token, return a string that consists of the text of that
573** token with any quotations removed. Space to hold the returned string
574** is obtained from sqliteMalloc() and must be freed by the calling
575** function.
drh75897232000-05-29 14:26:00 +0000576**
drhc96d8532005-05-03 12:30:33 +0000577** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000578** are not \000 terminated and are not persistent. The returned string
579** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000580*/
drha99db3b2004-06-19 14:49:12 +0000581char *sqlite3NameFromToken(Token *pName){
582 char *zName;
583 if( pName ){
drh2646da72005-12-09 20:02:05 +0000584 zName = sqliteStrNDup((char*)pName->z, pName->n);
drha99db3b2004-06-19 14:49:12 +0000585 sqlite3Dequote(zName);
586 }else{
587 zName = 0;
588 }
drh75897232000-05-29 14:26:00 +0000589 return zName;
590}
591
592/*
danielk1977cbb18d22004-05-28 11:37:27 +0000593** Open the sqlite_master table stored in database number iDb for
594** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000595*/
danielk1977c00da102006-01-07 13:21:04 +0000596void sqlite3OpenMasterTable(Parse *p, int iDb){
597 Vdbe *v = sqlite3GetVdbe(p);
598 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977cbb18d22004-05-28 11:37:27 +0000599 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000600 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000601 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000602}
603
604/*
danielk1977cbb18d22004-05-28 11:37:27 +0000605** The token *pName contains the name of a database (either "main" or
606** "temp" or the name of an attached db). This routine returns the
607** index of the named database in db->aDb[], or -1 if the named db
608** does not exist.
609*/
drhff2d5ea2005-07-23 00:41:48 +0000610int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000611 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000612 int n; /* Number of characters in the name */
613 Db *pDb; /* A database whose name space is being searched */
614 char *zName; /* Name we are searching for */
615
616 zName = sqlite3NameFromToken(pName);
617 if( zName ){
618 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000619 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000620 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
621 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000622 break;
drh73c42a12004-11-20 18:13:10 +0000623 }
danielk1977cbb18d22004-05-28 11:37:27 +0000624 }
drh73c42a12004-11-20 18:13:10 +0000625 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000626 }
danielk1977576ec6b2005-01-21 11:55:25 +0000627 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000628}
629
drh0e3d7472004-06-19 17:33:07 +0000630/* The table or view or trigger name is passed to this routine via tokens
631** pName1 and pName2. If the table name was fully qualified, for example:
632**
633** CREATE TABLE xxx.yyy (...);
634**
635** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
636** the table name is not fully qualified, i.e.:
637**
638** CREATE TABLE yyy(...);
639**
640** Then pName1 is set to "yyy" and pName2 is "".
641**
642** This routine sets the *ppUnqual pointer to point at the token (pName1 or
643** pName2) that stores the unqualified table name. The index of the
644** database "xxx" is returned.
645*/
danielk1977ef2cb632004-05-29 02:37:19 +0000646int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000647 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000648 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000649 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
650 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000651){
drh0e3d7472004-06-19 17:33:07 +0000652 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000653 sqlite3 *db = pParse->db;
654
655 if( pName2 && pName2->n>0 ){
656 assert( !db->init.busy );
657 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000658 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000659 if( iDb<0 ){
660 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
661 pParse->nErr++;
662 return -1;
663 }
664 }else{
665 assert( db->init.iDb==0 || db->init.busy );
666 iDb = db->init.iDb;
667 *pUnqual = pName1;
668 }
669 return iDb;
670}
671
672/*
danielk1977d8123362004-06-12 09:25:12 +0000673** This routine is used to check if the UTF-8 string zName is a legal
674** unqualified name for a new schema object (table, index, view or
675** trigger). All names are legal except those that begin with the string
676** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
677** is reserved for internal use.
678*/
679int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000680 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000681 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000682 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000683 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
684 return SQLITE_ERROR;
685 }
686 return SQLITE_OK;
687}
688
689/*
drh75897232000-05-29 14:26:00 +0000690** Begin constructing a new table representation in memory. This is
691** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000692** to a CREATE TABLE statement. In particular, this routine is called
693** after seeing tokens "CREATE" and "TABLE" and the table name. The
drhf57b3392001-10-08 13:22:32 +0000694** pStart token is the CREATE and pName is the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000695** flag is true if the table should be stored in the auxiliary database
696** file instead of in the main database file. This is normally the case
697** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000698** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000699**
drhf57b3392001-10-08 13:22:32 +0000700** The new table record is initialized and put in pParse->pNewTable.
701** As more of the CREATE TABLE statement is parsed, additional action
702** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000703** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000704** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000705*/
danielk19774adee202004-05-08 08:23:19 +0000706void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000707 Parse *pParse, /* Parser context */
708 Token *pStart, /* The "CREATE" token */
danielk1977cbb18d22004-05-28 11:37:27 +0000709 Token *pName1, /* First part of the name of the table or view */
710 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000711 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000712 int isView, /* True if this is a VIEW */
713 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000714){
drh75897232000-05-29 14:26:00 +0000715 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000716 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000717 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000718 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000719 int iDb; /* Database number to create the table in */
720 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000721
danielk1977cbb18d22004-05-28 11:37:27 +0000722 /* The table or view name to create is passed to this routine via tokens
723 ** pName1 and pName2. If the table name was fully qualified, for example:
724 **
725 ** CREATE TABLE xxx.yyy (...);
726 **
727 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
728 ** the table name is not fully qualified, i.e.:
729 **
730 ** CREATE TABLE yyy(...);
731 **
732 ** Then pName1 is set to "yyy" and pName2 is "".
733 **
734 ** The call below sets the pName pointer to point at the token (pName1 or
735 ** pName2) that stores the unqualified table name. The variable iDb is
736 ** set to the index of the database that the table or view is to be
737 ** created in.
738 */
danielk1977ef2cb632004-05-29 02:37:19 +0000739 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000740 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000741 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000742 /* If creating a temp table, the name may not be qualified */
743 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000744 return;
745 }
danielk197753c0f742005-03-29 03:10:59 +0000746 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000747
748 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000749 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000750 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000751 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000752 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000753 }
drh1d85d932004-02-14 23:05:52 +0000754 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000755#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000756 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000757 {
758 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000759 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000760 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000761 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000762 }
drhe5f9c642003-01-13 23:27:31 +0000763 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000764 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000765 code = SQLITE_CREATE_TEMP_VIEW;
766 }else{
767 code = SQLITE_CREATE_VIEW;
768 }
769 }else{
danielk197753c0f742005-03-29 03:10:59 +0000770 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000771 code = SQLITE_CREATE_TEMP_TABLE;
772 }else{
773 code = SQLITE_CREATE_TABLE;
774 }
775 }
danielk19774adee202004-05-08 08:23:19 +0000776 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000777 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000778 }
779 }
780#endif
drhf57b3392001-10-08 13:22:32 +0000781
drhf57b3392001-10-08 13:22:32 +0000782 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000783 ** index or table name in the same database. Issue an error message if
784 ** it does.
drhf57b3392001-10-08 13:22:32 +0000785 */
danielk19775558a8a2005-01-17 07:53:44 +0000786 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
787 goto begin_table_error;
788 }
danielk19773df6b252004-05-29 10:23:19 +0000789 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
790 if( pTable ){
drhfaa59552005-12-29 23:33:54 +0000791 if( !noErr ){
792 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
793 }
drh23bf66d2004-12-14 03:34:34 +0000794 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000795 }
drh4f26bb62005-09-08 14:17:20 +0000796 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
danielk19774adee202004-05-08 08:23:19 +0000797 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
drh23bf66d2004-12-14 03:34:34 +0000798 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000799 }
800 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000801 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000802 pParse->rc = SQLITE_NOMEM;
803 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000804 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000805 }
drh75897232000-05-29 14:26:00 +0000806 pTable->zName = zName;
drh75897232000-05-29 14:26:00 +0000807 pTable->nCol = 0;
drh7020f652000-06-03 18:06:52 +0000808 pTable->aCol = 0;
drh4a324312001-12-21 14:30:42 +0000809 pTable->iPKey = -1;
drh75897232000-05-29 14:26:00 +0000810 pTable->pIndex = 0;
danielk1977da184232006-01-05 11:34:32 +0000811 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000812 pTable->nRef = 1;
danielk19774adee202004-05-08 08:23:19 +0000813 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000814 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000815
drh4794f732004-11-05 17:17:50 +0000816 /* If this is the magic sqlite_sequence table used by autoincrement,
817 ** then record a pointer to this table in the main database structure
818 ** so that INSERT can find the table easily.
819 */
820#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000821 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000822 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000823 }
824#endif
825
drh17f71932002-02-21 12:01:27 +0000826 /* Begin generating the code that will insert the table record into
827 ** the SQLITE_MASTER table. Note in particular that we must go ahead
828 ** and allocate the record number for the table entry now. Before any
829 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
830 ** indices to be created and the table record must come before the
831 ** indices. Hence, the record number for the table must be allocated
832 ** now.
833 */
danielk19774adee202004-05-08 08:23:19 +0000834 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk197736963fd2005-02-19 08:18:05 +0000835 int lbl;
danielk1977cbb18d22004-05-28 11:37:27 +0000836 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000837
danielk197736963fd2005-02-19 08:18:05 +0000838 /* If the file format and encoding in the database have not been set,
839 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000840 */
danielk197736963fd2005-02-19 08:18:05 +0000841 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
842 lbl = sqlite3VdbeMakeLabel(v);
843 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
drhd946db02005-12-29 19:23:06 +0000844 sqlite3VdbeAddOp(v, OP_Integer, SQLITE_DEFAULT_FILE_FORMAT, 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000845 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
danielk197714db2662006-01-09 16:12:04 +0000846 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000847 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000848 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000849
drh4794f732004-11-05 17:17:50 +0000850 /* This just creates a place-holder record in the sqlite_master table.
851 ** The record created does not contain anything yet. It will be replaced
852 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000853 **
854 ** The rowid for the new entry is left on the top of the stack.
855 ** The rowid value is needed by the code that sqlite3EndTable will
856 ** generate.
drh4794f732004-11-05 17:17:50 +0000857 */
danielk1977a21c6b62005-01-24 10:25:59 +0000858#ifndef SQLITE_OMIT_VIEW
859 if( isView ){
860 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
861 }else
862#endif
863 {
864 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
865 }
danielk1977c00da102006-01-07 13:21:04 +0000866 sqlite3OpenMasterTable(pParse, iDb);
drhf0863fe2005-06-12 21:35:51 +0000867 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000868 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000869 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
870 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000871 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000872 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000873 }
drh23bf66d2004-12-14 03:34:34 +0000874
875 /* Normal (non-error) return. */
876 return;
877
878 /* If an error occurs, we jump here */
879begin_table_error:
880 sqliteFree(zName);
881 return;
drh75897232000-05-29 14:26:00 +0000882}
883
884/*
danielk1977c60e9b82005-01-31 12:42:29 +0000885** This macro is used to compare two strings in a case-insensitive manner.
886** It is slightly faster than calling sqlite3StrICmp() directly, but
887** produces larger code.
888**
889** WARNING: This macro is not compatible with the strcmp() family. It
890** returns true if the two strings are equal, otherwise false.
891*/
892#define STRICMP(x, y) (\
893sqlite3UpperToLower[*(unsigned char *)(x)]== \
894sqlite3UpperToLower[*(unsigned char *)(y)] \
895&& sqlite3StrICmp((x)+1,(y)+1)==0 )
896
897/*
drh75897232000-05-29 14:26:00 +0000898** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000899**
900** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000901** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000902** first to get things going. Then this routine is called for each
903** column.
drh75897232000-05-29 14:26:00 +0000904*/
danielk19774adee202004-05-08 08:23:19 +0000905void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000906 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000907 int i;
drha99db3b2004-06-19 14:49:12 +0000908 char *z;
drhc9b84a12002-06-20 11:36:48 +0000909 Column *pCol;
drh75897232000-05-29 14:26:00 +0000910 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000911 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000912 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000913 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000914 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000915 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000916 sqliteFree(z);
917 return;
918 }
919 }
drh75897232000-05-29 14:26:00 +0000920 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000921 Column *aNew;
922 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000923 if( aNew==0 ){
924 sqliteFree(z);
925 return;
926 }
drh6d4abfb2001-10-22 02:58:08 +0000927 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000928 }
drhc9b84a12002-06-20 11:36:48 +0000929 pCol = &p->aCol[p->nCol];
930 memset(pCol, 0, sizeof(p->aCol[0]));
931 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000932
933 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000934 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
935 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000936 */
danielk19774f057f92004-06-08 00:02:33 +0000937 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000938 p->nCol++;
drh75897232000-05-29 14:26:00 +0000939}
940
941/*
drh382c0242001-10-06 16:33:02 +0000942** This routine is called by the parser while in the middle of
943** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
944** been seen on a column. This routine sets the notNull flag on
945** the column currently under construction.
946*/
danielk19774adee202004-05-08 08:23:19 +0000947void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000948 Table *p;
949 int i;
950 if( (p = pParse->pNewTable)==0 ) return;
951 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000952 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000953}
954
955/*
danielk197752a83fb2005-01-31 12:56:44 +0000956** Scan the column type name zType (length nType) and return the
957** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000958**
959** This routine does a case-independent search of zType for the
960** substrings in the following table. If one of the substrings is
961** found, the corresponding affinity is returned. If zType contains
962** more than one of the substrings, entries toward the top of
963** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000964** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000965**
966** Substring | Affinity
967** --------------------------------
968** 'INT' | SQLITE_AFF_INTEGER
969** 'CHAR' | SQLITE_AFF_TEXT
970** 'CLOB' | SQLITE_AFF_TEXT
971** 'TEXT' | SQLITE_AFF_TEXT
972** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000973** 'REAL' | SQLITE_AFF_REAL
974** 'FLOA' | SQLITE_AFF_REAL
975** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000976**
977** If none of the substrings in the above table are found,
978** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000979*/
drh8a512562005-11-14 22:29:05 +0000980char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000981 u32 h = 0;
982 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000983 const unsigned char *zIn = pType->z;
984 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000985
danielk1977b3dff962005-02-01 01:21:55 +0000986 while( zIn!=zEnd ){
987 h = (h<<8) + sqlite3UpperToLower[*zIn];
988 zIn++;
danielk1977201f7162005-02-01 02:13:29 +0000989 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
990 aff = SQLITE_AFF_TEXT;
991 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
992 aff = SQLITE_AFF_TEXT;
993 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
994 aff = SQLITE_AFF_TEXT;
995 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +0000996 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +0000997 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +0000998#ifndef SQLITE_OMIT_FLOATING_POINT
999 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1000 && aff==SQLITE_AFF_NUMERIC ){
1001 aff = SQLITE_AFF_REAL;
1002 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1003 && aff==SQLITE_AFF_NUMERIC ){
1004 aff = SQLITE_AFF_REAL;
1005 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1006 && aff==SQLITE_AFF_NUMERIC ){
1007 aff = SQLITE_AFF_REAL;
1008#endif
danielk1977201f7162005-02-01 02:13:29 +00001009 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001010 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001011 break;
danielk197752a83fb2005-01-31 12:56:44 +00001012 }
1013 }
danielk1977b3dff962005-02-01 01:21:55 +00001014
1015 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001016}
1017
1018/*
drh382c0242001-10-06 16:33:02 +00001019** This routine is called by the parser while in the middle of
1020** parsing a CREATE TABLE statement. The pFirst token is the first
1021** token in the sequence of tokens that describe the type of the
1022** column currently under construction. pLast is the last token
1023** in the sequence. Use this information to construct a string
1024** that contains the typename of the column and store that string
1025** in zType.
1026*/
drh487e2622005-06-25 18:42:14 +00001027void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001028 Table *p;
drh487e2622005-06-25 18:42:14 +00001029 int i;
drhc9b84a12002-06-20 11:36:48 +00001030 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001031
drh382c0242001-10-06 16:33:02 +00001032 if( (p = pParse->pNewTable)==0 ) return;
1033 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001034 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001035 pCol = &p->aCol[i];
drhd8919672005-09-10 15:35:06 +00001036 sqliteFree(pCol->zType);
drh487e2622005-06-25 18:42:14 +00001037 pCol->zType = sqlite3NameFromToken(pType);
drh8a512562005-11-14 22:29:05 +00001038 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001039}
1040
1041/*
danielk19777977a172004-11-09 12:44:37 +00001042** The expression is the default value for the most recently added column
1043** of the table currently under construction.
1044**
1045** Default value expressions must be constant. Raise an exception if this
1046** is not the case.
drhd9b02572001-04-15 00:37:09 +00001047**
1048** This routine is called by the parser while in the middle of
1049** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001050*/
danielk19777977a172004-11-09 12:44:37 +00001051void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001052 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001053 Column *pCol;
drh42b9d7c2005-08-13 00:56:27 +00001054 if( (p = pParse->pNewTable)!=0 ){
1055 pCol = &(p->aCol[p->nCol-1]);
1056 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1057 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1058 pCol->zName);
1059 }else{
1060 sqlite3ExprDelete(pCol->pDflt);
1061 pCol->pDflt = sqlite3ExprDup(pExpr);
1062 }
danielk19777977a172004-11-09 12:44:37 +00001063 }
1064 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +00001065}
1066
1067/*
drh4a324312001-12-21 14:30:42 +00001068** Designate the PRIMARY KEY for the table. pList is a list of names
1069** of columns that form the primary key. If pList is NULL, then the
1070** most recently added column of the table is the primary key.
1071**
1072** A table can have at most one primary key. If the table already has
1073** a primary key (and this is the second primary key) then create an
1074** error.
1075**
1076** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001077** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001078** field of the table under construction to be the index of the
1079** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1080** no INTEGER PRIMARY KEY.
1081**
1082** If the key is not an INTEGER PRIMARY KEY, then create a unique
1083** index for the key. No index is created for INTEGER PRIMARY KEYs.
1084*/
drh205f48e2004-11-05 00:43:11 +00001085void sqlite3AddPrimaryKey(
1086 Parse *pParse, /* Parsing context */
1087 ExprList *pList, /* List of field names to be indexed */
1088 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001089 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1090 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001091){
drh4a324312001-12-21 14:30:42 +00001092 Table *pTab = pParse->pNewTable;
1093 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001094 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +00001095 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001096 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001097 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001098 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001099 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001100 }
1101 pTab->hasPrimKey = 1;
1102 if( pList==0 ){
1103 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001104 pTab->aCol[iCol].isPrimKey = 1;
1105 }else{
danielk19770202b292004-06-09 09:55:16 +00001106 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001107 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001108 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1109 break;
1110 }
drh78100cc2003-08-23 22:40:53 +00001111 }
drh6e4fc2c2005-09-15 21:24:51 +00001112 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001113 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001114 }
drh4a324312001-12-21 14:30:42 +00001115 }
danielk19770202b292004-06-09 09:55:16 +00001116 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001117 }
1118 if( iCol>=0 && iCol<pTab->nCol ){
1119 zType = pTab->aCol[iCol].zType;
1120 }
drhfdd6e852005-12-16 01:06:16 +00001121 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1122 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001123 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001124 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001125 pTab->autoInc = autoInc;
1126 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001127#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001128 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1129 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001130#endif
drh4a324312001-12-21 14:30:42 +00001131 }else{
drh4d91a702006-01-04 15:54:36 +00001132 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001133 pList = 0;
drh4a324312001-12-21 14:30:42 +00001134 }
drhe0194f22003-02-26 13:52:51 +00001135
1136primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001137 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001138 return;
drh4a324312001-12-21 14:30:42 +00001139}
1140
1141/*
drhffe07b22005-11-03 00:41:17 +00001142** Add a new CHECK constraint to the table currently under construction.
1143*/
1144void sqlite3AddCheckConstraint(
1145 Parse *pParse, /* Parsing context */
1146 Expr *pCheckExpr /* The check expression */
1147){
1148#ifndef SQLITE_OMIT_CHECK
1149 Table *pTab = pParse->pNewTable;
1150 if( pTab ){
1151 /* The CHECK expression must be duplicated so that tokens refer
1152 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1153 ** statement */
1154 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
1155 }
1156#endif
1157 sqlite3ExprDelete(pCheckExpr);
1158}
1159
1160/*
drhd3d39e92004-05-20 22:16:29 +00001161** Set the collation function of the most recently parsed table column
1162** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001163*/
drhd3d39e92004-05-20 22:16:29 +00001164void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001165 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001166 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001167
drhd3d39e92004-05-20 22:16:29 +00001168 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001169 i = p->nCol-1;
1170
danielk1977b3bf5562006-01-10 17:58:23 +00001171 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1172 Index *pIdx;
1173 p->aCol[i].zColl = sqlite3StrNDup(zType, nType);
1174
1175 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1176 ** then an index may have been created on this column before the
1177 ** collation type was added. Correct this if it is the case.
1178 */
1179 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1180 assert( pIdx->nColumn==1 );
1181 if( pIdx->aiColumn[0]==i ){
1182 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001183 }
1184 }
1185 }
danielk19777cedc8d2004-06-10 10:50:08 +00001186}
1187
danielk1977466be562004-06-10 02:16:01 +00001188/*
1189** This function returns the collation sequence for database native text
1190** encoding identified by the string zName, length nName.
1191**
1192** If the requested collation sequence is not available, or not available
1193** in the database native encoding, the collation factory is invoked to
1194** request it. If the collation factory does not supply such a sequence,
1195** and the sequence is available in another text encoding, then that is
1196** returned instead.
1197**
1198** If no versions of the requested collations sequence are available, or
1199** another error occurs, NULL is returned and an error message written into
1200** pParse.
1201*/
danielk19770202b292004-06-09 09:55:16 +00001202CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001203 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001204 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001205 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001206 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001207
danielk1977b3bf5562006-01-10 17:58:23 +00001208 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001209 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001210 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1211 if( !pColl ){
1212 if( nName<0 ){
1213 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001214 }
danielk19774dade032005-05-25 10:45:10 +00001215 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1216 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001217 }
1218 }
1219
danielk19770202b292004-06-09 09:55:16 +00001220 return pColl;
1221}
1222
1223
drh8e2ca022002-06-17 17:07:19 +00001224/*
drh3f7d4e42004-07-24 14:35:58 +00001225** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001226**
1227** The schema cookie is used to determine when the schema for the
1228** database changes. After each schema change, the cookie value
1229** changes. When a process first reads the schema it records the
1230** cookie. Thereafter, whenever it goes to access the database,
1231** it checks the cookie to make sure the schema has not changed
1232** since it was last read.
1233**
1234** This plan is not completely bullet-proof. It is possible for
1235** the schema to change multiple times and for the cookie to be
1236** set back to prior value. But schema changes are infrequent
1237** and the probability of hitting the same cookie value is only
1238** 1 chance in 2^32. So we're safe enough.
1239*/
drh9bb575f2004-09-06 17:24:11 +00001240void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
danielk1977da184232006-01-05 11:34:32 +00001241 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001242 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001243}
1244
1245/*
drh969fa7c2002-02-18 18:30:32 +00001246** Measure the number of characters needed to output the given
1247** identifier. The number returned includes any quotes used
1248** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001249**
1250** The estimate is conservative. It might be larger that what is
1251** really needed.
drh969fa7c2002-02-18 18:30:32 +00001252*/
1253static int identLength(const char *z){
1254 int n;
drh17f71932002-02-21 12:01:27 +00001255 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001256 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001257 }
drh234c39d2004-07-24 03:30:47 +00001258 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001259}
1260
1261/*
1262** Write an identifier onto the end of the given string. Add
1263** quote characters as needed.
1264*/
drh4c755c02004-08-08 20:22:17 +00001265static void identPut(char *z, int *pIdx, char *zSignedIdent){
1266 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001267 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001268 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001269 for(j=0; zIdent[j]; j++){
1270 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1271 }
1272 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001273 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001274 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001275 for(j=0; zIdent[j]; j++){
1276 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001277 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001278 }
drh234c39d2004-07-24 03:30:47 +00001279 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001280 z[i] = 0;
1281 *pIdx = i;
1282}
1283
1284/*
1285** Generate a CREATE TABLE statement appropriate for the given
1286** table. Memory to hold the text of the statement is obtained
1287** from sqliteMalloc() and must be freed by the calling function.
1288*/
danielk1977da184232006-01-05 11:34:32 +00001289static char *createTableStmt(Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001290 int i, k, n;
1291 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001292 char *zSep, *zSep2, *zEnd, *z;
1293 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001294 n = 0;
drh234c39d2004-07-24 03:30:47 +00001295 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1296 n += identLength(pCol->zName);
1297 z = pCol->zType;
1298 if( z ){
1299 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001300 }
drh969fa7c2002-02-18 18:30:32 +00001301 }
1302 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001303 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001304 zSep = "";
1305 zSep2 = ",";
1306 zEnd = ")";
1307 }else{
1308 zSep = "\n ";
1309 zSep2 = ",\n ";
1310 zEnd = "\n)";
1311 }
drhe0bc4042002-06-25 01:09:11 +00001312 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001313 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001314 if( zStmt==0 ) return 0;
danielk1977da184232006-01-05 11:34:32 +00001315 strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001316 k = strlen(zStmt);
1317 identPut(zStmt, &k, p->zName);
1318 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001319 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001320 strcpy(&zStmt[k], zSep);
1321 k += strlen(&zStmt[k]);
1322 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001323 identPut(zStmt, &k, pCol->zName);
1324 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001325 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001326 strcpy(&zStmt[k], z);
1327 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001328 }
drh969fa7c2002-02-18 18:30:32 +00001329 }
1330 strcpy(&zStmt[k], zEnd);
1331 return zStmt;
1332}
1333
1334/*
drh75897232000-05-29 14:26:00 +00001335** This routine is called to report the final ")" that terminates
1336** a CREATE TABLE statement.
1337**
drhf57b3392001-10-08 13:22:32 +00001338** The table structure that other action routines have been building
1339** is added to the internal hash tables, assuming no errors have
1340** occurred.
drh75897232000-05-29 14:26:00 +00001341**
drh1d85d932004-02-14 23:05:52 +00001342** An entry for the table is made in the master table on disk, unless
1343** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001344** it means we are reading the sqlite_master table because we just
1345** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001346** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001347** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001348**
1349** If the pSelect argument is not NULL, it means that this routine
1350** was called to create a table generated from a
1351** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1352** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001353*/
danielk197719a8e7e2005-03-17 05:03:38 +00001354void sqlite3EndTable(
1355 Parse *pParse, /* Parse context */
1356 Token *pCons, /* The ',' token after the last column defn. */
1357 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1358 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1359){
drh75897232000-05-29 14:26:00 +00001360 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001361 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001362 int iDb;
drh75897232000-05-29 14:26:00 +00001363
danielk1977e501b892006-01-09 06:29:47 +00001364 if( (pEnd==0 && pSelect==0) ||
drh6f7adc82006-01-11 21:41:20 +00001365 pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001366 return;
1367 }
drh28037572000-08-02 13:47:41 +00001368 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001369 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001370
danielk1977517eb642004-06-07 10:00:31 +00001371 assert( !db->init.busy || !pSelect );
1372
danielk1977da184232006-01-05 11:34:32 +00001373 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1374
drhffe07b22005-11-03 00:41:17 +00001375#ifndef SQLITE_OMIT_CHECK
1376 /* Resolve names in all CHECK constraint expressions.
1377 */
1378 if( p->pCheck ){
1379 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1380 NameContext sNC; /* Name context for pParse->pNewTable */
1381
1382 memset(&sNC, 0, sizeof(sNC));
1383 memset(&sSrc, 0, sizeof(sSrc));
1384 sSrc.nSrc = 1;
1385 sSrc.a[0].zName = p->zName;
1386 sSrc.a[0].pTab = p;
1387 sSrc.a[0].iCursor = -1;
1388 sNC.pParse = pParse;
1389 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001390 sNC.isCheck = 1;
drhffe07b22005-11-03 00:41:17 +00001391 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1392 return;
1393 }
1394 }
1395#endif /* !defined(SQLITE_OMIT_CHECK) */
1396
drh1d85d932004-02-14 23:05:52 +00001397 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001398 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1399 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001400 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001401 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001402 */
drh1d85d932004-02-14 23:05:52 +00001403 if( db->init.busy ){
1404 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001405 }
1406
drhe3c41372001-09-17 20:25:58 +00001407 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001408 ** in the SQLITE_MASTER table of the database. The record number
1409 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001410 **
drhe0bc4042002-06-25 01:09:11 +00001411 ** If this is a TEMPORARY table, write the entry into the auxiliary
1412 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001413 */
drh1d85d932004-02-14 23:05:52 +00001414 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001415 int n;
drhd8bc7082000-06-07 23:51:50 +00001416 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001417 char *zType; /* "view" or "table" */
1418 char *zType2; /* "VIEW" or "TABLE" */
1419 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001420
danielk19774adee202004-05-08 08:23:19 +00001421 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001422 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001423
danielk1977e6efa742004-11-10 11:55:10 +00001424 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1425
drh4794f732004-11-05 17:17:50 +00001426 /* Create the rootpage for the new table and push it onto the stack.
1427 ** A view has no rootpage, so just push a zero onto the stack for
1428 ** views. Initialize zType at the same time.
1429 */
drh4ff6dfa2002-03-03 23:06:00 +00001430 if( p->pSelect==0 ){
1431 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001432 zType = "table";
1433 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001434#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001435 }else{
1436 /* A view */
drh4794f732004-11-05 17:17:50 +00001437 zType = "view";
1438 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001439#endif
drh4ff6dfa2002-03-03 23:06:00 +00001440 }
danielk1977517eb642004-06-07 10:00:31 +00001441
danielk1977517eb642004-06-07 10:00:31 +00001442 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1443 ** statement to populate the new table. The root-page number for the
1444 ** new table is on the top of the vdbe stack.
1445 **
1446 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1447 ** suitable state to query for the column names and types to be used
1448 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001449 **
1450 ** A shared-cache write-lock is not required to write to the new table,
1451 ** as a schema-lock must have already been obtained to create it. Since
1452 ** a schema-lock excludes all other database users, the write-lock would
1453 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001454 */
1455 if( pSelect ){
1456 Table *pSelTab;
1457 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
danielk1977da184232006-01-05 11:34:32 +00001458 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977517eb642004-06-07 10:00:31 +00001459 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1460 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001461 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001462 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1463 if( pParse->nErr==0 ){
1464 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1465 if( pSelTab==0 ) return;
1466 assert( p->aCol==0 );
1467 p->nCol = pSelTab->nCol;
1468 p->aCol = pSelTab->aCol;
1469 pSelTab->nCol = 0;
1470 pSelTab->aCol = 0;
1471 sqlite3DeleteTable(0, pSelTab);
1472 }
1473 }
drh4794f732004-11-05 17:17:50 +00001474
drh4794f732004-11-05 17:17:50 +00001475 /* Compute the complete text of the CREATE statement */
1476 if( pSelect ){
danielk1977da184232006-01-05 11:34:32 +00001477 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001478 }else{
drh97903fe2005-05-24 20:19:57 +00001479 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001480 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1481 }
1482
1483 /* A slot for the record has already been allocated in the
1484 ** SQLITE_MASTER table. We just need to update that slot with all
1485 ** the information we've collected. The rowid for the preallocated
1486 ** slot is the 2nd item on the stack. The top of the stack is the
1487 ** root page for the new table (or a 0 if this is a view).
1488 */
1489 sqlite3NestedParse(pParse,
1490 "UPDATE %Q.%s "
1491 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1492 "WHERE rowid=#1",
danielk1977da184232006-01-05 11:34:32 +00001493 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001494 zType,
1495 p->zName,
1496 p->zName,
1497 zStmt
1498 );
1499 sqliteFree(zStmt);
danielk1977da184232006-01-05 11:34:32 +00001500 sqlite3ChangeCookie(db, v, iDb);
drh2958a4e2004-11-12 03:56:15 +00001501
1502#ifndef SQLITE_OMIT_AUTOINCREMENT
1503 /* Check to see if we need to create an sqlite_sequence table for
1504 ** keeping track of autoincrement keys.
1505 */
1506 if( p->autoInc ){
danielk1977da184232006-01-05 11:34:32 +00001507 Db *pDb = &db->aDb[iDb];
1508 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001509 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001510 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1511 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001512 );
1513 }
1514 }
1515#endif
drh4794f732004-11-05 17:17:50 +00001516
1517 /* Reparse everything to update our internal data structures */
danielk1977da184232006-01-05 11:34:32 +00001518 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
drh234c39d2004-07-24 03:30:47 +00001519 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001520 }
drh17e9e292003-02-01 13:53:28 +00001521
drh2958a4e2004-11-12 03:56:15 +00001522
drh17e9e292003-02-01 13:53:28 +00001523 /* Add the table to the in-memory representation of the database.
1524 */
drh234c39d2004-07-24 03:30:47 +00001525 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001526 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001527 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001528 Schema *pSchema = p->pSchema;
danielk1977da184232006-01-05 11:34:32 +00001529 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001530 if( pOld ){
1531 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1532 return;
1533 }
danielk1977576ec6b2005-01-21 11:55:25 +00001534#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001535 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1536 int nTo = strlen(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001537 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1538 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001539 }
danielk1977576ec6b2005-01-21 11:55:25 +00001540#endif
drh17e9e292003-02-01 13:53:28 +00001541 pParse->pNewTable = 0;
1542 db->nTable++;
1543 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001544
1545#ifndef SQLITE_OMIT_ALTERTABLE
1546 if( !p->pSelect ){
1547 assert( !pSelect && pCons && pEnd );
1548 if( pCons->z==0 ) pCons = pEnd;
1549 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1550 }
1551#endif
drh17e9e292003-02-01 13:53:28 +00001552 }
drh75897232000-05-29 14:26:00 +00001553}
1554
drhb7f91642004-10-31 02:22:47 +00001555#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001556/*
drha76b5df2002-02-23 02:32:10 +00001557** The parser calls this routine in order to create a new VIEW
1558*/
danielk19774adee202004-05-08 08:23:19 +00001559void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001560 Parse *pParse, /* The parsing context */
1561 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001562 Token *pName1, /* The token that holds the name of the view */
1563 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001564 Select *pSelect, /* A SELECT statement that will become the new view */
1565 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001566){
drha76b5df2002-02-23 02:32:10 +00001567 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001568 int n;
drh4c755c02004-08-08 20:22:17 +00001569 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001570 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001571 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001572 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001573 int iDb;
drha76b5df2002-02-23 02:32:10 +00001574
drh7c3d64f2005-06-06 15:32:08 +00001575 if( pParse->nVar>0 ){
1576 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1577 sqlite3SelectDelete(pSelect);
1578 return;
1579 }
drhfaa59552005-12-29 23:33:54 +00001580 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1, 0);
drha76b5df2002-02-23 02:32:10 +00001581 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001582 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001583 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001584 return;
1585 }
danielk1977ef2cb632004-05-29 02:37:19 +00001586 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977da184232006-01-05 11:34:32 +00001587 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1588 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001589 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001590 ){
danielk19774adee202004-05-08 08:23:19 +00001591 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001592 return;
1593 }
drh174b6192002-12-03 02:22:52 +00001594
drh4b59ab52002-08-24 18:24:51 +00001595 /* Make a copy of the entire SELECT statement that defines the view.
1596 ** This will force all the Expr.token.z values to be dynamically
1597 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001598 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001599 */
danielk19774adee202004-05-08 08:23:19 +00001600 p->pSelect = sqlite3SelectDup(pSelect);
1601 sqlite3SelectDelete(pSelect);
drh6f7adc82006-01-11 21:41:20 +00001602 if( sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001603 return;
1604 }
drh1d85d932004-02-14 23:05:52 +00001605 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001606 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001607 }
drh4b59ab52002-08-24 18:24:51 +00001608
1609 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1610 ** the end.
1611 */
drha76b5df2002-02-23 02:32:10 +00001612 sEnd = pParse->sLastToken;
1613 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1614 sEnd.z += sEnd.n;
1615 }
1616 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001617 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001618 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001619 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1620 sEnd.z = &z[n-1];
1621 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001622
danielk19774adee202004-05-08 08:23:19 +00001623 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001624 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001625 return;
drh417be792002-03-03 18:59:40 +00001626}
drhb7f91642004-10-31 02:22:47 +00001627#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001628
drhb7f91642004-10-31 02:22:47 +00001629#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001630/*
1631** The Table structure pTable is really a VIEW. Fill in the names of
1632** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001633** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001634*/
danielk19774adee202004-05-08 08:23:19 +00001635int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001636 Table *pSelTab; /* A fake table from which we get the result set */
1637 Select *pSel; /* Copy of the SELECT that implements the view */
1638 int nErr = 0; /* Number of errors encountered */
1639 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001640
1641 assert( pTable );
1642
1643 /* A positive nCol means the columns names for this view are
1644 ** already known.
1645 */
1646 if( pTable->nCol>0 ) return 0;
1647
1648 /* A negative nCol is a special marker meaning that we are currently
1649 ** trying to compute the column names. If we enter this routine with
1650 ** a negative nCol, it means two or more views form a loop, like this:
1651 **
1652 ** CREATE VIEW one AS SELECT * FROM two;
1653 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001654 **
1655 ** Actually, this error is caught previously and so the following test
1656 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001657 */
drh85c23c62005-08-20 03:03:04 +00001658#if 0
drh417be792002-03-03 18:59:40 +00001659 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001660 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001661 return 1;
1662 }
drh85c23c62005-08-20 03:03:04 +00001663#endif
1664 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001665
1666 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001667 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1668 ** "*" elements in the results set of the view and will assign cursors
1669 ** to the elements of the FROM clause. But we do not want these changes
1670 ** to be permanent. So the computation is done on a copy of the SELECT
1671 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001672 */
drh9b3187e2005-01-18 14:45:47 +00001673 assert( pTable->pSelect );
1674 pSel = sqlite3SelectDup(pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001675 if( pSel ){
1676 n = pParse->nTab;
1677 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1678 pTable->nCol = -1;
1679 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1680 pParse->nTab = n;
1681 if( pSelTab ){
1682 assert( pTable->aCol==0 );
1683 pTable->nCol = pSelTab->nCol;
1684 pTable->aCol = pSelTab->aCol;
1685 pSelTab->nCol = 0;
1686 pSelTab->aCol = 0;
1687 sqlite3DeleteTable(0, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001688 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001689 }else{
1690 pTable->nCol = 0;
1691 nErr++;
1692 }
1693 sqlite3SelectDelete(pSel);
1694 } else {
drh417be792002-03-03 18:59:40 +00001695 nErr++;
1696 }
drh417be792002-03-03 18:59:40 +00001697 return nErr;
1698}
drhb7f91642004-10-31 02:22:47 +00001699#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001700
drhb7f91642004-10-31 02:22:47 +00001701#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001702/*
drh8bf8dc92003-05-17 17:35:10 +00001703** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001704*/
drh9bb575f2004-09-06 17:24:11 +00001705static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001706 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001707 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001708 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001709 Table *pTab = sqliteHashData(i);
1710 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001711 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001712 }
1713 }
drh8bf8dc92003-05-17 17:35:10 +00001714 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001715}
drhb7f91642004-10-31 02:22:47 +00001716#else
1717# define sqliteViewResetAll(A,B)
1718#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001719
drh75897232000-05-29 14:26:00 +00001720/*
danielk1977a0bf2652004-11-04 14:30:04 +00001721** This function is called by the VDBE to adjust the internal schema
1722** used by SQLite when the btree layer moves a table root page. The
1723** root-page of a table or index in database iDb has changed from iFrom
1724** to iTo.
1725*/
1726#ifndef SQLITE_OMIT_AUTOVACUUM
1727void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1728 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001729 Hash *pHash;
1730
1731 pHash = &pDb->pSchema->tblHash;
1732 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001733 Table *pTab = sqliteHashData(pElem);
1734 if( pTab->tnum==iFrom ){
1735 pTab->tnum = iTo;
1736 return;
1737 }
1738 }
danielk1977da184232006-01-05 11:34:32 +00001739 pHash = &pDb->pSchema->idxHash;
1740 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001741 Index *pIdx = sqliteHashData(pElem);
1742 if( pIdx->tnum==iFrom ){
1743 pIdx->tnum = iTo;
1744 return;
1745 }
1746 }
1747 assert(0);
1748}
1749#endif
1750
1751/*
1752** Write code to erase the table with root-page iTable from database iDb.
1753** Also write code to modify the sqlite_master table and internal schema
1754** if a root-page of another table is moved by the btree-layer whilst
1755** erasing iTable (this can happen with an auto-vacuum database).
1756*/
drh4e0cff62004-11-05 05:10:28 +00001757static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1758 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001759 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1760#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001761 /* OP_Destroy pushes an integer onto the stack. If this integer
1762 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001763 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001764 ** reflect this.
1765 **
1766 ** The "#0" in the SQL is a special constant that means whatever value
1767 ** is on the top of the stack. See sqlite3RegisterExpr().
1768 */
danielk197763e3e9f2004-11-05 09:19:27 +00001769 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001770 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001771 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001772#endif
1773}
1774
1775/*
1776** Write VDBE code to erase table pTab and all associated indices on disk.
1777** Code to update the sqlite_master tables and internal schema definitions
1778** in case a root-page belonging to another table is moved by the btree layer
1779** is also added (this can happen with an auto-vacuum database).
1780*/
drh4e0cff62004-11-05 05:10:28 +00001781static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001782#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001783 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001784 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1785 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001786 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001787 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001788 }
1789#else
1790 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1791 ** is not defined), then it is important to call OP_Destroy on the
1792 ** table and index root-pages in order, starting with the numerically
1793 ** largest root-page number. This guarantees that none of the root-pages
1794 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1795 ** following were coded:
1796 **
1797 ** OP_Destroy 4 0
1798 ** ...
1799 ** OP_Destroy 5 0
1800 **
1801 ** and root page 5 happened to be the largest root-page number in the
1802 ** database, then root page 5 would be moved to page 4 by the
1803 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1804 ** a free-list page.
1805 */
1806 int iTab = pTab->tnum;
1807 int iDestroyed = 0;
1808
1809 while( 1 ){
1810 Index *pIdx;
1811 int iLargest = 0;
1812
1813 if( iDestroyed==0 || iTab<iDestroyed ){
1814 iLargest = iTab;
1815 }
1816 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1817 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001818 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001819 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1820 iLargest = iIdx;
1821 }
1822 }
danielk1977da184232006-01-05 11:34:32 +00001823 if( iLargest==0 ){
1824 return;
1825 }else{
1826 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1827 destroyRootPage(pParse, iLargest, iDb);
1828 iDestroyed = iLargest;
1829 }
danielk1977a0bf2652004-11-04 14:30:04 +00001830 }
1831#endif
1832}
1833
1834/*
drh75897232000-05-29 14:26:00 +00001835** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001836** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001837*/
drha0733842005-12-29 01:11:36 +00001838void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001839 Table *pTab;
drh75897232000-05-29 14:26:00 +00001840 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001841 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001842 int iDb;
drh75897232000-05-29 14:26:00 +00001843
drh6f7adc82006-01-11 21:41:20 +00001844 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
1845 goto exit_drop_table;
1846 }
danielk1977a8858102004-05-28 12:11:21 +00001847 assert( pName->nSrc==1 );
1848 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1849
drha0733842005-12-29 01:11:36 +00001850 if( pTab==0 ){
1851 if( noErr ){
1852 sqlite3ErrorClear(pParse);
1853 }
1854 goto exit_drop_table;
1855 }
danielk1977da184232006-01-05 11:34:32 +00001856 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001857 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001858#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001859 {
1860 int code;
danielk1977da184232006-01-05 11:34:32 +00001861 const char *zTab = SCHEMA_TABLE(iDb);
1862 const char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001863 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001864 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001865 }
drhe5f9c642003-01-13 23:27:31 +00001866 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001867 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001868 code = SQLITE_DROP_TEMP_VIEW;
1869 }else{
1870 code = SQLITE_DROP_VIEW;
1871 }
1872 }else{
danielk197753c0f742005-03-29 03:10:59 +00001873 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001874 code = SQLITE_DROP_TEMP_TABLE;
1875 }else{
1876 code = SQLITE_DROP_TABLE;
1877 }
1878 }
danielk1977a8858102004-05-28 12:11:21 +00001879 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1880 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001881 }
danielk1977a8858102004-05-28 12:11:21 +00001882 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1883 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001884 }
drhe5f9c642003-01-13 23:27:31 +00001885 }
1886#endif
danielk1977da184232006-01-05 11:34:32 +00001887 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001888 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001889 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001890 }
danielk1977576ec6b2005-01-21 11:55:25 +00001891
1892#ifndef SQLITE_OMIT_VIEW
1893 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1894 ** on a table.
1895 */
danielk1977a8858102004-05-28 12:11:21 +00001896 if( isView && pTab->pSelect==0 ){
1897 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1898 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001899 }
danielk1977a8858102004-05-28 12:11:21 +00001900 if( !isView && pTab->pSelect ){
1901 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1902 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001903 }
danielk1977576ec6b2005-01-21 11:55:25 +00001904#endif
drh75897232000-05-29 14:26:00 +00001905
drh1ccde152000-06-17 13:12:39 +00001906 /* Generate code to remove the table from the master table
1907 ** on disk.
1908 */
danielk19774adee202004-05-08 08:23:19 +00001909 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001910 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001911 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001912 Db *pDb = &db->aDb[iDb];
1913 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001914
danielk19778e227872004-06-07 07:52:17 +00001915 /* Drop all triggers associated with the table being dropped. Code
1916 ** is generated to remove entries from sqlite_master and/or
1917 ** sqlite_temp_master if required.
1918 */
danielk1977a8858102004-05-28 12:11:21 +00001919 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001920 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00001921 assert( pTrigger->pSchema==pTab->pSchema ||
1922 pTrigger->pSchema==db->aDb[1].pSchema );
danielk19774adee202004-05-08 08:23:19 +00001923 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001924 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001925 }
drh8bf8dc92003-05-17 17:35:10 +00001926
danielk19774d36b812004-11-19 07:07:30 +00001927#ifndef SQLITE_OMIT_AUTOINCREMENT
1928 /* Remove any entries of the sqlite_sequence table associated with
1929 ** the table being dropped. This is done before the table is dropped
1930 ** at the btree level, in case the sqlite_sequence table needs to
1931 ** move as a result of the drop (can happen in auto-vacuum mode).
1932 */
1933 if( pTab->autoInc ){
1934 sqlite3NestedParse(pParse,
1935 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1936 pDb->zName, pTab->zName
1937 );
1938 }
1939#endif
1940
danielk19778e227872004-06-07 07:52:17 +00001941 /* Drop all SQLITE_MASTER table and index entries that refer to the
1942 ** table. The program name loops through the master table and deletes
1943 ** every row that refers to a table of the same name as the one being
1944 ** dropped. Triggers are handled seperately because a trigger can be
1945 ** created in the temp database that refers to a table in another
1946 ** database.
1947 */
drhf1974842004-11-05 03:56:00 +00001948 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001949 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001950 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001951 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001952 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001953 }
drh2958a4e2004-11-12 03:56:15 +00001954
danielk1977a21c6b62005-01-24 10:25:59 +00001955 /* Remove the table entry from SQLite's internal schema and modify
1956 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001957 */
1958 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00001959 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00001960 }
drhd24cc422003-03-27 12:51:24 +00001961 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001962
1963exit_drop_table:
1964 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001965}
1966
1967/*
drhc2eef3b2002-08-31 18:53:06 +00001968** This routine is called to create a new foreign key on the table
1969** currently under construction. pFromCol determines which columns
1970** in the current table point to the foreign key. If pFromCol==0 then
1971** connect the key to the last column inserted. pTo is the name of
1972** the table referred to. pToCol is a list of tables in the other
1973** pTo table that the foreign key points to. flags contains all
1974** information about the conflict resolution algorithms specified
1975** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1976**
1977** An FKey structure is created and added to the table currently
1978** under construction in the pParse->pNewTable field. The new FKey
1979** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001980** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001981**
1982** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001983** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001984*/
danielk19774adee202004-05-08 08:23:19 +00001985void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001986 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001987 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001988 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001989 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001990 int flags /* Conflict resolution algorithms. */
1991){
drhb7f91642004-10-31 02:22:47 +00001992#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001993 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001994 Table *p = pParse->pNewTable;
1995 int nByte;
1996 int i;
1997 int nCol;
1998 char *z;
drhc2eef3b2002-08-31 18:53:06 +00001999
2000 assert( pTo!=0 );
2001 if( p==0 || pParse->nErr ) goto fk_end;
2002 if( pFromCol==0 ){
2003 int iCol = p->nCol-1;
2004 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002005 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002006 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002007 " should reference only one column of table %T",
2008 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002009 goto fk_end;
2010 }
2011 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002012 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002013 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002014 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002015 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002016 goto fk_end;
2017 }else{
danielk19770202b292004-06-09 09:55:16 +00002018 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002019 }
2020 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2021 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002022 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00002023 nByte += strlen(pToCol->a[i].zName) + 1;
2024 }
2025 }
2026 pFKey = sqliteMalloc( nByte );
2027 if( pFKey==0 ) goto fk_end;
2028 pFKey->pFrom = p;
2029 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002030 z = (char*)&pFKey[1];
2031 pFKey->aCol = (struct sColMap*)z;
2032 z += sizeof(struct sColMap)*nCol;
2033 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002034 memcpy(z, pTo->z, pTo->n);
2035 z[pTo->n] = 0;
2036 z += pTo->n+1;
2037 pFKey->pNextTo = 0;
2038 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002039 if( pFromCol==0 ){
2040 pFKey->aCol[0].iFrom = p->nCol-1;
2041 }else{
2042 for(i=0; i<nCol; i++){
2043 int j;
2044 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002045 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002046 pFKey->aCol[i].iFrom = j;
2047 break;
2048 }
2049 }
2050 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002051 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002052 "unknown column \"%s\" in foreign key definition",
2053 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002054 goto fk_end;
2055 }
2056 }
2057 }
2058 if( pToCol ){
2059 for(i=0; i<nCol; i++){
2060 int n = strlen(pToCol->a[i].zName);
2061 pFKey->aCol[i].zCol = z;
2062 memcpy(z, pToCol->a[i].zName, n);
2063 z[n] = 0;
2064 z += n+1;
2065 }
2066 }
2067 pFKey->isDeferred = 0;
2068 pFKey->deleteConf = flags & 0xff;
2069 pFKey->updateConf = (flags >> 8 ) & 0xff;
2070 pFKey->insertConf = (flags >> 16 ) & 0xff;
2071
2072 /* Link the foreign key to the table as the last step.
2073 */
2074 p->pFKey = pFKey;
2075 pFKey = 0;
2076
2077fk_end:
2078 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00002079#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00002080 sqlite3ExprListDelete(pFromCol);
2081 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002082}
2083
2084/*
2085** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2086** clause is seen as part of a foreign key definition. The isDeferred
2087** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2088** The behavior of the most recently created foreign key is adjusted
2089** accordingly.
2090*/
danielk19774adee202004-05-08 08:23:19 +00002091void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002092#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002093 Table *pTab;
2094 FKey *pFKey;
2095 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2096 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002097#endif
drhc2eef3b2002-08-31 18:53:06 +00002098}
2099
2100/*
drh063336a2004-11-05 20:58:39 +00002101** Generate code that will erase and refill index *pIdx. This is
2102** used to initialize a newly created index or to recompute the
2103** content of an index in response to a REINDEX command.
2104**
2105** if memRootPage is not negative, it means that the index is newly
2106** created. The memory cell specified by memRootPage contains the
2107** root page number of the index. If memRootPage is negative, then
2108** the index already exists and must be cleared before being refilled and
2109** the root page number of the index is taken from pIndex->tnum.
2110*/
2111static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2112 Table *pTab = pIndex->pTable; /* The table that is indexed */
2113 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2114 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2115 int addr1; /* Address of top of loop */
2116 int tnum; /* Root page of index */
2117 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002118 KeyInfo *pKey; /* KeyInfo for index */
danielk1977da184232006-01-05 11:34:32 +00002119 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002120
danielk19771d54df82004-11-23 15:41:16 +00002121#ifndef SQLITE_OMIT_AUTHORIZATION
2122 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
danielk1977da184232006-01-05 11:34:32 +00002123 pParse->db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002124 return;
2125 }
2126#endif
2127
danielk1977c00da102006-01-07 13:21:04 +00002128 /* Require a write-lock on the table to perform this operation */
2129 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2130
drh063336a2004-11-05 20:58:39 +00002131 v = sqlite3GetVdbe(pParse);
2132 if( v==0 ) return;
2133 if( memRootPage>=0 ){
2134 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2135 tnum = 0;
2136 }else{
2137 tnum = pIndex->tnum;
danielk1977da184232006-01-05 11:34:32 +00002138 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002139 }
danielk1977da184232006-01-05 11:34:32 +00002140 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977b3bf5562006-01-10 17:58:23 +00002141 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2142 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
danielk1977c00da102006-01-07 13:21:04 +00002143 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh063336a2004-11-05 20:58:39 +00002144 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2145 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00002146 if( pIndex->onError!=OE_None ){
2147 int curaddr = sqlite3VdbeCurrentAddr(v);
2148 int addr2 = curaddr+4;
2149 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2150 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2151 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2152 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2153 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2154 "indexed columns are not unique", P3_STATIC);
2155 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002156 }
drh7f057c92005-06-24 03:53:06 +00002157 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002158 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002159 sqlite3VdbeJumpHere(v, addr1);
drh063336a2004-11-05 20:58:39 +00002160 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2161 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2162}
2163
2164/*
drh23bf66d2004-12-14 03:34:34 +00002165** Create a new index for an SQL table. pName1.pName2 is the name of the index
2166** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002167** be NULL for a primary key or an index that is created to satisfy a
2168** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002169** as the table to be indexed. pParse->pNewTable is a table that is
2170** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002171**
drh382c0242001-10-06 16:33:02 +00002172** pList is a list of columns to be indexed. pList will be NULL if this
2173** is a primary key or unique-constraint on the most recent column added
2174** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002175*/
danielk19774adee202004-05-08 08:23:19 +00002176void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002177 Parse *pParse, /* All information about this parse */
2178 Token *pName1, /* First part of index name. May be NULL */
2179 Token *pName2, /* Second part of index name. May be NULL */
2180 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002181 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002182 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2183 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
drhfdd6e852005-12-16 01:06:16 +00002184 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002185 int sortOrder, /* Sort order of primary key when pList==NULL */
2186 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002187){
drhfdd6e852005-12-16 01:06:16 +00002188 Table *pTab = 0; /* Table to be indexed */
2189 Index *pIndex = 0; /* The index to be created */
2190 char *zName = 0; /* Name of the index */
2191 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002192 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002193 Token nullId; /* Fake token for an empty ID list */
2194 DbFixer sFix; /* For assigning database names to pTable */
2195 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002196 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002197 Db *pDb; /* The specific table containing the indexed database */
2198 int iDb; /* Index of the database that is being written */
2199 Token *pName = 0; /* Unqualified name of the index to create */
2200 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002201 int nCol;
2202 int nExtra = 0;
2203 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002204
drh6f7adc82006-01-11 21:41:20 +00002205 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977e501b892006-01-09 06:29:47 +00002206 goto exit_create_index;
2207 }
drhdaffd0e2001-04-11 14:28:42 +00002208
drh75897232000-05-29 14:26:00 +00002209 /*
2210 ** Find the table that is to be indexed. Return early if not found.
2211 */
danielk1977cbb18d22004-05-28 11:37:27 +00002212 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002213
2214 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002215 ** to search for the table. 'Fix' the table name to this db
2216 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002217 */
2218 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002219 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002220 if( iDb<0 ) goto exit_create_index;
2221
danielk197753c0f742005-03-29 03:10:59 +00002222#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002223 /* If the index name was unqualified, check if the the table
2224 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002225 */
danielk1977ef2cb632004-05-29 02:37:19 +00002226 pTab = sqlite3SrcListLookup(pParse, pTblName);
danielk1977da184232006-01-05 11:34:32 +00002227 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977ef2cb632004-05-29 02:37:19 +00002228 iDb = 1;
2229 }
danielk197753c0f742005-03-29 03:10:59 +00002230#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002231
2232 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2233 sqlite3FixSrcList(&sFix, pTblName)
2234 ){
drh85c23c62005-08-20 03:03:04 +00002235 /* Because the parser constructs pTblName from a single identifier,
2236 ** sqlite3FixSrcList can never fail. */
2237 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002238 }
danielk1977ef2cb632004-05-29 02:37:19 +00002239 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2240 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002241 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002242 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002243 }else{
drhe3c41372001-09-17 20:25:58 +00002244 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002245 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002246 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002247 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002248 }
drhfdd6e852005-12-16 01:06:16 +00002249 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002250
drh75897232000-05-29 14:26:00 +00002251 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002252 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002253 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002254 goto exit_create_index;
2255 }
danielk1977576ec6b2005-01-21 11:55:25 +00002256#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002257 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002258 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002259 goto exit_create_index;
2260 }
danielk1977576ec6b2005-01-21 11:55:25 +00002261#endif
drh75897232000-05-29 14:26:00 +00002262
2263 /*
2264 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002265 ** index or table with the same name.
2266 **
2267 ** Exception: If we are reading the names of permanent indices from the
2268 ** sqlite_master table (because some other process changed the schema) and
2269 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002270 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002271 **
2272 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002273 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2274 ** own name.
drh75897232000-05-29 14:26:00 +00002275 */
danielk1977d8123362004-06-12 09:25:12 +00002276 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002277 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002278 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002279 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002280 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002281 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002282 }
danielk1977d8123362004-06-12 09:25:12 +00002283 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002284 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002285 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
drh4d91a702006-01-04 15:54:36 +00002286 if( !ifNotExist ){
2287 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2288 }
danielk1977d8123362004-06-12 09:25:12 +00002289 goto exit_create_index;
2290 }
drh4f26bb62005-09-08 14:17:20 +00002291 if( sqlite3FindTable(db, zName, 0)!=0 ){
danielk1977d8123362004-06-12 09:25:12 +00002292 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2293 goto exit_create_index;
2294 }
drhe3c41372001-09-17 20:25:58 +00002295 }
danielk1977a21c6b62005-01-24 10:25:59 +00002296 }else{
drhadbca9c2001-09-27 15:11:53 +00002297 char zBuf[30];
2298 int n;
2299 Index *pLoop;
2300 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002301 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002302 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002303 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002304 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002305 }
2306
drhe5f9c642003-01-13 23:27:31 +00002307 /* Check for authorization to create an index.
2308 */
2309#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002310 {
drhfdd6e852005-12-16 01:06:16 +00002311 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002312 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002313 goto exit_create_index;
2314 }
2315 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002316 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002317 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002318 goto exit_create_index;
2319 }
drhe5f9c642003-01-13 23:27:31 +00002320 }
2321#endif
2322
drh75897232000-05-29 14:26:00 +00002323 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002324 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002325 ** So create a fake list to simulate this.
2326 */
2327 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002328 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2329 nullId.n = strlen((char*)nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002330 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002331 if( pList==0 ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002332 pList->a[0].sortOrder = sortOrder;
drh75897232000-05-29 14:26:00 +00002333 }
2334
danielk1977b3bf5562006-01-10 17:58:23 +00002335 /* Figure out how many bytes of space are required to store explicitly
2336 ** specified collation sequence names.
2337 */
2338 for(i=0; i<pList->nExpr; i++){
2339 Expr *pExpr = pList->a[i].pExpr;
2340 if( pExpr ){
2341 nExtra += (1 + strlen(pExpr->pColl->zName));
2342 }
2343 }
2344
drh75897232000-05-29 14:26:00 +00002345 /*
2346 ** Allocate the index structure.
2347 */
drhfdd6e852005-12-16 01:06:16 +00002348 nName = strlen(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002349 nCol = pList->nExpr;
2350 pIndex = sqliteMalloc(
2351 sizeof(Index) + /* Index structure */
2352 sizeof(int)*nCol + /* Index.aiColumn */
2353 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2354 sizeof(char *)*nCol + /* Index.azColl */
2355 sizeof(u8)*nCol + /* Index.aSortOrder */
2356 nName + 1 + /* Index.zName */
2357 nExtra /* Collation sequence names */
2358 );
drh6f7adc82006-01-11 21:41:20 +00002359 if( sqlite3ThreadDataReadOnly()->mallocFailed ) goto exit_create_index;
danielk1977b3bf5562006-01-10 17:58:23 +00002360 pIndex->aiColumn = (int *)(&pIndex[1]);
2361 pIndex->aiRowEst = (int *)(&pIndex->aiColumn[nCol]);
2362 pIndex->azColl = (char **)(&pIndex->aiRowEst[nCol+1]);
2363 pIndex->aSortOrder = (u8 *)(&pIndex->azColl[nCol]);
2364 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2365 zExtra = (char *)(&pIndex->zName[nName+1]);
drh75897232000-05-29 14:26:00 +00002366 strcpy(pIndex->zName, zName);
2367 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002368 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002369 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002370 pIndex->autoIndex = pName==0;
danielk1977da184232006-01-05 11:34:32 +00002371 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002372
drhfdd6e852005-12-16 01:06:16 +00002373 /* Check to see if we should honor DESC requests on index columns
2374 */
danielk1977da184232006-01-05 11:34:32 +00002375 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002376 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002377 }else{
2378 sortOrderMask = 0; /* Ignore DESC */
2379 }
2380
drh1ccde152000-06-17 13:12:39 +00002381 /* Scan the names of the columns of the table to be indexed and
2382 ** load the column indices into the Index structure. Report an error
2383 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002384 */
drhfdd6e852005-12-16 01:06:16 +00002385 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2386 const char *zColName = pListItem->zName;
2387 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002388 int requestedSortOrder;
danielk1977b3bf5562006-01-10 17:58:23 +00002389 char *zColl; /* Collation sequence */
2390
drhfdd6e852005-12-16 01:06:16 +00002391 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2392 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002393 }
2394 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002395 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002396 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002397 goto exit_create_index;
2398 }
drh967e8b72000-06-21 13:59:10 +00002399 pIndex->aiColumn[i] = j;
drhfdd6e852005-12-16 01:06:16 +00002400 if( pListItem->pExpr ){
2401 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002402 zColl = zExtra;
2403 strcpy(zExtra, pListItem->pExpr->pColl->zName);
2404 zExtra += (strlen(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002405 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002406 zColl = pTab->aCol[j].zColl;
2407 if( !zColl ){
2408 zColl = db->pDfltColl->zName;
2409 }
danielk19770202b292004-06-09 09:55:16 +00002410 }
danielk1977b3bf5562006-01-10 17:58:23 +00002411 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002412 goto exit_create_index;
2413 }
danielk1977b3bf5562006-01-10 17:58:23 +00002414 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002415 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
danielk1977b3bf5562006-01-10 17:58:23 +00002416 pIndex->aSortOrder[i] = requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002417 }
drh51147ba2005-07-23 22:59:55 +00002418 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002419
danielk1977d8123362004-06-12 09:25:12 +00002420 if( pTab==pParse->pNewTable ){
2421 /* This routine has been called to create an automatic index as a
2422 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2423 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2424 ** i.e. one of:
2425 **
2426 ** CREATE TABLE t(x PRIMARY KEY, y);
2427 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2428 **
2429 ** Either way, check to see if the table already has such an index. If
2430 ** so, don't bother creating this one. This only applies to
2431 ** automatically created indices. Users can do as they wish with
2432 ** explicit indices.
2433 */
2434 Index *pIdx;
2435 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2436 int k;
2437 assert( pIdx->onError!=OE_None );
2438 assert( pIdx->autoIndex );
2439 assert( pIndex->onError!=OE_None );
2440
2441 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2442 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002443 const char *z1 = pIdx->azColl[k];
2444 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002445 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002446 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2447 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002448 }
2449 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002450 if( pIdx->onError!=pIndex->onError ){
2451 /* This constraint creates the same index as a previous
2452 ** constraint specified somewhere in the CREATE TABLE statement.
2453 ** However the ON CONFLICT clauses are different. If both this
2454 ** constraint and the previous equivalent constraint have explicit
2455 ** ON CONFLICT clauses this is an error. Otherwise, use the
2456 ** explicitly specified behaviour for the index.
2457 */
2458 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2459 sqlite3ErrorMsg(pParse,
2460 "conflicting ON CONFLICT clauses specified", 0);
2461 }
2462 if( pIdx->onError==OE_Default ){
2463 pIdx->onError = pIndex->onError;
2464 }
2465 }
danielk1977d8123362004-06-12 09:25:12 +00002466 goto exit_create_index;
2467 }
2468 }
2469 }
2470
drh75897232000-05-29 14:26:00 +00002471 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002472 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002473 */
drh234c39d2004-07-24 03:30:47 +00002474 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002475 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002476 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drh3c8bf552003-07-01 18:13:14 +00002477 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002478 if( p ){
2479 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002480 goto exit_create_index;
2481 }
drh5e00f6c2001-09-13 13:46:56 +00002482 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002483 if( pTblName!=0 ){
2484 pIndex->tnum = db->init.newTnum;
2485 }
drhd78eeee2001-09-13 16:18:53 +00002486 }
2487
drh1d85d932004-02-14 23:05:52 +00002488 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002489 ** involves writing the index into the master table and filling in the
2490 ** index with the current table contents.
2491 **
drh1d85d932004-02-14 23:05:52 +00002492 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2493 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002494 ** CREATE INDEX statements are read out of the master table. In
2495 ** the latter case the index already exists on disk, which is why
2496 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002497 **
danielk1977cbb18d22004-05-28 11:37:27 +00002498 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002499 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2500 ** has just been created, it contains no data and the index initialization
2501 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002502 */
drh1d85d932004-02-14 23:05:52 +00002503 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002504 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002505 char *zStmt;
2506 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002507
danielk19774adee202004-05-08 08:23:19 +00002508 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002509 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002510
drhfdd6e852005-12-16 01:06:16 +00002511
drh063336a2004-11-05 20:58:39 +00002512 /* Create the rootpage for the index
2513 */
drhaee128d2005-02-14 20:48:18 +00002514 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002515 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002516 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2517
2518 /* Gather the complete text of the CREATE INDEX statement into
2519 ** the zStmt variable
2520 */
drhe0bc4042002-06-25 01:09:11 +00002521 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002522 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002523 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002524 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002525 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002526 pName->z);
2527 }else{
2528 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002529 /* zStmt = sqlite3MPrintf(""); */
2530 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002531 }
drh063336a2004-11-05 20:58:39 +00002532
2533 /* Add an entry in sqlite_master for this index
2534 */
2535 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002536 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002537 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2538 pIndex->zName,
2539 pTab->zName,
2540 zStmt
2541 );
2542 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2543 sqliteFree(zStmt);
2544
danielk1977a21c6b62005-01-24 10:25:59 +00002545 /* Fill the index with data and reparse the schema. Code an OP_Expire
2546 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002547 */
danielk1977cbb18d22004-05-28 11:37:27 +00002548 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002549 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002550 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002551 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2552 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002553 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002554 }
drh75897232000-05-29 14:26:00 +00002555 }
2556
danielk1977d8123362004-06-12 09:25:12 +00002557 /* When adding an index to the list of indices for a table, make
2558 ** sure all indices labeled OE_Replace come after all those labeled
2559 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2560 ** and INSERT.
2561 */
drh234c39d2004-07-24 03:30:47 +00002562 if( db->init.busy || pTblName==0 ){
2563 if( onError!=OE_Replace || pTab->pIndex==0
2564 || pTab->pIndex->onError==OE_Replace){
2565 pIndex->pNext = pTab->pIndex;
2566 pTab->pIndex = pIndex;
2567 }else{
2568 Index *pOther = pTab->pIndex;
2569 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2570 pOther = pOther->pNext;
2571 }
2572 pIndex->pNext = pOther->pNext;
2573 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002574 }
drh234c39d2004-07-24 03:30:47 +00002575 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002576 }
danielk1977d8123362004-06-12 09:25:12 +00002577
drh75897232000-05-29 14:26:00 +00002578 /* Clean up before exiting */
2579exit_create_index:
drh956bc922004-07-24 17:38:29 +00002580 if( pIndex ){
2581 freeIndex(pIndex);
2582 }
danielk19770202b292004-06-09 09:55:16 +00002583 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002584 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002585 sqliteFree(zName);
2586 return;
2587}
2588
2589/*
drhd28bcb32005-12-21 14:43:11 +00002590** Generate code to make sure the file format number is at least minFormat.
2591** The generated code will increase the file format number if necessary.
2592*/
2593void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2594 Vdbe *v;
2595 v = sqlite3GetVdbe(pParse);
2596 if( v ){
2597 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
2598 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2599 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
2600 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2601 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
2602 }
2603}
2604
2605/*
drh51147ba2005-07-23 22:59:55 +00002606** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002607** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002608**
2609** aiRowEst[0] is suppose to contain the number of elements in the index.
2610** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2611** number of rows in the table that match any particular value of the
2612** first column of the index. aiRowEst[2] is an estimate of the number
2613** of rows that match any particular combiniation of the first 2 columns
2614** of the index. And so forth. It must always be the case that
2615*
2616** aiRowEst[N]<=aiRowEst[N-1]
2617** aiRowEst[N]>=1
2618**
2619** Apart from that, we have little to go on besides intuition as to
2620** how aiRowEst[] should be initialized. The numbers generated here
2621** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002622*/
2623void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002624 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002625 int i;
drh28c4cf42005-07-27 20:41:43 +00002626 assert( a!=0 );
2627 a[0] = 1000000;
drh3adc9ce2005-07-28 16:51:51 +00002628 for(i=pIdx->nColumn; i>=1; i--){
2629 a[i] = 10;
drh28c4cf42005-07-27 20:41:43 +00002630 }
2631 if( pIdx->onError!=OE_None ){
2632 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002633 }
2634}
2635
2636/*
drh74e24cd2002-01-09 03:19:59 +00002637** This routine will drop an existing named index. This routine
2638** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002639*/
drh4d91a702006-01-04 15:54:36 +00002640void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002641 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002642 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002643 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002644 int iDb;
drh75897232000-05-29 14:26:00 +00002645
drh6f7adc82006-01-11 21:41:20 +00002646 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002647 goto exit_drop_index;
2648 }
drhd24cc422003-03-27 12:51:24 +00002649 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002650 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2651 goto exit_drop_index;
2652 }
danielk19774adee202004-05-08 08:23:19 +00002653 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002654 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002655 if( !ifExists ){
2656 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2657 }
drha6ecd332004-06-10 00:29:09 +00002658 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002659 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002660 }
drh485b39b2002-07-13 03:11:52 +00002661 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002662 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002663 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002664 goto exit_drop_index;
2665 }
danielk1977da184232006-01-05 11:34:32 +00002666 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002667#ifndef SQLITE_OMIT_AUTHORIZATION
2668 {
2669 int code = SQLITE_DROP_INDEX;
2670 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002671 const char *zDb = db->aDb[iDb].zName;
2672 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002673 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002674 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002675 }
danielk1977da184232006-01-05 11:34:32 +00002676 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002677 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002678 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002679 }
drhed6c8672003-01-12 18:02:16 +00002680 }
drhe5f9c642003-01-13 23:27:31 +00002681#endif
drh75897232000-05-29 14:26:00 +00002682
2683 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002684 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002685 if( v ){
drhb17131a2004-11-05 22:18:49 +00002686 sqlite3NestedParse(pParse,
2687 "DELETE FROM %Q.%s WHERE name=%Q",
2688 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2689 pIndex->zName
2690 );
2691 sqlite3ChangeCookie(db, v, iDb);
2692 destroyRootPage(pParse, pIndex->tnum, iDb);
2693 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002694 }
2695
drhd24cc422003-03-27 12:51:24 +00002696exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002697 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002698}
2699
2700/*
drh13449892005-09-07 21:22:45 +00002701** ppArray points into a structure where there is an array pointer
2702** followed by two integers. The first integer is the
2703** number of elements in the structure array. The second integer
2704** is the number of allocated slots in the array.
2705**
2706** In other words, the structure looks something like this:
2707**
2708** struct Example1 {
2709** struct subElem *aEntry;
2710** int nEntry;
2711** int nAlloc;
2712** }
2713**
2714** The pnEntry parameter points to the equivalent of Example1.nEntry.
2715**
2716** This routine allocates a new slot in the array, zeros it out,
2717** and returns its index. If malloc fails a negative number is returned.
2718**
2719** szEntry is the sizeof of a single array entry. initSize is the
2720** number of array entries allocated on the initial allocation.
2721*/
2722int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
2723 char *p;
2724 int *an = (int*)&ppArray[1];
2725 if( an[0]>=an[1] ){
2726 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002727 int newSize;
2728 newSize = an[1]*2 + initSize;
2729 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002730 if( pNew==0 ){
2731 return -1;
2732 }
drh5360ad32005-09-08 00:13:27 +00002733 an[1] = newSize;
drh13449892005-09-07 21:22:45 +00002734 *ppArray = pNew;
2735 }
2736 p = *ppArray;
2737 memset(&p[an[0]*szEntry], 0, szEntry);
2738 return an[0]++;
2739}
2740
2741/*
drh75897232000-05-29 14:26:00 +00002742** Append a new element to the given IdList. Create a new IdList if
2743** need be.
drhdaffd0e2001-04-11 14:28:42 +00002744**
2745** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002746*/
danielk19774adee202004-05-08 08:23:19 +00002747IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002748 int i;
drh75897232000-05-29 14:26:00 +00002749 if( pList==0 ){
2750 pList = sqliteMalloc( sizeof(IdList) );
2751 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002752 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002753 }
drh13449892005-09-07 21:22:45 +00002754 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
2755 if( i<0 ){
2756 sqlite3IdListDelete(pList);
2757 return 0;
drh75897232000-05-29 14:26:00 +00002758 }
drh13449892005-09-07 21:22:45 +00002759 pList->a[i].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002760 return pList;
2761}
2762
2763/*
drhfe05af82005-07-21 03:14:59 +00002764** Delete an IdList.
2765*/
2766void sqlite3IdListDelete(IdList *pList){
2767 int i;
2768 if( pList==0 ) return;
2769 for(i=0; i<pList->nId; i++){
2770 sqliteFree(pList->a[i].zName);
2771 }
2772 sqliteFree(pList->a);
2773 sqliteFree(pList);
2774}
2775
2776/*
2777** Return the index in pList of the identifier named zId. Return -1
2778** if not found.
2779*/
2780int sqlite3IdListIndex(IdList *pList, const char *zName){
2781 int i;
2782 if( pList==0 ) return -1;
2783 for(i=0; i<pList->nId; i++){
2784 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2785 }
2786 return -1;
2787}
2788
2789/*
drhad3cab52002-05-24 02:04:32 +00002790** Append a new table name to the given SrcList. Create a new SrcList if
2791** need be. A new entry is created in the SrcList even if pToken is NULL.
2792**
2793** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002794**
2795** If pDatabase is not null, it means that the table has an optional
2796** database name prefix. Like this: "database.table". The pDatabase
2797** points to the table name and the pTable points to the database name.
2798** The SrcList.a[].zName field is filled with the table name which might
2799** come from pTable (if pDatabase is NULL) or from pDatabase.
2800** SrcList.a[].zDatabase is filled with the database name from pTable,
2801** or with NULL if no database is specified.
2802**
2803** In other words, if call like this:
2804**
danielk19774adee202004-05-08 08:23:19 +00002805** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002806**
2807** Then B is a table name and the database name is unspecified. If called
2808** like this:
2809**
danielk19774adee202004-05-08 08:23:19 +00002810** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002811**
2812** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002813*/
danielk19774adee202004-05-08 08:23:19 +00002814SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002815 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002816 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002817 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002818 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002819 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002820 }
drh4305d102003-07-30 12:34:12 +00002821 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002822 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002823 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002824 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002825 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002826 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002827 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002828 return 0;
2829 }
drh113088e2003-03-20 01:16:58 +00002830 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002831 }
drha99db3b2004-06-19 14:49:12 +00002832 pItem = &pList->a[pList->nSrc];
2833 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002834 if( pDatabase && pDatabase->z==0 ){
2835 pDatabase = 0;
2836 }
2837 if( pDatabase && pTable ){
2838 Token *pTemp = pDatabase;
2839 pDatabase = pTable;
2840 pTable = pTemp;
2841 }
drha99db3b2004-06-19 14:49:12 +00002842 pItem->zName = sqlite3NameFromToken(pTable);
2843 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2844 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002845 pList->nSrc++;
2846 return pList;
2847}
2848
2849/*
drh63eb5f22003-04-29 16:20:44 +00002850** Assign cursors to all tables in a SrcList
2851*/
danielk19774adee202004-05-08 08:23:19 +00002852void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002853 int i;
drh9b3187e2005-01-18 14:45:47 +00002854 struct SrcList_item *pItem;
drh6f7adc82006-01-11 21:41:20 +00002855 assert(pList || sqlite3ThreadDataReadOnly()->mallocFailed);
danielk1977261919c2005-12-06 12:52:59 +00002856 if( pList ){
2857 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2858 if( pItem->iCursor>=0 ) break;
2859 pItem->iCursor = pParse->nTab++;
2860 if( pItem->pSelect ){
2861 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2862 }
drh63eb5f22003-04-29 16:20:44 +00002863 }
2864 }
2865}
2866
2867/*
drh75897232000-05-29 14:26:00 +00002868** Add an alias to the last identifier on the given identifier list.
2869*/
danielk19774adee202004-05-08 08:23:19 +00002870void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002871 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002872 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002873 }
2874}
2875
2876/*
drhad3cab52002-05-24 02:04:32 +00002877** Delete an entire SrcList including all its substructure.
2878*/
danielk19774adee202004-05-08 08:23:19 +00002879void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002880 int i;
drhbe5c89a2004-07-26 00:31:09 +00002881 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002882 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002883 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2884 sqliteFree(pItem->zDatabase);
2885 sqliteFree(pItem->zName);
2886 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002887 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002888 sqlite3SelectDelete(pItem->pSelect);
2889 sqlite3ExprDelete(pItem->pOn);
2890 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002891 }
drh75897232000-05-29 14:26:00 +00002892 sqliteFree(pList);
2893}
2894
drh982cef72000-05-30 16:27:03 +00002895/*
drhc4a3c772001-04-04 11:48:57 +00002896** Begin a transaction
2897*/
drh684917c2004-10-05 02:41:42 +00002898void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002899 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002900 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002901 int i;
drh5e00f6c2001-09-13 13:46:56 +00002902
drh001bbcb2003-03-19 03:14:00 +00002903 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002904 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002905 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002906
2907 v = sqlite3GetVdbe(pParse);
2908 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002909 if( type!=TK_DEFERRED ){
2910 for(i=0; i<db->nDb; i++){
2911 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2912 }
2913 }
danielk19771d850a72004-05-31 08:26:49 +00002914 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002915}
2916
2917/*
2918** Commit a transaction
2919*/
danielk19774adee202004-05-08 08:23:19 +00002920void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002921 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002922 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002923
drh001bbcb2003-03-19 03:14:00 +00002924 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002925 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002926 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002927
2928 v = sqlite3GetVdbe(pParse);
2929 if( v ){
2930 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002931 }
drhc4a3c772001-04-04 11:48:57 +00002932}
2933
2934/*
2935** Rollback a transaction
2936*/
danielk19774adee202004-05-08 08:23:19 +00002937void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002938 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002939 Vdbe *v;
2940
drh001bbcb2003-03-19 03:14:00 +00002941 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002942 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002943 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002944
danielk19774adee202004-05-08 08:23:19 +00002945 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002946 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002947 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002948 }
drhc4a3c772001-04-04 11:48:57 +00002949}
drhf57b14a2001-09-14 18:54:08 +00002950
2951/*
drhdc3ff9c2004-08-18 02:10:15 +00002952** Make sure the TEMP database is open and available for use. Return
2953** the number of errors. Leave any error messages in the pParse structure.
2954*/
2955static int sqlite3OpenTempDatabase(Parse *pParse){
2956 sqlite3 *db = pParse->db;
2957 if( db->aDb[1].pBt==0 && !pParse->explain ){
2958 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2959 if( rc!=SQLITE_OK ){
2960 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2961 "file for storing temporary tables");
2962 pParse->rc = rc;
2963 return 1;
2964 }
2965 if( db->flags & !db->autoCommit ){
2966 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2967 if( rc!=SQLITE_OK ){
2968 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2969 "the temporary database file");
2970 pParse->rc = rc;
2971 return 1;
2972 }
2973 }
danielk197714db2662006-01-09 16:12:04 +00002974 assert( db->aDb[1].pSchema );
drhdc3ff9c2004-08-18 02:10:15 +00002975 }
2976 return 0;
2977}
2978
2979/*
drh80242052004-06-09 00:48:12 +00002980** Generate VDBE code that will verify the schema cookie and start
2981** a read-transaction for all named database files.
2982**
2983** It is important that all schema cookies be verified and all
2984** read transactions be started before anything else happens in
2985** the VDBE program. But this routine can be called after much other
2986** code has been generated. So here is what we do:
2987**
drhc275b4e2004-07-19 17:25:24 +00002988** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002989** will jump to a subroutine at the end of the program. Then we
2990** record every database that needs its schema verified in the
2991** pParse->cookieMask field. Later, after all other code has been
2992** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002993** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002994** will be made to point to that subroutine. The generation of the
2995** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002996**
2997** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2998** schema on any databases. This can be used to position the OP_Goto
2999** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003000*/
danielk19774adee202004-05-08 08:23:19 +00003001void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003002 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003003 Vdbe *v;
3004 int mask;
3005
3006 v = sqlite3GetVdbe(pParse);
3007 if( v==0 ) return; /* This only happens if there was a prior error */
3008 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003009 if( pParse->cookieGoto==0 ){
3010 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003011 }
drhc275b4e2004-07-19 17:25:24 +00003012 if( iDb>=0 ){
3013 assert( iDb<db->nDb );
3014 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3015 assert( iDb<32 );
3016 mask = 1<<iDb;
3017 if( (pParse->cookieMask & mask)==0 ){
3018 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003019 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003020 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003021 sqlite3OpenTempDatabase(pParse);
3022 }
drhc275b4e2004-07-19 17:25:24 +00003023 }
drh001bbcb2003-03-19 03:14:00 +00003024 }
drh001bbcb2003-03-19 03:14:00 +00003025}
3026
3027/*
drh1c928532002-01-31 15:54:21 +00003028** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003029** might change the database.
3030**
3031** This routine starts a new transaction if we are not already within
3032** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003033** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003034** be set for operations that might fail (due to a constraint) part of
3035** the way through and which will need to undo some writes without having to
3036** rollback the whole transaction. For operations where all constraints
3037** can be checked before any changes are made to the database, it is never
3038** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003039**
drh8bf8dc92003-05-17 17:35:10 +00003040** Only database iDb and the temp database are made writable by this call.
3041** If iDb==0, then the main and temp databases are made writable. If
3042** iDb==1 then only the temp database is made writable. If iDb>1 then the
3043** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003044*/
drh7f0f12e2004-05-21 13:39:50 +00003045void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003046 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003047 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003048 sqlite3CodeVerifySchema(pParse, iDb);
3049 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003050 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00003051 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00003052 }
danielk197753c0f742005-03-29 03:10:59 +00003053 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003054 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003055 }
3056}
3057
drh4343fea2004-11-05 23:46:15 +00003058/*
3059** Check to see if pIndex uses the collating sequence pColl. Return
3060** true if it does and false if it does not.
3061*/
3062#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003063static int collationMatch(const char *zColl, Index *pIndex){
3064 int i;
3065 for(i=0; i<pIndex->nColumn; i++){
3066 const char *z = pIndex->azColl[i];
3067 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3068 return 1;
3069 }
drh4343fea2004-11-05 23:46:15 +00003070 }
3071 return 0;
3072}
3073#endif
3074
3075/*
3076** Recompute all indices of pTab that use the collating sequence pColl.
3077** If pColl==0 then recompute all indices of pTab.
3078*/
3079#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003080static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003081 Index *pIndex; /* An index associated with pTab */
3082
3083 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003084 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003085 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3086 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003087 sqlite3RefillIndex(pParse, pIndex, -1);
3088 }
3089 }
3090}
3091#endif
3092
3093/*
3094** Recompute all indices of all tables in all databases where the
3095** indices use the collating sequence pColl. If pColl==0 then recompute
3096** all indices everywhere.
3097*/
3098#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003099static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003100 Db *pDb; /* A single database */
3101 int iDb; /* The database index number */
3102 sqlite3 *db = pParse->db; /* The database connection */
3103 HashElem *k; /* For looping over tables in pDb */
3104 Table *pTab; /* A table in the database */
3105
3106 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3107 if( pDb==0 ) continue;
danielk1977da184232006-01-05 11:34:32 +00003108 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003109 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003110 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003111 }
3112 }
3113}
3114#endif
3115
3116/*
drheee46cf2004-11-06 00:02:48 +00003117** Generate code for the REINDEX command.
3118**
3119** REINDEX -- 1
3120** REINDEX <collation> -- 2
3121** REINDEX ?<database>.?<tablename> -- 3
3122** REINDEX ?<database>.?<indexname> -- 4
3123**
3124** Form 1 causes all indices in all attached databases to be rebuilt.
3125** Form 2 rebuilds all indices in all databases that use the named
3126** collating function. Forms 3 and 4 rebuild the named index or all
3127** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003128*/
3129#ifndef SQLITE_OMIT_REINDEX
3130void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3131 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3132 char *z; /* Name of a table or index */
3133 const char *zDb; /* Name of the database */
3134 Table *pTab; /* A table in the database */
3135 Index *pIndex; /* An index associated with pTab */
3136 int iDb; /* The database index number */
3137 sqlite3 *db = pParse->db; /* The database connection */
3138 Token *pObjName; /* Name of the table or index to be reindexed */
3139
danielk197733a5edc2005-01-27 00:22:02 +00003140 /* Read the database schema. If an error occurs, leave an error message
3141 ** and code in pParse and return NULL. */
3142 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003143 return;
danielk197733a5edc2005-01-27 00:22:02 +00003144 }
3145
drhe497f002004-11-07 13:01:49 +00003146 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003147 reindexDatabases(pParse, 0);
3148 return;
drhe497f002004-11-07 13:01:49 +00003149 }else if( pName2==0 || pName2->z==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003150 assert( pName1->z );
danielk197714db2662006-01-09 16:12:04 +00003151 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
drh4343fea2004-11-05 23:46:15 +00003152 if( pColl ){
danielk1977b3bf5562006-01-10 17:58:23 +00003153 char *z = sqlite3StrNDup(pName1->z, pName1->n);
3154 if( z ){
3155 reindexDatabases(pParse, z);
3156 sqliteFree(z);
3157 }
drh4343fea2004-11-05 23:46:15 +00003158 return;
3159 }
3160 }
3161 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3162 if( iDb<0 ) return;
3163 z = sqlite3NameFromToken(pObjName);
3164 zDb = db->aDb[iDb].zName;
3165 pTab = sqlite3FindTable(db, z, zDb);
3166 if( pTab ){
3167 reindexTable(pParse, pTab, 0);
3168 sqliteFree(z);
3169 return;
3170 }
3171 pIndex = sqlite3FindIndex(db, z, zDb);
3172 sqliteFree(z);
3173 if( pIndex ){
3174 sqlite3BeginWriteOperation(pParse, 0, iDb);
3175 sqlite3RefillIndex(pParse, pIndex, -1);
3176 return;
3177 }
3178 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3179}
3180#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003181
3182/*
3183** Return a dynamicly allocated KeyInfo structure that can be used
3184** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3185**
3186** If successful, a pointer to the new structure is returned. In this case
3187** the caller is responsible for calling sqliteFree() on the returned
3188** pointer. If an error occurs (out of memory or missing collation
3189** sequence), NULL is returned and the state of pParse updated to reflect
3190** the error.
3191*/
3192KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3193 int i;
3194 int nCol = pIdx->nColumn;
3195 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3196 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
3197
3198 if( pKey ){
3199 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3200 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3201 for(i=0; i<nCol; i++){
3202 char *zColl = pIdx->azColl[i];
3203 assert( zColl );
3204 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3205 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3206 }
3207 pKey->nField = nCol;
3208 }
3209
3210 if( pParse->nErr ){
3211 sqliteFree(pKey);
3212 pKey = 0;
3213 }
3214 return pKey;
3215}