blob: 1563e12560951ff490d6ca96743eab0fce2cc806 [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**
drhe321c292006-01-12 01:56:43 +000025** $Id: build.c,v 1.378 2006/01/12 01:56:44 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;
drhe321c292006-01-12 01:56:43 +0000836 int fileFormat;
danielk1977cbb18d22004-05-28 11:37:27 +0000837 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000838
danielk197736963fd2005-02-19 08:18:05 +0000839 /* If the file format and encoding in the database have not been set,
840 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000841 */
danielk197736963fd2005-02-19 08:18:05 +0000842 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
843 lbl = sqlite3VdbeMakeLabel(v);
844 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
drhe321c292006-01-12 01:56:43 +0000845 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
846 1 : SQLITE_DEFAULT_FILE_FORMAT;
847 sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000848 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
danielk197714db2662006-01-09 16:12:04 +0000849 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000850 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000851 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000852
drh4794f732004-11-05 17:17:50 +0000853 /* This just creates a place-holder record in the sqlite_master table.
854 ** The record created does not contain anything yet. It will be replaced
855 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000856 **
857 ** The rowid for the new entry is left on the top of the stack.
858 ** The rowid value is needed by the code that sqlite3EndTable will
859 ** generate.
drh4794f732004-11-05 17:17:50 +0000860 */
danielk1977a21c6b62005-01-24 10:25:59 +0000861#ifndef SQLITE_OMIT_VIEW
862 if( isView ){
863 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
864 }else
865#endif
866 {
867 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
868 }
danielk1977c00da102006-01-07 13:21:04 +0000869 sqlite3OpenMasterTable(pParse, iDb);
drhf0863fe2005-06-12 21:35:51 +0000870 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000871 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000872 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
873 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000874 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000875 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000876 }
drh23bf66d2004-12-14 03:34:34 +0000877
878 /* Normal (non-error) return. */
879 return;
880
881 /* If an error occurs, we jump here */
882begin_table_error:
883 sqliteFree(zName);
884 return;
drh75897232000-05-29 14:26:00 +0000885}
886
887/*
danielk1977c60e9b82005-01-31 12:42:29 +0000888** This macro is used to compare two strings in a case-insensitive manner.
889** It is slightly faster than calling sqlite3StrICmp() directly, but
890** produces larger code.
891**
892** WARNING: This macro is not compatible with the strcmp() family. It
893** returns true if the two strings are equal, otherwise false.
894*/
895#define STRICMP(x, y) (\
896sqlite3UpperToLower[*(unsigned char *)(x)]== \
897sqlite3UpperToLower[*(unsigned char *)(y)] \
898&& sqlite3StrICmp((x)+1,(y)+1)==0 )
899
900/*
drh75897232000-05-29 14:26:00 +0000901** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000902**
903** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000904** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000905** first to get things going. Then this routine is called for each
906** column.
drh75897232000-05-29 14:26:00 +0000907*/
danielk19774adee202004-05-08 08:23:19 +0000908void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000909 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000910 int i;
drha99db3b2004-06-19 14:49:12 +0000911 char *z;
drhc9b84a12002-06-20 11:36:48 +0000912 Column *pCol;
drh75897232000-05-29 14:26:00 +0000913 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000914 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000915 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000916 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000917 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000918 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000919 sqliteFree(z);
920 return;
921 }
922 }
drh75897232000-05-29 14:26:00 +0000923 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000924 Column *aNew;
925 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000926 if( aNew==0 ){
927 sqliteFree(z);
928 return;
929 }
drh6d4abfb2001-10-22 02:58:08 +0000930 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000931 }
drhc9b84a12002-06-20 11:36:48 +0000932 pCol = &p->aCol[p->nCol];
933 memset(pCol, 0, sizeof(p->aCol[0]));
934 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000935
936 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000937 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
938 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000939 */
danielk19774f057f92004-06-08 00:02:33 +0000940 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000941 p->nCol++;
drh75897232000-05-29 14:26:00 +0000942}
943
944/*
drh382c0242001-10-06 16:33:02 +0000945** This routine is called by the parser while in the middle of
946** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
947** been seen on a column. This routine sets the notNull flag on
948** the column currently under construction.
949*/
danielk19774adee202004-05-08 08:23:19 +0000950void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000951 Table *p;
952 int i;
953 if( (p = pParse->pNewTable)==0 ) return;
954 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000955 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000956}
957
958/*
danielk197752a83fb2005-01-31 12:56:44 +0000959** Scan the column type name zType (length nType) and return the
960** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000961**
962** This routine does a case-independent search of zType for the
963** substrings in the following table. If one of the substrings is
964** found, the corresponding affinity is returned. If zType contains
965** more than one of the substrings, entries toward the top of
966** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000967** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000968**
969** Substring | Affinity
970** --------------------------------
971** 'INT' | SQLITE_AFF_INTEGER
972** 'CHAR' | SQLITE_AFF_TEXT
973** 'CLOB' | SQLITE_AFF_TEXT
974** 'TEXT' | SQLITE_AFF_TEXT
975** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000976** 'REAL' | SQLITE_AFF_REAL
977** 'FLOA' | SQLITE_AFF_REAL
978** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000979**
980** If none of the substrings in the above table are found,
981** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000982*/
drh8a512562005-11-14 22:29:05 +0000983char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000984 u32 h = 0;
985 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000986 const unsigned char *zIn = pType->z;
987 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000988
danielk1977b3dff962005-02-01 01:21:55 +0000989 while( zIn!=zEnd ){
990 h = (h<<8) + sqlite3UpperToLower[*zIn];
991 zIn++;
danielk1977201f7162005-02-01 02:13:29 +0000992 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
993 aff = SQLITE_AFF_TEXT;
994 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
995 aff = SQLITE_AFF_TEXT;
996 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
997 aff = SQLITE_AFF_TEXT;
998 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +0000999 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001000 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001001#ifndef SQLITE_OMIT_FLOATING_POINT
1002 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1003 && aff==SQLITE_AFF_NUMERIC ){
1004 aff = SQLITE_AFF_REAL;
1005 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1006 && aff==SQLITE_AFF_NUMERIC ){
1007 aff = SQLITE_AFF_REAL;
1008 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1009 && aff==SQLITE_AFF_NUMERIC ){
1010 aff = SQLITE_AFF_REAL;
1011#endif
danielk1977201f7162005-02-01 02:13:29 +00001012 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001013 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001014 break;
danielk197752a83fb2005-01-31 12:56:44 +00001015 }
1016 }
danielk1977b3dff962005-02-01 01:21:55 +00001017
1018 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001019}
1020
1021/*
drh382c0242001-10-06 16:33:02 +00001022** This routine is called by the parser while in the middle of
1023** parsing a CREATE TABLE statement. The pFirst token is the first
1024** token in the sequence of tokens that describe the type of the
1025** column currently under construction. pLast is the last token
1026** in the sequence. Use this information to construct a string
1027** that contains the typename of the column and store that string
1028** in zType.
1029*/
drh487e2622005-06-25 18:42:14 +00001030void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001031 Table *p;
drh487e2622005-06-25 18:42:14 +00001032 int i;
drhc9b84a12002-06-20 11:36:48 +00001033 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001034
drh382c0242001-10-06 16:33:02 +00001035 if( (p = pParse->pNewTable)==0 ) return;
1036 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001037 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001038 pCol = &p->aCol[i];
drhd8919672005-09-10 15:35:06 +00001039 sqliteFree(pCol->zType);
drh487e2622005-06-25 18:42:14 +00001040 pCol->zType = sqlite3NameFromToken(pType);
drh8a512562005-11-14 22:29:05 +00001041 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001042}
1043
1044/*
danielk19777977a172004-11-09 12:44:37 +00001045** The expression is the default value for the most recently added column
1046** of the table currently under construction.
1047**
1048** Default value expressions must be constant. Raise an exception if this
1049** is not the case.
drhd9b02572001-04-15 00:37:09 +00001050**
1051** This routine is called by the parser while in the middle of
1052** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001053*/
danielk19777977a172004-11-09 12:44:37 +00001054void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001055 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001056 Column *pCol;
drh42b9d7c2005-08-13 00:56:27 +00001057 if( (p = pParse->pNewTable)!=0 ){
1058 pCol = &(p->aCol[p->nCol-1]);
1059 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1060 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1061 pCol->zName);
1062 }else{
1063 sqlite3ExprDelete(pCol->pDflt);
1064 pCol->pDflt = sqlite3ExprDup(pExpr);
1065 }
danielk19777977a172004-11-09 12:44:37 +00001066 }
1067 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +00001068}
1069
1070/*
drh4a324312001-12-21 14:30:42 +00001071** Designate the PRIMARY KEY for the table. pList is a list of names
1072** of columns that form the primary key. If pList is NULL, then the
1073** most recently added column of the table is the primary key.
1074**
1075** A table can have at most one primary key. If the table already has
1076** a primary key (and this is the second primary key) then create an
1077** error.
1078**
1079** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001080** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001081** field of the table under construction to be the index of the
1082** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1083** no INTEGER PRIMARY KEY.
1084**
1085** If the key is not an INTEGER PRIMARY KEY, then create a unique
1086** index for the key. No index is created for INTEGER PRIMARY KEYs.
1087*/
drh205f48e2004-11-05 00:43:11 +00001088void sqlite3AddPrimaryKey(
1089 Parse *pParse, /* Parsing context */
1090 ExprList *pList, /* List of field names to be indexed */
1091 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001092 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1093 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001094){
drh4a324312001-12-21 14:30:42 +00001095 Table *pTab = pParse->pNewTable;
1096 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001097 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +00001098 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001099 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001100 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001101 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001102 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001103 }
1104 pTab->hasPrimKey = 1;
1105 if( pList==0 ){
1106 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001107 pTab->aCol[iCol].isPrimKey = 1;
1108 }else{
danielk19770202b292004-06-09 09:55:16 +00001109 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001110 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001111 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1112 break;
1113 }
drh78100cc2003-08-23 22:40:53 +00001114 }
drh6e4fc2c2005-09-15 21:24:51 +00001115 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001116 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001117 }
drh4a324312001-12-21 14:30:42 +00001118 }
danielk19770202b292004-06-09 09:55:16 +00001119 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001120 }
1121 if( iCol>=0 && iCol<pTab->nCol ){
1122 zType = pTab->aCol[iCol].zType;
1123 }
drhfdd6e852005-12-16 01:06:16 +00001124 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1125 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001126 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001127 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001128 pTab->autoInc = autoInc;
1129 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001130#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001131 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1132 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001133#endif
drh4a324312001-12-21 14:30:42 +00001134 }else{
drh4d91a702006-01-04 15:54:36 +00001135 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001136 pList = 0;
drh4a324312001-12-21 14:30:42 +00001137 }
drhe0194f22003-02-26 13:52:51 +00001138
1139primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001140 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001141 return;
drh4a324312001-12-21 14:30:42 +00001142}
1143
1144/*
drhffe07b22005-11-03 00:41:17 +00001145** Add a new CHECK constraint to the table currently under construction.
1146*/
1147void sqlite3AddCheckConstraint(
1148 Parse *pParse, /* Parsing context */
1149 Expr *pCheckExpr /* The check expression */
1150){
1151#ifndef SQLITE_OMIT_CHECK
1152 Table *pTab = pParse->pNewTable;
1153 if( pTab ){
1154 /* The CHECK expression must be duplicated so that tokens refer
1155 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1156 ** statement */
1157 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
1158 }
1159#endif
1160 sqlite3ExprDelete(pCheckExpr);
1161}
1162
1163/*
drhd3d39e92004-05-20 22:16:29 +00001164** Set the collation function of the most recently parsed table column
1165** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001166*/
drhd3d39e92004-05-20 22:16:29 +00001167void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001168 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001169 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001170
drhd3d39e92004-05-20 22:16:29 +00001171 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001172 i = p->nCol-1;
1173
danielk1977b3bf5562006-01-10 17:58:23 +00001174 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1175 Index *pIdx;
1176 p->aCol[i].zColl = sqlite3StrNDup(zType, nType);
1177
1178 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1179 ** then an index may have been created on this column before the
1180 ** collation type was added. Correct this if it is the case.
1181 */
1182 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1183 assert( pIdx->nColumn==1 );
1184 if( pIdx->aiColumn[0]==i ){
1185 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001186 }
1187 }
1188 }
danielk19777cedc8d2004-06-10 10:50:08 +00001189}
1190
danielk1977466be562004-06-10 02:16:01 +00001191/*
1192** This function returns the collation sequence for database native text
1193** encoding identified by the string zName, length nName.
1194**
1195** If the requested collation sequence is not available, or not available
1196** in the database native encoding, the collation factory is invoked to
1197** request it. If the collation factory does not supply such a sequence,
1198** and the sequence is available in another text encoding, then that is
1199** returned instead.
1200**
1201** If no versions of the requested collations sequence are available, or
1202** another error occurs, NULL is returned and an error message written into
1203** pParse.
1204*/
danielk19770202b292004-06-09 09:55:16 +00001205CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001206 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001207 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001208 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001209 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001210
danielk1977b3bf5562006-01-10 17:58:23 +00001211 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001212 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001213 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1214 if( !pColl ){
1215 if( nName<0 ){
1216 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001217 }
danielk19774dade032005-05-25 10:45:10 +00001218 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1219 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001220 }
1221 }
1222
danielk19770202b292004-06-09 09:55:16 +00001223 return pColl;
1224}
1225
1226
drh8e2ca022002-06-17 17:07:19 +00001227/*
drh3f7d4e42004-07-24 14:35:58 +00001228** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001229**
1230** The schema cookie is used to determine when the schema for the
1231** database changes. After each schema change, the cookie value
1232** changes. When a process first reads the schema it records the
1233** cookie. Thereafter, whenever it goes to access the database,
1234** it checks the cookie to make sure the schema has not changed
1235** since it was last read.
1236**
1237** This plan is not completely bullet-proof. It is possible for
1238** the schema to change multiple times and for the cookie to be
1239** set back to prior value. But schema changes are infrequent
1240** and the probability of hitting the same cookie value is only
1241** 1 chance in 2^32. So we're safe enough.
1242*/
drh9bb575f2004-09-06 17:24:11 +00001243void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
danielk1977da184232006-01-05 11:34:32 +00001244 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001245 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001246}
1247
1248/*
drh969fa7c2002-02-18 18:30:32 +00001249** Measure the number of characters needed to output the given
1250** identifier. The number returned includes any quotes used
1251** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001252**
1253** The estimate is conservative. It might be larger that what is
1254** really needed.
drh969fa7c2002-02-18 18:30:32 +00001255*/
1256static int identLength(const char *z){
1257 int n;
drh17f71932002-02-21 12:01:27 +00001258 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001259 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001260 }
drh234c39d2004-07-24 03:30:47 +00001261 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001262}
1263
1264/*
1265** Write an identifier onto the end of the given string. Add
1266** quote characters as needed.
1267*/
drh4c755c02004-08-08 20:22:17 +00001268static void identPut(char *z, int *pIdx, char *zSignedIdent){
1269 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001270 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001271 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001272 for(j=0; zIdent[j]; j++){
1273 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1274 }
1275 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001276 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001277 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001278 for(j=0; zIdent[j]; j++){
1279 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001280 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001281 }
drh234c39d2004-07-24 03:30:47 +00001282 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001283 z[i] = 0;
1284 *pIdx = i;
1285}
1286
1287/*
1288** Generate a CREATE TABLE statement appropriate for the given
1289** table. Memory to hold the text of the statement is obtained
1290** from sqliteMalloc() and must be freed by the calling function.
1291*/
danielk1977da184232006-01-05 11:34:32 +00001292static char *createTableStmt(Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001293 int i, k, n;
1294 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001295 char *zSep, *zSep2, *zEnd, *z;
1296 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001297 n = 0;
drh234c39d2004-07-24 03:30:47 +00001298 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1299 n += identLength(pCol->zName);
1300 z = pCol->zType;
1301 if( z ){
1302 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001303 }
drh969fa7c2002-02-18 18:30:32 +00001304 }
1305 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001306 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001307 zSep = "";
1308 zSep2 = ",";
1309 zEnd = ")";
1310 }else{
1311 zSep = "\n ";
1312 zSep2 = ",\n ";
1313 zEnd = "\n)";
1314 }
drhe0bc4042002-06-25 01:09:11 +00001315 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001316 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001317 if( zStmt==0 ) return 0;
danielk1977da184232006-01-05 11:34:32 +00001318 strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001319 k = strlen(zStmt);
1320 identPut(zStmt, &k, p->zName);
1321 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001322 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001323 strcpy(&zStmt[k], zSep);
1324 k += strlen(&zStmt[k]);
1325 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001326 identPut(zStmt, &k, pCol->zName);
1327 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001328 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001329 strcpy(&zStmt[k], z);
1330 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001331 }
drh969fa7c2002-02-18 18:30:32 +00001332 }
1333 strcpy(&zStmt[k], zEnd);
1334 return zStmt;
1335}
1336
1337/*
drh75897232000-05-29 14:26:00 +00001338** This routine is called to report the final ")" that terminates
1339** a CREATE TABLE statement.
1340**
drhf57b3392001-10-08 13:22:32 +00001341** The table structure that other action routines have been building
1342** is added to the internal hash tables, assuming no errors have
1343** occurred.
drh75897232000-05-29 14:26:00 +00001344**
drh1d85d932004-02-14 23:05:52 +00001345** An entry for the table is made in the master table on disk, unless
1346** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001347** it means we are reading the sqlite_master table because we just
1348** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001349** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001350** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001351**
1352** If the pSelect argument is not NULL, it means that this routine
1353** was called to create a table generated from a
1354** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1355** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001356*/
danielk197719a8e7e2005-03-17 05:03:38 +00001357void sqlite3EndTable(
1358 Parse *pParse, /* Parse context */
1359 Token *pCons, /* The ',' token after the last column defn. */
1360 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1361 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1362){
drh75897232000-05-29 14:26:00 +00001363 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001364 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001365 int iDb;
drh75897232000-05-29 14:26:00 +00001366
danielk1977e501b892006-01-09 06:29:47 +00001367 if( (pEnd==0 && pSelect==0) ||
drh6f7adc82006-01-11 21:41:20 +00001368 pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) {
danielk1977261919c2005-12-06 12:52:59 +00001369 return;
1370 }
drh28037572000-08-02 13:47:41 +00001371 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001372 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001373
danielk1977517eb642004-06-07 10:00:31 +00001374 assert( !db->init.busy || !pSelect );
1375
danielk1977da184232006-01-05 11:34:32 +00001376 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1377
drhffe07b22005-11-03 00:41:17 +00001378#ifndef SQLITE_OMIT_CHECK
1379 /* Resolve names in all CHECK constraint expressions.
1380 */
1381 if( p->pCheck ){
1382 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1383 NameContext sNC; /* Name context for pParse->pNewTable */
1384
1385 memset(&sNC, 0, sizeof(sNC));
1386 memset(&sSrc, 0, sizeof(sSrc));
1387 sSrc.nSrc = 1;
1388 sSrc.a[0].zName = p->zName;
1389 sSrc.a[0].pTab = p;
1390 sSrc.a[0].iCursor = -1;
1391 sNC.pParse = pParse;
1392 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001393 sNC.isCheck = 1;
drhffe07b22005-11-03 00:41:17 +00001394 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1395 return;
1396 }
1397 }
1398#endif /* !defined(SQLITE_OMIT_CHECK) */
1399
drh1d85d932004-02-14 23:05:52 +00001400 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001401 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1402 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001403 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001404 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001405 */
drh1d85d932004-02-14 23:05:52 +00001406 if( db->init.busy ){
1407 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001408 }
1409
drhe3c41372001-09-17 20:25:58 +00001410 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001411 ** in the SQLITE_MASTER table of the database. The record number
1412 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001413 **
drhe0bc4042002-06-25 01:09:11 +00001414 ** If this is a TEMPORARY table, write the entry into the auxiliary
1415 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001416 */
drh1d85d932004-02-14 23:05:52 +00001417 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001418 int n;
drhd8bc7082000-06-07 23:51:50 +00001419 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001420 char *zType; /* "view" or "table" */
1421 char *zType2; /* "VIEW" or "TABLE" */
1422 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001423
danielk19774adee202004-05-08 08:23:19 +00001424 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001425 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001426
danielk1977e6efa742004-11-10 11:55:10 +00001427 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1428
drh4794f732004-11-05 17:17:50 +00001429 /* Create the rootpage for the new table and push it onto the stack.
1430 ** A view has no rootpage, so just push a zero onto the stack for
1431 ** views. Initialize zType at the same time.
1432 */
drh4ff6dfa2002-03-03 23:06:00 +00001433 if( p->pSelect==0 ){
1434 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001435 zType = "table";
1436 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001437#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001438 }else{
1439 /* A view */
drh4794f732004-11-05 17:17:50 +00001440 zType = "view";
1441 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001442#endif
drh4ff6dfa2002-03-03 23:06:00 +00001443 }
danielk1977517eb642004-06-07 10:00:31 +00001444
danielk1977517eb642004-06-07 10:00:31 +00001445 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1446 ** statement to populate the new table. The root-page number for the
1447 ** new table is on the top of the vdbe stack.
1448 **
1449 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1450 ** suitable state to query for the column names and types to be used
1451 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001452 **
1453 ** A shared-cache write-lock is not required to write to the new table,
1454 ** as a schema-lock must have already been obtained to create it. Since
1455 ** a schema-lock excludes all other database users, the write-lock would
1456 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001457 */
1458 if( pSelect ){
1459 Table *pSelTab;
1460 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
danielk1977da184232006-01-05 11:34:32 +00001461 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977517eb642004-06-07 10:00:31 +00001462 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1463 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001464 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001465 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1466 if( pParse->nErr==0 ){
1467 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1468 if( pSelTab==0 ) return;
1469 assert( p->aCol==0 );
1470 p->nCol = pSelTab->nCol;
1471 p->aCol = pSelTab->aCol;
1472 pSelTab->nCol = 0;
1473 pSelTab->aCol = 0;
1474 sqlite3DeleteTable(0, pSelTab);
1475 }
1476 }
drh4794f732004-11-05 17:17:50 +00001477
drh4794f732004-11-05 17:17:50 +00001478 /* Compute the complete text of the CREATE statement */
1479 if( pSelect ){
danielk1977da184232006-01-05 11:34:32 +00001480 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001481 }else{
drh97903fe2005-05-24 20:19:57 +00001482 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001483 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1484 }
1485
1486 /* A slot for the record has already been allocated in the
1487 ** SQLITE_MASTER table. We just need to update that slot with all
1488 ** the information we've collected. The rowid for the preallocated
1489 ** slot is the 2nd item on the stack. The top of the stack is the
1490 ** root page for the new table (or a 0 if this is a view).
1491 */
1492 sqlite3NestedParse(pParse,
1493 "UPDATE %Q.%s "
1494 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1495 "WHERE rowid=#1",
danielk1977da184232006-01-05 11:34:32 +00001496 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001497 zType,
1498 p->zName,
1499 p->zName,
1500 zStmt
1501 );
1502 sqliteFree(zStmt);
danielk1977da184232006-01-05 11:34:32 +00001503 sqlite3ChangeCookie(db, v, iDb);
drh2958a4e2004-11-12 03:56:15 +00001504
1505#ifndef SQLITE_OMIT_AUTOINCREMENT
1506 /* Check to see if we need to create an sqlite_sequence table for
1507 ** keeping track of autoincrement keys.
1508 */
1509 if( p->autoInc ){
danielk1977da184232006-01-05 11:34:32 +00001510 Db *pDb = &db->aDb[iDb];
1511 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001512 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001513 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1514 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001515 );
1516 }
1517 }
1518#endif
drh4794f732004-11-05 17:17:50 +00001519
1520 /* Reparse everything to update our internal data structures */
danielk1977da184232006-01-05 11:34:32 +00001521 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
drh234c39d2004-07-24 03:30:47 +00001522 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001523 }
drh17e9e292003-02-01 13:53:28 +00001524
drh2958a4e2004-11-12 03:56:15 +00001525
drh17e9e292003-02-01 13:53:28 +00001526 /* Add the table to the in-memory representation of the database.
1527 */
drh234c39d2004-07-24 03:30:47 +00001528 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001529 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001530 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001531 Schema *pSchema = p->pSchema;
danielk1977da184232006-01-05 11:34:32 +00001532 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001533 if( pOld ){
1534 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1535 return;
1536 }
danielk1977576ec6b2005-01-21 11:55:25 +00001537#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001538 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1539 int nTo = strlen(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001540 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1541 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001542 }
danielk1977576ec6b2005-01-21 11:55:25 +00001543#endif
drh17e9e292003-02-01 13:53:28 +00001544 pParse->pNewTable = 0;
1545 db->nTable++;
1546 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001547
1548#ifndef SQLITE_OMIT_ALTERTABLE
1549 if( !p->pSelect ){
1550 assert( !pSelect && pCons && pEnd );
1551 if( pCons->z==0 ) pCons = pEnd;
1552 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1553 }
1554#endif
drh17e9e292003-02-01 13:53:28 +00001555 }
drh75897232000-05-29 14:26:00 +00001556}
1557
drhb7f91642004-10-31 02:22:47 +00001558#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001559/*
drha76b5df2002-02-23 02:32:10 +00001560** The parser calls this routine in order to create a new VIEW
1561*/
danielk19774adee202004-05-08 08:23:19 +00001562void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001563 Parse *pParse, /* The parsing context */
1564 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001565 Token *pName1, /* The token that holds the name of the view */
1566 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001567 Select *pSelect, /* A SELECT statement that will become the new view */
1568 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001569){
drha76b5df2002-02-23 02:32:10 +00001570 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001571 int n;
drh4c755c02004-08-08 20:22:17 +00001572 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001573 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001574 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001575 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001576 int iDb;
drha76b5df2002-02-23 02:32:10 +00001577
drh7c3d64f2005-06-06 15:32:08 +00001578 if( pParse->nVar>0 ){
1579 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1580 sqlite3SelectDelete(pSelect);
1581 return;
1582 }
drhfaa59552005-12-29 23:33:54 +00001583 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1, 0);
drha76b5df2002-02-23 02:32:10 +00001584 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001585 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001586 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001587 return;
1588 }
danielk1977ef2cb632004-05-29 02:37:19 +00001589 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977da184232006-01-05 11:34:32 +00001590 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1591 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001592 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001593 ){
danielk19774adee202004-05-08 08:23:19 +00001594 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001595 return;
1596 }
drh174b6192002-12-03 02:22:52 +00001597
drh4b59ab52002-08-24 18:24:51 +00001598 /* Make a copy of the entire SELECT statement that defines the view.
1599 ** This will force all the Expr.token.z values to be dynamically
1600 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001601 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001602 */
danielk19774adee202004-05-08 08:23:19 +00001603 p->pSelect = sqlite3SelectDup(pSelect);
1604 sqlite3SelectDelete(pSelect);
drh6f7adc82006-01-11 21:41:20 +00001605 if( sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977261919c2005-12-06 12:52:59 +00001606 return;
1607 }
drh1d85d932004-02-14 23:05:52 +00001608 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001609 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001610 }
drh4b59ab52002-08-24 18:24:51 +00001611
1612 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1613 ** the end.
1614 */
drha76b5df2002-02-23 02:32:10 +00001615 sEnd = pParse->sLastToken;
1616 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1617 sEnd.z += sEnd.n;
1618 }
1619 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001620 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001621 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001622 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1623 sEnd.z = &z[n-1];
1624 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001625
danielk19774adee202004-05-08 08:23:19 +00001626 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001627 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001628 return;
drh417be792002-03-03 18:59:40 +00001629}
drhb7f91642004-10-31 02:22:47 +00001630#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001631
drhb7f91642004-10-31 02:22:47 +00001632#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001633/*
1634** The Table structure pTable is really a VIEW. Fill in the names of
1635** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001636** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001637*/
danielk19774adee202004-05-08 08:23:19 +00001638int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001639 Table *pSelTab; /* A fake table from which we get the result set */
1640 Select *pSel; /* Copy of the SELECT that implements the view */
1641 int nErr = 0; /* Number of errors encountered */
1642 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001643
1644 assert( pTable );
1645
1646 /* A positive nCol means the columns names for this view are
1647 ** already known.
1648 */
1649 if( pTable->nCol>0 ) return 0;
1650
1651 /* A negative nCol is a special marker meaning that we are currently
1652 ** trying to compute the column names. If we enter this routine with
1653 ** a negative nCol, it means two or more views form a loop, like this:
1654 **
1655 ** CREATE VIEW one AS SELECT * FROM two;
1656 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001657 **
1658 ** Actually, this error is caught previously and so the following test
1659 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001660 */
drh85c23c62005-08-20 03:03:04 +00001661#if 0
drh417be792002-03-03 18:59:40 +00001662 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001663 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001664 return 1;
1665 }
drh85c23c62005-08-20 03:03:04 +00001666#endif
1667 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001668
1669 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001670 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1671 ** "*" elements in the results set of the view and will assign cursors
1672 ** to the elements of the FROM clause. But we do not want these changes
1673 ** to be permanent. So the computation is done on a copy of the SELECT
1674 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001675 */
drh9b3187e2005-01-18 14:45:47 +00001676 assert( pTable->pSelect );
1677 pSel = sqlite3SelectDup(pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001678 if( pSel ){
1679 n = pParse->nTab;
1680 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1681 pTable->nCol = -1;
1682 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1683 pParse->nTab = n;
1684 if( pSelTab ){
1685 assert( pTable->aCol==0 );
1686 pTable->nCol = pSelTab->nCol;
1687 pTable->aCol = pSelTab->aCol;
1688 pSelTab->nCol = 0;
1689 pSelTab->aCol = 0;
1690 sqlite3DeleteTable(0, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001691 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001692 }else{
1693 pTable->nCol = 0;
1694 nErr++;
1695 }
1696 sqlite3SelectDelete(pSel);
1697 } else {
drh417be792002-03-03 18:59:40 +00001698 nErr++;
1699 }
drh417be792002-03-03 18:59:40 +00001700 return nErr;
1701}
drhb7f91642004-10-31 02:22:47 +00001702#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001703
drhb7f91642004-10-31 02:22:47 +00001704#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001705/*
drh8bf8dc92003-05-17 17:35:10 +00001706** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001707*/
drh9bb575f2004-09-06 17:24:11 +00001708static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001709 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001710 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001711 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001712 Table *pTab = sqliteHashData(i);
1713 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001714 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001715 }
1716 }
drh8bf8dc92003-05-17 17:35:10 +00001717 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001718}
drhb7f91642004-10-31 02:22:47 +00001719#else
1720# define sqliteViewResetAll(A,B)
1721#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001722
drh75897232000-05-29 14:26:00 +00001723/*
danielk1977a0bf2652004-11-04 14:30:04 +00001724** This function is called by the VDBE to adjust the internal schema
1725** used by SQLite when the btree layer moves a table root page. The
1726** root-page of a table or index in database iDb has changed from iFrom
1727** to iTo.
1728*/
1729#ifndef SQLITE_OMIT_AUTOVACUUM
1730void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1731 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001732 Hash *pHash;
1733
1734 pHash = &pDb->pSchema->tblHash;
1735 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001736 Table *pTab = sqliteHashData(pElem);
1737 if( pTab->tnum==iFrom ){
1738 pTab->tnum = iTo;
1739 return;
1740 }
1741 }
danielk1977da184232006-01-05 11:34:32 +00001742 pHash = &pDb->pSchema->idxHash;
1743 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001744 Index *pIdx = sqliteHashData(pElem);
1745 if( pIdx->tnum==iFrom ){
1746 pIdx->tnum = iTo;
1747 return;
1748 }
1749 }
1750 assert(0);
1751}
1752#endif
1753
1754/*
1755** Write code to erase the table with root-page iTable from database iDb.
1756** Also write code to modify the sqlite_master table and internal schema
1757** if a root-page of another table is moved by the btree-layer whilst
1758** erasing iTable (this can happen with an auto-vacuum database).
1759*/
drh4e0cff62004-11-05 05:10:28 +00001760static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1761 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001762 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1763#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001764 /* OP_Destroy pushes an integer onto the stack. If this integer
1765 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001766 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001767 ** reflect this.
1768 **
1769 ** The "#0" in the SQL is a special constant that means whatever value
1770 ** is on the top of the stack. See sqlite3RegisterExpr().
1771 */
danielk197763e3e9f2004-11-05 09:19:27 +00001772 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001773 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001774 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001775#endif
1776}
1777
1778/*
1779** Write VDBE code to erase table pTab and all associated indices on disk.
1780** Code to update the sqlite_master tables and internal schema definitions
1781** in case a root-page belonging to another table is moved by the btree layer
1782** is also added (this can happen with an auto-vacuum database).
1783*/
drh4e0cff62004-11-05 05:10:28 +00001784static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001785#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001786 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001787 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1788 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001789 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001790 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001791 }
1792#else
1793 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1794 ** is not defined), then it is important to call OP_Destroy on the
1795 ** table and index root-pages in order, starting with the numerically
1796 ** largest root-page number. This guarantees that none of the root-pages
1797 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1798 ** following were coded:
1799 **
1800 ** OP_Destroy 4 0
1801 ** ...
1802 ** OP_Destroy 5 0
1803 **
1804 ** and root page 5 happened to be the largest root-page number in the
1805 ** database, then root page 5 would be moved to page 4 by the
1806 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1807 ** a free-list page.
1808 */
1809 int iTab = pTab->tnum;
1810 int iDestroyed = 0;
1811
1812 while( 1 ){
1813 Index *pIdx;
1814 int iLargest = 0;
1815
1816 if( iDestroyed==0 || iTab<iDestroyed ){
1817 iLargest = iTab;
1818 }
1819 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1820 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001821 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001822 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1823 iLargest = iIdx;
1824 }
1825 }
danielk1977da184232006-01-05 11:34:32 +00001826 if( iLargest==0 ){
1827 return;
1828 }else{
1829 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1830 destroyRootPage(pParse, iLargest, iDb);
1831 iDestroyed = iLargest;
1832 }
danielk1977a0bf2652004-11-04 14:30:04 +00001833 }
1834#endif
1835}
1836
1837/*
drh75897232000-05-29 14:26:00 +00001838** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001839** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001840*/
drha0733842005-12-29 01:11:36 +00001841void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001842 Table *pTab;
drh75897232000-05-29 14:26:00 +00001843 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001844 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001845 int iDb;
drh75897232000-05-29 14:26:00 +00001846
drh6f7adc82006-01-11 21:41:20 +00001847 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
1848 goto exit_drop_table;
1849 }
danielk1977a8858102004-05-28 12:11:21 +00001850 assert( pName->nSrc==1 );
1851 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1852
drha0733842005-12-29 01:11:36 +00001853 if( pTab==0 ){
1854 if( noErr ){
1855 sqlite3ErrorClear(pParse);
1856 }
1857 goto exit_drop_table;
1858 }
danielk1977da184232006-01-05 11:34:32 +00001859 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001860 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001861#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001862 {
1863 int code;
danielk1977da184232006-01-05 11:34:32 +00001864 const char *zTab = SCHEMA_TABLE(iDb);
1865 const char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001866 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001867 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001868 }
drhe5f9c642003-01-13 23:27:31 +00001869 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001870 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001871 code = SQLITE_DROP_TEMP_VIEW;
1872 }else{
1873 code = SQLITE_DROP_VIEW;
1874 }
1875 }else{
danielk197753c0f742005-03-29 03:10:59 +00001876 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001877 code = SQLITE_DROP_TEMP_TABLE;
1878 }else{
1879 code = SQLITE_DROP_TABLE;
1880 }
1881 }
danielk1977a8858102004-05-28 12:11:21 +00001882 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1883 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001884 }
danielk1977a8858102004-05-28 12:11:21 +00001885 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1886 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001887 }
drhe5f9c642003-01-13 23:27:31 +00001888 }
1889#endif
danielk1977da184232006-01-05 11:34:32 +00001890 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001891 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001892 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001893 }
danielk1977576ec6b2005-01-21 11:55:25 +00001894
1895#ifndef SQLITE_OMIT_VIEW
1896 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1897 ** on a table.
1898 */
danielk1977a8858102004-05-28 12:11:21 +00001899 if( isView && pTab->pSelect==0 ){
1900 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1901 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001902 }
danielk1977a8858102004-05-28 12:11:21 +00001903 if( !isView && pTab->pSelect ){
1904 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1905 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001906 }
danielk1977576ec6b2005-01-21 11:55:25 +00001907#endif
drh75897232000-05-29 14:26:00 +00001908
drh1ccde152000-06-17 13:12:39 +00001909 /* Generate code to remove the table from the master table
1910 ** on disk.
1911 */
danielk19774adee202004-05-08 08:23:19 +00001912 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001913 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001914 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001915 Db *pDb = &db->aDb[iDb];
1916 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001917
danielk19778e227872004-06-07 07:52:17 +00001918 /* Drop all triggers associated with the table being dropped. Code
1919 ** is generated to remove entries from sqlite_master and/or
1920 ** sqlite_temp_master if required.
1921 */
danielk1977a8858102004-05-28 12:11:21 +00001922 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001923 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00001924 assert( pTrigger->pSchema==pTab->pSchema ||
1925 pTrigger->pSchema==db->aDb[1].pSchema );
danielk19774adee202004-05-08 08:23:19 +00001926 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001927 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001928 }
drh8bf8dc92003-05-17 17:35:10 +00001929
danielk19774d36b812004-11-19 07:07:30 +00001930#ifndef SQLITE_OMIT_AUTOINCREMENT
1931 /* Remove any entries of the sqlite_sequence table associated with
1932 ** the table being dropped. This is done before the table is dropped
1933 ** at the btree level, in case the sqlite_sequence table needs to
1934 ** move as a result of the drop (can happen in auto-vacuum mode).
1935 */
1936 if( pTab->autoInc ){
1937 sqlite3NestedParse(pParse,
1938 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1939 pDb->zName, pTab->zName
1940 );
1941 }
1942#endif
1943
danielk19778e227872004-06-07 07:52:17 +00001944 /* Drop all SQLITE_MASTER table and index entries that refer to the
1945 ** table. The program name loops through the master table and deletes
1946 ** every row that refers to a table of the same name as the one being
1947 ** dropped. Triggers are handled seperately because a trigger can be
1948 ** created in the temp database that refers to a table in another
1949 ** database.
1950 */
drhf1974842004-11-05 03:56:00 +00001951 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001952 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001953 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001954 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001955 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001956 }
drh2958a4e2004-11-12 03:56:15 +00001957
danielk1977a21c6b62005-01-24 10:25:59 +00001958 /* Remove the table entry from SQLite's internal schema and modify
1959 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001960 */
1961 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00001962 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00001963 }
drhd24cc422003-03-27 12:51:24 +00001964 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001965
1966exit_drop_table:
1967 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001968}
1969
1970/*
drhc2eef3b2002-08-31 18:53:06 +00001971** This routine is called to create a new foreign key on the table
1972** currently under construction. pFromCol determines which columns
1973** in the current table point to the foreign key. If pFromCol==0 then
1974** connect the key to the last column inserted. pTo is the name of
1975** the table referred to. pToCol is a list of tables in the other
1976** pTo table that the foreign key points to. flags contains all
1977** information about the conflict resolution algorithms specified
1978** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1979**
1980** An FKey structure is created and added to the table currently
1981** under construction in the pParse->pNewTable field. The new FKey
1982** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001983** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001984**
1985** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001986** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001987*/
danielk19774adee202004-05-08 08:23:19 +00001988void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001989 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001990 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001991 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001992 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001993 int flags /* Conflict resolution algorithms. */
1994){
drhb7f91642004-10-31 02:22:47 +00001995#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001996 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001997 Table *p = pParse->pNewTable;
1998 int nByte;
1999 int i;
2000 int nCol;
2001 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002002
2003 assert( pTo!=0 );
2004 if( p==0 || pParse->nErr ) goto fk_end;
2005 if( pFromCol==0 ){
2006 int iCol = p->nCol-1;
2007 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002008 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002009 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002010 " should reference only one column of table %T",
2011 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002012 goto fk_end;
2013 }
2014 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002015 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002016 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002017 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002018 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002019 goto fk_end;
2020 }else{
danielk19770202b292004-06-09 09:55:16 +00002021 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002022 }
2023 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2024 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002025 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00002026 nByte += strlen(pToCol->a[i].zName) + 1;
2027 }
2028 }
2029 pFKey = sqliteMalloc( nByte );
2030 if( pFKey==0 ) goto fk_end;
2031 pFKey->pFrom = p;
2032 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002033 z = (char*)&pFKey[1];
2034 pFKey->aCol = (struct sColMap*)z;
2035 z += sizeof(struct sColMap)*nCol;
2036 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002037 memcpy(z, pTo->z, pTo->n);
2038 z[pTo->n] = 0;
2039 z += pTo->n+1;
2040 pFKey->pNextTo = 0;
2041 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002042 if( pFromCol==0 ){
2043 pFKey->aCol[0].iFrom = p->nCol-1;
2044 }else{
2045 for(i=0; i<nCol; i++){
2046 int j;
2047 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002048 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002049 pFKey->aCol[i].iFrom = j;
2050 break;
2051 }
2052 }
2053 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002054 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002055 "unknown column \"%s\" in foreign key definition",
2056 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002057 goto fk_end;
2058 }
2059 }
2060 }
2061 if( pToCol ){
2062 for(i=0; i<nCol; i++){
2063 int n = strlen(pToCol->a[i].zName);
2064 pFKey->aCol[i].zCol = z;
2065 memcpy(z, pToCol->a[i].zName, n);
2066 z[n] = 0;
2067 z += n+1;
2068 }
2069 }
2070 pFKey->isDeferred = 0;
2071 pFKey->deleteConf = flags & 0xff;
2072 pFKey->updateConf = (flags >> 8 ) & 0xff;
2073 pFKey->insertConf = (flags >> 16 ) & 0xff;
2074
2075 /* Link the foreign key to the table as the last step.
2076 */
2077 p->pFKey = pFKey;
2078 pFKey = 0;
2079
2080fk_end:
2081 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00002082#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00002083 sqlite3ExprListDelete(pFromCol);
2084 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002085}
2086
2087/*
2088** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2089** clause is seen as part of a foreign key definition. The isDeferred
2090** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2091** The behavior of the most recently created foreign key is adjusted
2092** accordingly.
2093*/
danielk19774adee202004-05-08 08:23:19 +00002094void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002095#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002096 Table *pTab;
2097 FKey *pFKey;
2098 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2099 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002100#endif
drhc2eef3b2002-08-31 18:53:06 +00002101}
2102
2103/*
drh063336a2004-11-05 20:58:39 +00002104** Generate code that will erase and refill index *pIdx. This is
2105** used to initialize a newly created index or to recompute the
2106** content of an index in response to a REINDEX command.
2107**
2108** if memRootPage is not negative, it means that the index is newly
2109** created. The memory cell specified by memRootPage contains the
2110** root page number of the index. If memRootPage is negative, then
2111** the index already exists and must be cleared before being refilled and
2112** the root page number of the index is taken from pIndex->tnum.
2113*/
2114static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2115 Table *pTab = pIndex->pTable; /* The table that is indexed */
2116 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2117 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2118 int addr1; /* Address of top of loop */
2119 int tnum; /* Root page of index */
2120 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002121 KeyInfo *pKey; /* KeyInfo for index */
danielk1977da184232006-01-05 11:34:32 +00002122 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002123
danielk19771d54df82004-11-23 15:41:16 +00002124#ifndef SQLITE_OMIT_AUTHORIZATION
2125 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
danielk1977da184232006-01-05 11:34:32 +00002126 pParse->db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002127 return;
2128 }
2129#endif
2130
danielk1977c00da102006-01-07 13:21:04 +00002131 /* Require a write-lock on the table to perform this operation */
2132 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2133
drh063336a2004-11-05 20:58:39 +00002134 v = sqlite3GetVdbe(pParse);
2135 if( v==0 ) return;
2136 if( memRootPage>=0 ){
2137 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2138 tnum = 0;
2139 }else{
2140 tnum = pIndex->tnum;
danielk1977da184232006-01-05 11:34:32 +00002141 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002142 }
danielk1977da184232006-01-05 11:34:32 +00002143 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977b3bf5562006-01-10 17:58:23 +00002144 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2145 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
danielk1977c00da102006-01-07 13:21:04 +00002146 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh063336a2004-11-05 20:58:39 +00002147 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2148 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00002149 if( pIndex->onError!=OE_None ){
2150 int curaddr = sqlite3VdbeCurrentAddr(v);
2151 int addr2 = curaddr+4;
2152 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2153 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2154 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2155 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2156 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2157 "indexed columns are not unique", P3_STATIC);
2158 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002159 }
drh7f057c92005-06-24 03:53:06 +00002160 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002161 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002162 sqlite3VdbeJumpHere(v, addr1);
drh063336a2004-11-05 20:58:39 +00002163 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2164 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2165}
2166
2167/*
drh23bf66d2004-12-14 03:34:34 +00002168** Create a new index for an SQL table. pName1.pName2 is the name of the index
2169** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002170** be NULL for a primary key or an index that is created to satisfy a
2171** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002172** as the table to be indexed. pParse->pNewTable is a table that is
2173** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002174**
drh382c0242001-10-06 16:33:02 +00002175** pList is a list of columns to be indexed. pList will be NULL if this
2176** is a primary key or unique-constraint on the most recent column added
2177** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002178*/
danielk19774adee202004-05-08 08:23:19 +00002179void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002180 Parse *pParse, /* All information about this parse */
2181 Token *pName1, /* First part of index name. May be NULL */
2182 Token *pName2, /* Second part of index name. May be NULL */
2183 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002184 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002185 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2186 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
drhfdd6e852005-12-16 01:06:16 +00002187 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002188 int sortOrder, /* Sort order of primary key when pList==NULL */
2189 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002190){
drhfdd6e852005-12-16 01:06:16 +00002191 Table *pTab = 0; /* Table to be indexed */
2192 Index *pIndex = 0; /* The index to be created */
2193 char *zName = 0; /* Name of the index */
2194 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002195 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002196 Token nullId; /* Fake token for an empty ID list */
2197 DbFixer sFix; /* For assigning database names to pTable */
2198 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002199 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002200 Db *pDb; /* The specific table containing the indexed database */
2201 int iDb; /* Index of the database that is being written */
2202 Token *pName = 0; /* Unqualified name of the index to create */
2203 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002204 int nCol;
2205 int nExtra = 0;
2206 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002207
drh6f7adc82006-01-11 21:41:20 +00002208 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977e501b892006-01-09 06:29:47 +00002209 goto exit_create_index;
2210 }
drhdaffd0e2001-04-11 14:28:42 +00002211
drh75897232000-05-29 14:26:00 +00002212 /*
2213 ** Find the table that is to be indexed. Return early if not found.
2214 */
danielk1977cbb18d22004-05-28 11:37:27 +00002215 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002216
2217 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002218 ** to search for the table. 'Fix' the table name to this db
2219 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002220 */
2221 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002222 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002223 if( iDb<0 ) goto exit_create_index;
2224
danielk197753c0f742005-03-29 03:10:59 +00002225#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002226 /* If the index name was unqualified, check if the the table
2227 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002228 */
danielk1977ef2cb632004-05-29 02:37:19 +00002229 pTab = sqlite3SrcListLookup(pParse, pTblName);
danielk1977da184232006-01-05 11:34:32 +00002230 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977ef2cb632004-05-29 02:37:19 +00002231 iDb = 1;
2232 }
danielk197753c0f742005-03-29 03:10:59 +00002233#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002234
2235 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2236 sqlite3FixSrcList(&sFix, pTblName)
2237 ){
drh85c23c62005-08-20 03:03:04 +00002238 /* Because the parser constructs pTblName from a single identifier,
2239 ** sqlite3FixSrcList can never fail. */
2240 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002241 }
danielk1977ef2cb632004-05-29 02:37:19 +00002242 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2243 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002244 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002245 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002246 }else{
drhe3c41372001-09-17 20:25:58 +00002247 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002248 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002249 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002250 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002251 }
drhfdd6e852005-12-16 01:06:16 +00002252 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002253
drh75897232000-05-29 14:26:00 +00002254 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002255 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002256 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002257 goto exit_create_index;
2258 }
danielk1977576ec6b2005-01-21 11:55:25 +00002259#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002260 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002261 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002262 goto exit_create_index;
2263 }
danielk1977576ec6b2005-01-21 11:55:25 +00002264#endif
drh75897232000-05-29 14:26:00 +00002265
2266 /*
2267 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002268 ** index or table with the same name.
2269 **
2270 ** Exception: If we are reading the names of permanent indices from the
2271 ** sqlite_master table (because some other process changed the schema) and
2272 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002273 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002274 **
2275 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002276 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2277 ** own name.
drh75897232000-05-29 14:26:00 +00002278 */
danielk1977d8123362004-06-12 09:25:12 +00002279 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002280 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002281 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002282 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002283 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002284 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002285 }
danielk1977d8123362004-06-12 09:25:12 +00002286 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002287 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002288 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
drh4d91a702006-01-04 15:54:36 +00002289 if( !ifNotExist ){
2290 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2291 }
danielk1977d8123362004-06-12 09:25:12 +00002292 goto exit_create_index;
2293 }
drh4f26bb62005-09-08 14:17:20 +00002294 if( sqlite3FindTable(db, zName, 0)!=0 ){
danielk1977d8123362004-06-12 09:25:12 +00002295 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2296 goto exit_create_index;
2297 }
drhe3c41372001-09-17 20:25:58 +00002298 }
danielk1977a21c6b62005-01-24 10:25:59 +00002299 }else{
drhadbca9c2001-09-27 15:11:53 +00002300 char zBuf[30];
2301 int n;
2302 Index *pLoop;
2303 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002304 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002305 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002306 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002307 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002308 }
2309
drhe5f9c642003-01-13 23:27:31 +00002310 /* Check for authorization to create an index.
2311 */
2312#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002313 {
drhfdd6e852005-12-16 01:06:16 +00002314 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002315 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002316 goto exit_create_index;
2317 }
2318 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002319 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002320 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002321 goto exit_create_index;
2322 }
drhe5f9c642003-01-13 23:27:31 +00002323 }
2324#endif
2325
drh75897232000-05-29 14:26:00 +00002326 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002327 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002328 ** So create a fake list to simulate this.
2329 */
2330 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002331 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2332 nullId.n = strlen((char*)nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002333 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002334 if( pList==0 ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002335 pList->a[0].sortOrder = sortOrder;
drh75897232000-05-29 14:26:00 +00002336 }
2337
danielk1977b3bf5562006-01-10 17:58:23 +00002338 /* Figure out how many bytes of space are required to store explicitly
2339 ** specified collation sequence names.
2340 */
2341 for(i=0; i<pList->nExpr; i++){
2342 Expr *pExpr = pList->a[i].pExpr;
2343 if( pExpr ){
2344 nExtra += (1 + strlen(pExpr->pColl->zName));
2345 }
2346 }
2347
drh75897232000-05-29 14:26:00 +00002348 /*
2349 ** Allocate the index structure.
2350 */
drhfdd6e852005-12-16 01:06:16 +00002351 nName = strlen(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002352 nCol = pList->nExpr;
2353 pIndex = sqliteMalloc(
2354 sizeof(Index) + /* Index structure */
2355 sizeof(int)*nCol + /* Index.aiColumn */
2356 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2357 sizeof(char *)*nCol + /* Index.azColl */
2358 sizeof(u8)*nCol + /* Index.aSortOrder */
2359 nName + 1 + /* Index.zName */
2360 nExtra /* Collation sequence names */
2361 );
drh6f7adc82006-01-11 21:41:20 +00002362 if( sqlite3ThreadDataReadOnly()->mallocFailed ) goto exit_create_index;
danielk1977b3bf5562006-01-10 17:58:23 +00002363 pIndex->aiColumn = (int *)(&pIndex[1]);
2364 pIndex->aiRowEst = (int *)(&pIndex->aiColumn[nCol]);
2365 pIndex->azColl = (char **)(&pIndex->aiRowEst[nCol+1]);
2366 pIndex->aSortOrder = (u8 *)(&pIndex->azColl[nCol]);
2367 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2368 zExtra = (char *)(&pIndex->zName[nName+1]);
drh75897232000-05-29 14:26:00 +00002369 strcpy(pIndex->zName, zName);
2370 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002371 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002372 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002373 pIndex->autoIndex = pName==0;
danielk1977da184232006-01-05 11:34:32 +00002374 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002375
drhfdd6e852005-12-16 01:06:16 +00002376 /* Check to see if we should honor DESC requests on index columns
2377 */
danielk1977da184232006-01-05 11:34:32 +00002378 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002379 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002380 }else{
2381 sortOrderMask = 0; /* Ignore DESC */
2382 }
2383
drh1ccde152000-06-17 13:12:39 +00002384 /* Scan the names of the columns of the table to be indexed and
2385 ** load the column indices into the Index structure. Report an error
2386 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002387 */
drhfdd6e852005-12-16 01:06:16 +00002388 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2389 const char *zColName = pListItem->zName;
2390 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002391 int requestedSortOrder;
danielk1977b3bf5562006-01-10 17:58:23 +00002392 char *zColl; /* Collation sequence */
2393
drhfdd6e852005-12-16 01:06:16 +00002394 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2395 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002396 }
2397 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002398 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002399 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002400 goto exit_create_index;
2401 }
drh967e8b72000-06-21 13:59:10 +00002402 pIndex->aiColumn[i] = j;
drhfdd6e852005-12-16 01:06:16 +00002403 if( pListItem->pExpr ){
2404 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002405 zColl = zExtra;
2406 strcpy(zExtra, pListItem->pExpr->pColl->zName);
2407 zExtra += (strlen(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002408 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002409 zColl = pTab->aCol[j].zColl;
2410 if( !zColl ){
2411 zColl = db->pDfltColl->zName;
2412 }
danielk19770202b292004-06-09 09:55:16 +00002413 }
danielk1977b3bf5562006-01-10 17:58:23 +00002414 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002415 goto exit_create_index;
2416 }
danielk1977b3bf5562006-01-10 17:58:23 +00002417 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002418 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
danielk1977b3bf5562006-01-10 17:58:23 +00002419 pIndex->aSortOrder[i] = requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002420 }
drh51147ba2005-07-23 22:59:55 +00002421 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002422
danielk1977d8123362004-06-12 09:25:12 +00002423 if( pTab==pParse->pNewTable ){
2424 /* This routine has been called to create an automatic index as a
2425 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2426 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2427 ** i.e. one of:
2428 **
2429 ** CREATE TABLE t(x PRIMARY KEY, y);
2430 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2431 **
2432 ** Either way, check to see if the table already has such an index. If
2433 ** so, don't bother creating this one. This only applies to
2434 ** automatically created indices. Users can do as they wish with
2435 ** explicit indices.
2436 */
2437 Index *pIdx;
2438 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2439 int k;
2440 assert( pIdx->onError!=OE_None );
2441 assert( pIdx->autoIndex );
2442 assert( pIndex->onError!=OE_None );
2443
2444 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2445 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002446 const char *z1 = pIdx->azColl[k];
2447 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002448 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002449 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2450 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002451 }
2452 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002453 if( pIdx->onError!=pIndex->onError ){
2454 /* This constraint creates the same index as a previous
2455 ** constraint specified somewhere in the CREATE TABLE statement.
2456 ** However the ON CONFLICT clauses are different. If both this
2457 ** constraint and the previous equivalent constraint have explicit
2458 ** ON CONFLICT clauses this is an error. Otherwise, use the
2459 ** explicitly specified behaviour for the index.
2460 */
2461 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2462 sqlite3ErrorMsg(pParse,
2463 "conflicting ON CONFLICT clauses specified", 0);
2464 }
2465 if( pIdx->onError==OE_Default ){
2466 pIdx->onError = pIndex->onError;
2467 }
2468 }
danielk1977d8123362004-06-12 09:25:12 +00002469 goto exit_create_index;
2470 }
2471 }
2472 }
2473
drh75897232000-05-29 14:26:00 +00002474 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002475 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002476 */
drh234c39d2004-07-24 03:30:47 +00002477 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002478 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002479 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drh3c8bf552003-07-01 18:13:14 +00002480 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002481 if( p ){
2482 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002483 goto exit_create_index;
2484 }
drh5e00f6c2001-09-13 13:46:56 +00002485 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002486 if( pTblName!=0 ){
2487 pIndex->tnum = db->init.newTnum;
2488 }
drhd78eeee2001-09-13 16:18:53 +00002489 }
2490
drh1d85d932004-02-14 23:05:52 +00002491 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002492 ** involves writing the index into the master table and filling in the
2493 ** index with the current table contents.
2494 **
drh1d85d932004-02-14 23:05:52 +00002495 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2496 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002497 ** CREATE INDEX statements are read out of the master table. In
2498 ** the latter case the index already exists on disk, which is why
2499 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002500 **
danielk1977cbb18d22004-05-28 11:37:27 +00002501 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002502 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2503 ** has just been created, it contains no data and the index initialization
2504 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002505 */
drh1d85d932004-02-14 23:05:52 +00002506 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002507 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002508 char *zStmt;
2509 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002510
danielk19774adee202004-05-08 08:23:19 +00002511 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002512 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002513
drhfdd6e852005-12-16 01:06:16 +00002514
drh063336a2004-11-05 20:58:39 +00002515 /* Create the rootpage for the index
2516 */
drhaee128d2005-02-14 20:48:18 +00002517 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002518 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002519 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2520
2521 /* Gather the complete text of the CREATE INDEX statement into
2522 ** the zStmt variable
2523 */
drhe0bc4042002-06-25 01:09:11 +00002524 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002525 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002526 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002527 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002528 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002529 pName->z);
2530 }else{
2531 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002532 /* zStmt = sqlite3MPrintf(""); */
2533 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002534 }
drh063336a2004-11-05 20:58:39 +00002535
2536 /* Add an entry in sqlite_master for this index
2537 */
2538 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002539 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002540 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2541 pIndex->zName,
2542 pTab->zName,
2543 zStmt
2544 );
2545 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2546 sqliteFree(zStmt);
2547
danielk1977a21c6b62005-01-24 10:25:59 +00002548 /* Fill the index with data and reparse the schema. Code an OP_Expire
2549 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002550 */
danielk1977cbb18d22004-05-28 11:37:27 +00002551 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002552 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002553 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002554 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2555 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002556 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002557 }
drh75897232000-05-29 14:26:00 +00002558 }
2559
danielk1977d8123362004-06-12 09:25:12 +00002560 /* When adding an index to the list of indices for a table, make
2561 ** sure all indices labeled OE_Replace come after all those labeled
2562 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2563 ** and INSERT.
2564 */
drh234c39d2004-07-24 03:30:47 +00002565 if( db->init.busy || pTblName==0 ){
2566 if( onError!=OE_Replace || pTab->pIndex==0
2567 || pTab->pIndex->onError==OE_Replace){
2568 pIndex->pNext = pTab->pIndex;
2569 pTab->pIndex = pIndex;
2570 }else{
2571 Index *pOther = pTab->pIndex;
2572 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2573 pOther = pOther->pNext;
2574 }
2575 pIndex->pNext = pOther->pNext;
2576 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002577 }
drh234c39d2004-07-24 03:30:47 +00002578 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002579 }
danielk1977d8123362004-06-12 09:25:12 +00002580
drh75897232000-05-29 14:26:00 +00002581 /* Clean up before exiting */
2582exit_create_index:
drh956bc922004-07-24 17:38:29 +00002583 if( pIndex ){
2584 freeIndex(pIndex);
2585 }
danielk19770202b292004-06-09 09:55:16 +00002586 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002587 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002588 sqliteFree(zName);
2589 return;
2590}
2591
2592/*
drhd28bcb32005-12-21 14:43:11 +00002593** Generate code to make sure the file format number is at least minFormat.
2594** The generated code will increase the file format number if necessary.
2595*/
2596void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2597 Vdbe *v;
2598 v = sqlite3GetVdbe(pParse);
2599 if( v ){
2600 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
2601 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2602 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
2603 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2604 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
2605 }
2606}
2607
2608/*
drh51147ba2005-07-23 22:59:55 +00002609** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002610** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002611**
2612** aiRowEst[0] is suppose to contain the number of elements in the index.
2613** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2614** number of rows in the table that match any particular value of the
2615** first column of the index. aiRowEst[2] is an estimate of the number
2616** of rows that match any particular combiniation of the first 2 columns
2617** of the index. And so forth. It must always be the case that
2618*
2619** aiRowEst[N]<=aiRowEst[N-1]
2620** aiRowEst[N]>=1
2621**
2622** Apart from that, we have little to go on besides intuition as to
2623** how aiRowEst[] should be initialized. The numbers generated here
2624** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002625*/
2626void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002627 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002628 int i;
drh28c4cf42005-07-27 20:41:43 +00002629 assert( a!=0 );
2630 a[0] = 1000000;
drh3adc9ce2005-07-28 16:51:51 +00002631 for(i=pIdx->nColumn; i>=1; i--){
2632 a[i] = 10;
drh28c4cf42005-07-27 20:41:43 +00002633 }
2634 if( pIdx->onError!=OE_None ){
2635 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002636 }
2637}
2638
2639/*
drh74e24cd2002-01-09 03:19:59 +00002640** This routine will drop an existing named index. This routine
2641** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002642*/
drh4d91a702006-01-04 15:54:36 +00002643void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002644 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002645 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002646 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002647 int iDb;
drh75897232000-05-29 14:26:00 +00002648
drh6f7adc82006-01-11 21:41:20 +00002649 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00002650 goto exit_drop_index;
2651 }
drhd24cc422003-03-27 12:51:24 +00002652 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002653 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2654 goto exit_drop_index;
2655 }
danielk19774adee202004-05-08 08:23:19 +00002656 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002657 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002658 if( !ifExists ){
2659 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2660 }
drha6ecd332004-06-10 00:29:09 +00002661 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002662 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002663 }
drh485b39b2002-07-13 03:11:52 +00002664 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002665 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002666 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002667 goto exit_drop_index;
2668 }
danielk1977da184232006-01-05 11:34:32 +00002669 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002670#ifndef SQLITE_OMIT_AUTHORIZATION
2671 {
2672 int code = SQLITE_DROP_INDEX;
2673 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002674 const char *zDb = db->aDb[iDb].zName;
2675 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002676 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002677 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002678 }
danielk1977da184232006-01-05 11:34:32 +00002679 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002680 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002681 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002682 }
drhed6c8672003-01-12 18:02:16 +00002683 }
drhe5f9c642003-01-13 23:27:31 +00002684#endif
drh75897232000-05-29 14:26:00 +00002685
2686 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002687 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002688 if( v ){
drhb17131a2004-11-05 22:18:49 +00002689 sqlite3NestedParse(pParse,
2690 "DELETE FROM %Q.%s WHERE name=%Q",
2691 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2692 pIndex->zName
2693 );
2694 sqlite3ChangeCookie(db, v, iDb);
2695 destroyRootPage(pParse, pIndex->tnum, iDb);
2696 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002697 }
2698
drhd24cc422003-03-27 12:51:24 +00002699exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002700 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002701}
2702
2703/*
drh13449892005-09-07 21:22:45 +00002704** ppArray points into a structure where there is an array pointer
2705** followed by two integers. The first integer is the
2706** number of elements in the structure array. The second integer
2707** is the number of allocated slots in the array.
2708**
2709** In other words, the structure looks something like this:
2710**
2711** struct Example1 {
2712** struct subElem *aEntry;
2713** int nEntry;
2714** int nAlloc;
2715** }
2716**
2717** The pnEntry parameter points to the equivalent of Example1.nEntry.
2718**
2719** This routine allocates a new slot in the array, zeros it out,
2720** and returns its index. If malloc fails a negative number is returned.
2721**
2722** szEntry is the sizeof of a single array entry. initSize is the
2723** number of array entries allocated on the initial allocation.
2724*/
2725int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
2726 char *p;
2727 int *an = (int*)&ppArray[1];
2728 if( an[0]>=an[1] ){
2729 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002730 int newSize;
2731 newSize = an[1]*2 + initSize;
2732 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002733 if( pNew==0 ){
2734 return -1;
2735 }
drh5360ad32005-09-08 00:13:27 +00002736 an[1] = newSize;
drh13449892005-09-07 21:22:45 +00002737 *ppArray = pNew;
2738 }
2739 p = *ppArray;
2740 memset(&p[an[0]*szEntry], 0, szEntry);
2741 return an[0]++;
2742}
2743
2744/*
drh75897232000-05-29 14:26:00 +00002745** Append a new element to the given IdList. Create a new IdList if
2746** need be.
drhdaffd0e2001-04-11 14:28:42 +00002747**
2748** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002749*/
danielk19774adee202004-05-08 08:23:19 +00002750IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002751 int i;
drh75897232000-05-29 14:26:00 +00002752 if( pList==0 ){
2753 pList = sqliteMalloc( sizeof(IdList) );
2754 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002755 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002756 }
drh13449892005-09-07 21:22:45 +00002757 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
2758 if( i<0 ){
2759 sqlite3IdListDelete(pList);
2760 return 0;
drh75897232000-05-29 14:26:00 +00002761 }
drh13449892005-09-07 21:22:45 +00002762 pList->a[i].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002763 return pList;
2764}
2765
2766/*
drhfe05af82005-07-21 03:14:59 +00002767** Delete an IdList.
2768*/
2769void sqlite3IdListDelete(IdList *pList){
2770 int i;
2771 if( pList==0 ) return;
2772 for(i=0; i<pList->nId; i++){
2773 sqliteFree(pList->a[i].zName);
2774 }
2775 sqliteFree(pList->a);
2776 sqliteFree(pList);
2777}
2778
2779/*
2780** Return the index in pList of the identifier named zId. Return -1
2781** if not found.
2782*/
2783int sqlite3IdListIndex(IdList *pList, const char *zName){
2784 int i;
2785 if( pList==0 ) return -1;
2786 for(i=0; i<pList->nId; i++){
2787 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2788 }
2789 return -1;
2790}
2791
2792/*
drhad3cab52002-05-24 02:04:32 +00002793** Append a new table name to the given SrcList. Create a new SrcList if
2794** need be. A new entry is created in the SrcList even if pToken is NULL.
2795**
2796** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002797**
2798** If pDatabase is not null, it means that the table has an optional
2799** database name prefix. Like this: "database.table". The pDatabase
2800** points to the table name and the pTable points to the database name.
2801** The SrcList.a[].zName field is filled with the table name which might
2802** come from pTable (if pDatabase is NULL) or from pDatabase.
2803** SrcList.a[].zDatabase is filled with the database name from pTable,
2804** or with NULL if no database is specified.
2805**
2806** In other words, if call like this:
2807**
danielk19774adee202004-05-08 08:23:19 +00002808** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002809**
2810** Then B is a table name and the database name is unspecified. If called
2811** like this:
2812**
danielk19774adee202004-05-08 08:23:19 +00002813** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002814**
2815** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002816*/
danielk19774adee202004-05-08 08:23:19 +00002817SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002818 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002819 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002820 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002821 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002822 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002823 }
drh4305d102003-07-30 12:34:12 +00002824 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002825 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002826 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002827 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002828 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002829 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002830 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002831 return 0;
2832 }
drh113088e2003-03-20 01:16:58 +00002833 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002834 }
drha99db3b2004-06-19 14:49:12 +00002835 pItem = &pList->a[pList->nSrc];
2836 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002837 if( pDatabase && pDatabase->z==0 ){
2838 pDatabase = 0;
2839 }
2840 if( pDatabase && pTable ){
2841 Token *pTemp = pDatabase;
2842 pDatabase = pTable;
2843 pTable = pTemp;
2844 }
drha99db3b2004-06-19 14:49:12 +00002845 pItem->zName = sqlite3NameFromToken(pTable);
2846 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2847 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002848 pList->nSrc++;
2849 return pList;
2850}
2851
2852/*
drh63eb5f22003-04-29 16:20:44 +00002853** Assign cursors to all tables in a SrcList
2854*/
danielk19774adee202004-05-08 08:23:19 +00002855void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002856 int i;
drh9b3187e2005-01-18 14:45:47 +00002857 struct SrcList_item *pItem;
drh6f7adc82006-01-11 21:41:20 +00002858 assert(pList || sqlite3ThreadDataReadOnly()->mallocFailed);
danielk1977261919c2005-12-06 12:52:59 +00002859 if( pList ){
2860 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2861 if( pItem->iCursor>=0 ) break;
2862 pItem->iCursor = pParse->nTab++;
2863 if( pItem->pSelect ){
2864 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2865 }
drh63eb5f22003-04-29 16:20:44 +00002866 }
2867 }
2868}
2869
2870/*
drh75897232000-05-29 14:26:00 +00002871** Add an alias to the last identifier on the given identifier list.
2872*/
danielk19774adee202004-05-08 08:23:19 +00002873void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002874 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002875 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002876 }
2877}
2878
2879/*
drhad3cab52002-05-24 02:04:32 +00002880** Delete an entire SrcList including all its substructure.
2881*/
danielk19774adee202004-05-08 08:23:19 +00002882void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002883 int i;
drhbe5c89a2004-07-26 00:31:09 +00002884 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002885 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002886 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2887 sqliteFree(pItem->zDatabase);
2888 sqliteFree(pItem->zName);
2889 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002890 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002891 sqlite3SelectDelete(pItem->pSelect);
2892 sqlite3ExprDelete(pItem->pOn);
2893 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002894 }
drh75897232000-05-29 14:26:00 +00002895 sqliteFree(pList);
2896}
2897
drh982cef72000-05-30 16:27:03 +00002898/*
drhc4a3c772001-04-04 11:48:57 +00002899** Begin a transaction
2900*/
drh684917c2004-10-05 02:41:42 +00002901void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002902 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002903 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002904 int i;
drh5e00f6c2001-09-13 13:46:56 +00002905
drh001bbcb2003-03-19 03:14:00 +00002906 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002907 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002908 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002909
2910 v = sqlite3GetVdbe(pParse);
2911 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002912 if( type!=TK_DEFERRED ){
2913 for(i=0; i<db->nDb; i++){
2914 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2915 }
2916 }
danielk19771d850a72004-05-31 08:26:49 +00002917 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002918}
2919
2920/*
2921** Commit a transaction
2922*/
danielk19774adee202004-05-08 08:23:19 +00002923void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002924 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002925 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002926
drh001bbcb2003-03-19 03:14:00 +00002927 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002928 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002929 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002930
2931 v = sqlite3GetVdbe(pParse);
2932 if( v ){
2933 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002934 }
drhc4a3c772001-04-04 11:48:57 +00002935}
2936
2937/*
2938** Rollback a transaction
2939*/
danielk19774adee202004-05-08 08:23:19 +00002940void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002941 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002942 Vdbe *v;
2943
drh001bbcb2003-03-19 03:14:00 +00002944 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
drh6f7adc82006-01-11 21:41:20 +00002945 if( pParse->nErr || sqlite3ThreadDataReadOnly()->mallocFailed ) return;
danielk19774adee202004-05-08 08:23:19 +00002946 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002947
danielk19774adee202004-05-08 08:23:19 +00002948 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002949 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002950 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002951 }
drhc4a3c772001-04-04 11:48:57 +00002952}
drhf57b14a2001-09-14 18:54:08 +00002953
2954/*
drhdc3ff9c2004-08-18 02:10:15 +00002955** Make sure the TEMP database is open and available for use. Return
2956** the number of errors. Leave any error messages in the pParse structure.
2957*/
2958static int sqlite3OpenTempDatabase(Parse *pParse){
2959 sqlite3 *db = pParse->db;
2960 if( db->aDb[1].pBt==0 && !pParse->explain ){
2961 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2962 if( rc!=SQLITE_OK ){
2963 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2964 "file for storing temporary tables");
2965 pParse->rc = rc;
2966 return 1;
2967 }
2968 if( db->flags & !db->autoCommit ){
2969 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2970 if( rc!=SQLITE_OK ){
2971 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2972 "the temporary database file");
2973 pParse->rc = rc;
2974 return 1;
2975 }
2976 }
danielk197714db2662006-01-09 16:12:04 +00002977 assert( db->aDb[1].pSchema );
drhdc3ff9c2004-08-18 02:10:15 +00002978 }
2979 return 0;
2980}
2981
2982/*
drh80242052004-06-09 00:48:12 +00002983** Generate VDBE code that will verify the schema cookie and start
2984** a read-transaction for all named database files.
2985**
2986** It is important that all schema cookies be verified and all
2987** read transactions be started before anything else happens in
2988** the VDBE program. But this routine can be called after much other
2989** code has been generated. So here is what we do:
2990**
drhc275b4e2004-07-19 17:25:24 +00002991** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002992** will jump to a subroutine at the end of the program. Then we
2993** record every database that needs its schema verified in the
2994** pParse->cookieMask field. Later, after all other code has been
2995** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002996** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002997** will be made to point to that subroutine. The generation of the
2998** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002999**
3000** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3001** schema on any databases. This can be used to position the OP_Goto
3002** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003003*/
danielk19774adee202004-05-08 08:23:19 +00003004void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003005 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003006 Vdbe *v;
3007 int mask;
3008
3009 v = sqlite3GetVdbe(pParse);
3010 if( v==0 ) return; /* This only happens if there was a prior error */
3011 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003012 if( pParse->cookieGoto==0 ){
3013 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003014 }
drhc275b4e2004-07-19 17:25:24 +00003015 if( iDb>=0 ){
3016 assert( iDb<db->nDb );
3017 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
3018 assert( iDb<32 );
3019 mask = 1<<iDb;
3020 if( (pParse->cookieMask & mask)==0 ){
3021 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003022 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003023 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003024 sqlite3OpenTempDatabase(pParse);
3025 }
drhc275b4e2004-07-19 17:25:24 +00003026 }
drh001bbcb2003-03-19 03:14:00 +00003027 }
drh001bbcb2003-03-19 03:14:00 +00003028}
3029
3030/*
drh1c928532002-01-31 15:54:21 +00003031** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003032** might change the database.
3033**
3034** This routine starts a new transaction if we are not already within
3035** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003036** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003037** be set for operations that might fail (due to a constraint) part of
3038** the way through and which will need to undo some writes without having to
3039** rollback the whole transaction. For operations where all constraints
3040** can be checked before any changes are made to the database, it is never
3041** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003042**
drh8bf8dc92003-05-17 17:35:10 +00003043** Only database iDb and the temp database are made writable by this call.
3044** If iDb==0, then the main and temp databases are made writable. If
3045** iDb==1 then only the temp database is made writable. If iDb>1 then the
3046** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003047*/
drh7f0f12e2004-05-21 13:39:50 +00003048void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003049 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003050 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003051 sqlite3CodeVerifySchema(pParse, iDb);
3052 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003053 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00003054 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00003055 }
danielk197753c0f742005-03-29 03:10:59 +00003056 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003057 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003058 }
3059}
3060
drh4343fea2004-11-05 23:46:15 +00003061/*
3062** Check to see if pIndex uses the collating sequence pColl. Return
3063** true if it does and false if it does not.
3064*/
3065#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003066static int collationMatch(const char *zColl, Index *pIndex){
3067 int i;
3068 for(i=0; i<pIndex->nColumn; i++){
3069 const char *z = pIndex->azColl[i];
3070 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3071 return 1;
3072 }
drh4343fea2004-11-05 23:46:15 +00003073 }
3074 return 0;
3075}
3076#endif
3077
3078/*
3079** Recompute all indices of pTab that use the collating sequence pColl.
3080** If pColl==0 then recompute all indices of pTab.
3081*/
3082#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003083static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003084 Index *pIndex; /* An index associated with pTab */
3085
3086 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003087 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003088 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3089 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003090 sqlite3RefillIndex(pParse, pIndex, -1);
3091 }
3092 }
3093}
3094#endif
3095
3096/*
3097** Recompute all indices of all tables in all databases where the
3098** indices use the collating sequence pColl. If pColl==0 then recompute
3099** all indices everywhere.
3100*/
3101#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003102static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003103 Db *pDb; /* A single database */
3104 int iDb; /* The database index number */
3105 sqlite3 *db = pParse->db; /* The database connection */
3106 HashElem *k; /* For looping over tables in pDb */
3107 Table *pTab; /* A table in the database */
3108
3109 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
3110 if( pDb==0 ) continue;
danielk1977da184232006-01-05 11:34:32 +00003111 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003112 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003113 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003114 }
3115 }
3116}
3117#endif
3118
3119/*
drheee46cf2004-11-06 00:02:48 +00003120** Generate code for the REINDEX command.
3121**
3122** REINDEX -- 1
3123** REINDEX <collation> -- 2
3124** REINDEX ?<database>.?<tablename> -- 3
3125** REINDEX ?<database>.?<indexname> -- 4
3126**
3127** Form 1 causes all indices in all attached databases to be rebuilt.
3128** Form 2 rebuilds all indices in all databases that use the named
3129** collating function. Forms 3 and 4 rebuild the named index or all
3130** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003131*/
3132#ifndef SQLITE_OMIT_REINDEX
3133void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3134 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3135 char *z; /* Name of a table or index */
3136 const char *zDb; /* Name of the database */
3137 Table *pTab; /* A table in the database */
3138 Index *pIndex; /* An index associated with pTab */
3139 int iDb; /* The database index number */
3140 sqlite3 *db = pParse->db; /* The database connection */
3141 Token *pObjName; /* Name of the table or index to be reindexed */
3142
danielk197733a5edc2005-01-27 00:22:02 +00003143 /* Read the database schema. If an error occurs, leave an error message
3144 ** and code in pParse and return NULL. */
3145 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003146 return;
danielk197733a5edc2005-01-27 00:22:02 +00003147 }
3148
drhe497f002004-11-07 13:01:49 +00003149 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003150 reindexDatabases(pParse, 0);
3151 return;
drhe497f002004-11-07 13:01:49 +00003152 }else if( pName2==0 || pName2->z==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003153 assert( pName1->z );
danielk197714db2662006-01-09 16:12:04 +00003154 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
drh4343fea2004-11-05 23:46:15 +00003155 if( pColl ){
danielk1977b3bf5562006-01-10 17:58:23 +00003156 char *z = sqlite3StrNDup(pName1->z, pName1->n);
3157 if( z ){
3158 reindexDatabases(pParse, z);
3159 sqliteFree(z);
3160 }
drh4343fea2004-11-05 23:46:15 +00003161 return;
3162 }
3163 }
3164 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3165 if( iDb<0 ) return;
3166 z = sqlite3NameFromToken(pObjName);
3167 zDb = db->aDb[iDb].zName;
3168 pTab = sqlite3FindTable(db, z, zDb);
3169 if( pTab ){
3170 reindexTable(pParse, pTab, 0);
3171 sqliteFree(z);
3172 return;
3173 }
3174 pIndex = sqlite3FindIndex(db, z, zDb);
3175 sqliteFree(z);
3176 if( pIndex ){
3177 sqlite3BeginWriteOperation(pParse, 0, iDb);
3178 sqlite3RefillIndex(pParse, pIndex, -1);
3179 return;
3180 }
3181 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3182}
3183#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003184
3185/*
3186** Return a dynamicly allocated KeyInfo structure that can be used
3187** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3188**
3189** If successful, a pointer to the new structure is returned. In this case
3190** the caller is responsible for calling sqliteFree() on the returned
3191** pointer. If an error occurs (out of memory or missing collation
3192** sequence), NULL is returned and the state of pParse updated to reflect
3193** the error.
3194*/
3195KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3196 int i;
3197 int nCol = pIdx->nColumn;
3198 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3199 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
3200
3201 if( pKey ){
3202 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3203 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3204 for(i=0; i<nCol; i++){
3205 char *zColl = pIdx->azColl[i];
3206 assert( zColl );
3207 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3208 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3209 }
3210 pKey->nField = nCol;
3211 }
3212
3213 if( pParse->nErr ){
3214 sqliteFree(pKey);
3215 pKey = 0;
3216 }
3217 return pKey;
3218}