blob: 84464bfbf870af65f86c01410e617bbae621e867 [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**
danielk19779d1b2a22006-06-21 07:34:11 +000025** $Id: build.c,v 1.406 2006/06/21 07:34:11 danielk1977 Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
drhf57b14a2001-09-14 18:54:08 +000028#include <ctype.h>
drh75897232000-05-29 14:26:00 +000029
30/*
drhe0bc4042002-06-25 01:09:11 +000031** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000032** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000033*/
danielk19774adee202004-05-08 08:23:19 +000034void sqlite3BeginParse(Parse *pParse, int explainFlag){
drhe0bc4042002-06-25 01:09:11 +000035 pParse->explain = explainFlag;
drh7c972de2003-09-06 22:18:07 +000036 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000037}
38
danielk1977c00da102006-01-07 13:21:04 +000039#ifndef SQLITE_OMIT_SHARED_CACHE
40/*
41** The TableLock structure is only used by the sqlite3TableLock() and
42** codeTableLocks() functions.
43*/
44struct TableLock {
drhd698bc12006-03-23 23:33:26 +000045 int iDb; /* The database containing the table to be locked */
46 int iTab; /* The root page of the table to be locked */
47 u8 isWriteLock; /* True for write lock. False for a read lock */
48 const char *zName; /* Name of the table */
danielk1977c00da102006-01-07 13:21:04 +000049};
50
51/*
drhd698bc12006-03-23 23:33:26 +000052** Record the fact that we want to lock a table at run-time.
danielk1977c00da102006-01-07 13:21:04 +000053**
drhd698bc12006-03-23 23:33:26 +000054** The table to be locked has root page iTab and is found in database iDb.
55** A read or a write lock can be taken depending on isWritelock.
56**
57** This routine just records the fact that the lock is desired. The
58** code to make the lock occur is generated by a later call to
59** codeTableLocks() which occurs during sqlite3FinishCoding().
danielk1977c00da102006-01-07 13:21:04 +000060*/
61void sqlite3TableLock(
drhd698bc12006-03-23 23:33:26 +000062 Parse *pParse, /* Parsing context */
63 int iDb, /* Index of the database containing the table to lock */
64 int iTab, /* Root page number of the table to be locked */
65 u8 isWriteLock, /* True for a write lock */
66 const char *zName /* Name of the table to be locked */
danielk1977c00da102006-01-07 13:21:04 +000067){
68 int i;
69 int nBytes;
70 TableLock *p;
danielk1977c00da102006-01-07 13:21:04 +000071
drh6f7adc82006-01-11 21:41:20 +000072 if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
danielk1977c00da102006-01-07 13:21:04 +000073 return;
74 }
75
76 for(i=0; i<pParse->nTableLock; i++){
77 p = &pParse->aTableLock[i];
78 if( p->iDb==iDb && p->iTab==iTab ){
79 p->isWriteLock = (p->isWriteLock || isWriteLock);
80 return;
81 }
82 }
83
84 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
85 sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
86 if( pParse->aTableLock ){
87 p = &pParse->aTableLock[pParse->nTableLock++];
88 p->iDb = iDb;
89 p->iTab = iTab;
90 p->isWriteLock = isWriteLock;
91 p->zName = zName;
92 }
93}
94
95/*
96** Code an OP_TableLock instruction for each table locked by the
97** statement (configured by calls to sqlite3TableLock()).
98*/
99static void codeTableLocks(Parse *pParse){
100 int i;
101 Vdbe *pVdbe;
drh6f7adc82006-01-11 21:41:20 +0000102 assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
danielk1977c00da102006-01-07 13:21:04 +0000103
104 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
105 return;
106 }
107
108 for(i=0; i<pParse->nTableLock; i++){
109 TableLock *p = &pParse->aTableLock[i];
110 int p1 = p->iDb;
111 if( p->isWriteLock ){
112 p1 = -1*(p1+1);
113 }
114 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
115 }
116}
117#else
118 #define codeTableLocks(x)
119#endif
120
drhe0bc4042002-06-25 01:09:11 +0000121/*
drh75897232000-05-29 14:26:00 +0000122** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +0000123** parsed and a VDBE program to execute that statement has been
124** prepared. This routine puts the finishing touches on the
125** VDBE program and resets the pParse structure for the next
126** parse.
drh75897232000-05-29 14:26:00 +0000127**
128** Note that if an error occurred, it might be the case that
129** no VDBE code was generated.
130*/
drh80242052004-06-09 00:48:12 +0000131void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +0000132 sqlite3 *db;
drh80242052004-06-09 00:48:12 +0000133 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +0000134
danielk19779e128002006-01-18 16:51:35 +0000135 if( sqlite3MallocFailed() ) return;
drh205f48e2004-11-05 00:43:11 +0000136 if( pParse->nested ) return;
danielk1977441daf62005-02-01 03:46:43 +0000137 if( !pParse->pVdbe ){
danielk1977c30f9e72005-02-09 07:05:46 +0000138 if( pParse->rc==SQLITE_OK && pParse->nErr ){
139 pParse->rc = SQLITE_ERROR;
drhe134ff12006-02-18 16:36:45 +0000140 return;
danielk1977c30f9e72005-02-09 07:05:46 +0000141 }
danielk1977441daf62005-02-01 03:46:43 +0000142 }
danielk197748d0d862005-02-01 03:09:52 +0000143
drh80242052004-06-09 00:48:12 +0000144 /* Begin by generating some termination code at the end of the
145 ** vdbe program
146 */
147 db = pParse->db;
148 v = sqlite3GetVdbe(pParse);
149 if( v ){
150 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
drh0e3d7472004-06-19 17:33:07 +0000151
152 /* The cookie mask contains one bit for each database file open.
153 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
154 ** set for each database that is used. Generate code to start a
155 ** transaction on each used database and to verify the schema cookie
156 ** on each used database.
157 */
drhc275b4e2004-07-19 17:25:24 +0000158 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +0000159 u32 mask;
160 int iDb;
drhd654be82005-09-20 17:42:23 +0000161 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
drh80242052004-06-09 00:48:12 +0000162 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
163 if( (mask & pParse->cookieMask)==0 ) continue;
164 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drhc275b4e2004-07-19 17:25:24 +0000165 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +0000166 }
danielk1977f9e7dda2006-06-16 16:08:53 +0000167#ifndef SQLITE_OMIT_VIRTUALTABLE
168 if( pParse->pVirtualLock ){
169 char *vtab = (char *)pParse->pVirtualLock->pVtab;
170 sqlite3VdbeOp3(v, OP_VBegin, 0, 0, vtab, P3_VTAB);
171 }
172#endif
danielk1977c00da102006-01-07 13:21:04 +0000173
174 /* Once all the cookies have been verified and transactions opened,
175 ** obtain the required table-locks. This is a no-op unless the
176 ** shared-cache feature is enabled.
177 */
178 codeTableLocks(pParse);
drhc275b4e2004-07-19 17:25:24 +0000179 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +0000180 }
drh80242052004-06-09 00:48:12 +0000181
drh19e2d372005-08-29 23:00:03 +0000182#ifndef SQLITE_OMIT_TRACE
drh71c697e2004-08-08 23:39:19 +0000183 /* Add a No-op that contains the complete text of the compiled SQL
184 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +0000185 ** of the program.
186 **
drh23bf66d2004-12-14 03:34:34 +0000187 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +0000188 */
189 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh19e2d372005-08-29 23:00:03 +0000190#endif /* SQLITE_OMIT_TRACE */
drh71c697e2004-08-08 23:39:19 +0000191 }
192
drh3f7d4e42004-07-24 14:35:58 +0000193
drh80242052004-06-09 00:48:12 +0000194 /* Get the VDBE program ready for execution
195 */
drhe134ff12006-02-18 16:36:45 +0000196 if( v && pParse->nErr==0 && !sqlite3MallocFailed() ){
drhb86ccfb2003-01-28 23:13:10 +0000197 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000198 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +0000199 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
drh13449892005-09-07 21:22:45 +0000200 pParse->nTab+3, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000201 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000202 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000203 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000204 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000205 }
drha226d052002-09-25 19:04:07 +0000206 pParse->nTab = 0;
207 pParse->nMem = 0;
208 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000209 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000210 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000211 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000212}
213
214/*
drh205f48e2004-11-05 00:43:11 +0000215** Run the parser and code generator recursively in order to generate
216** code for the SQL statement given onto the end of the pParse context
217** currently under construction. When the parser is run recursively
218** this way, the final OP_Halt is not appended and other initialization
219** and finalization steps are omitted because those are handling by the
220** outermost parser.
221**
222** Not everything is nestable. This facility is designed to permit
223** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000224** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000225*/
226void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
227 va_list ap;
228 char *zSql;
drhf1974842004-11-05 03:56:00 +0000229# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
230 char saveBuf[SAVE_SZ];
231
drh205f48e2004-11-05 00:43:11 +0000232 if( pParse->nErr ) return;
233 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
234 va_start(ap, zFormat);
235 zSql = sqlite3VMPrintf(zFormat, ap);
236 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000237 if( zSql==0 ){
238 return; /* A malloc must have failed */
239 }
drh205f48e2004-11-05 00:43:11 +0000240 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000241 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
242 memset(&pParse->nVar, 0, SAVE_SZ);
drh4f26bb62005-09-08 14:17:20 +0000243 sqlite3RunParser(pParse, zSql, 0);
drh205f48e2004-11-05 00:43:11 +0000244 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000245 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000246 pParse->nested--;
247}
248
249/*
danielk19778a414492004-06-29 08:59:35 +0000250** Locate the in-memory structure that describes a particular database
251** table given the name of that table and (optionally) the name of the
252** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000253**
danielk19778a414492004-06-29 08:59:35 +0000254** If zDatabase is 0, all databases are searched for the table and the
255** first matching table is returned. (No checking for duplicate table
256** names is done.) The search order is TEMP first, then MAIN, then any
257** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000258**
danielk19774adee202004-05-08 08:23:19 +0000259** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000260*/
drh9bb575f2004-09-06 17:24:11 +0000261Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000262 Table *p = 0;
263 int i;
drh645f63e2004-06-22 13:22:40 +0000264 assert( zName!=0 );
danielk197753c0f742005-03-29 03:10:59 +0000265 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000266 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000267 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000268 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000269 if( p ) break;
270 }
drh74e24cd2002-01-09 03:19:59 +0000271 return p;
drh75897232000-05-29 14:26:00 +0000272}
273
274/*
danielk19778a414492004-06-29 08:59:35 +0000275** Locate the in-memory structure that describes a particular database
276** table given the name of that table and (optionally) the name of the
277** database containing the table. Return NULL if not found. Also leave an
278** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000279**
danielk19778a414492004-06-29 08:59:35 +0000280** The difference between this routine and sqlite3FindTable() is that this
281** routine leaves an error message in pParse->zErrMsg where
282** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000283*/
danielk19774adee202004-05-08 08:23:19 +0000284Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000285 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000286
danielk19778a414492004-06-29 08:59:35 +0000287 /* Read the database schema. If an error occurs, leave an error message
288 ** and code in pParse and return NULL. */
289 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
290 return 0;
291 }
292
danielk19774adee202004-05-08 08:23:19 +0000293 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000294 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000295 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000296 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000297 }else{
danielk19774adee202004-05-08 08:23:19 +0000298 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000299 }
drha6ecd332004-06-10 00:29:09 +0000300 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000301 }
302 return p;
303}
304
305/*
306** Locate the in-memory structure that describes
307** a particular index given the name of that index
308** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000309** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000310**
311** If zDatabase is 0, all databases are searched for the
312** table and the first matching index is returned. (No checking
313** for duplicate index names is done.) The search order is
314** TEMP first, then MAIN, then any auxiliary databases added
315** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000316*/
drh9bb575f2004-09-06 17:24:11 +0000317Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000318 Index *p = 0;
319 int i;
danielk197753c0f742005-03-29 03:10:59 +0000320 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000321 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk1977e501b892006-01-09 06:29:47 +0000322 Schema *pSchema = db->aDb[j].pSchema;
danielk19774adee202004-05-08 08:23:19 +0000323 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
danielk1977da184232006-01-05 11:34:32 +0000324 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
325 if( pSchema ){
326 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
327 }
drhd24cc422003-03-27 12:51:24 +0000328 if( p ) break;
329 }
drh74e24cd2002-01-09 03:19:59 +0000330 return p;
drh75897232000-05-29 14:26:00 +0000331}
332
333/*
drh956bc922004-07-24 17:38:29 +0000334** Reclaim the memory used by an index
335*/
336static void freeIndex(Index *p){
337 sqliteFree(p->zColAff);
338 sqliteFree(p);
339}
340
341/*
drh75897232000-05-29 14:26:00 +0000342** Remove the given index from the index hash table, and free
343** its memory structures.
344**
drhd229ca92002-01-09 13:30:41 +0000345** The index is removed from the database hash tables but
346** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000347** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000348*/
drh74161702006-02-24 02:53:49 +0000349static void sqliteDeleteIndex(Index *p){
drhd229ca92002-01-09 13:30:41 +0000350 Index *pOld;
danielk1977da184232006-01-05 11:34:32 +0000351 const char *zName = p->zName;
drhd24cc422003-03-27 12:51:24 +0000352
danielk1977da184232006-01-05 11:34:32 +0000353 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000354 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000355 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000356}
357
358/*
drhc96d8532005-05-03 12:30:33 +0000359** For the index called zIdxName which is found in the database iDb,
360** unlike that index from its Table then remove the index from
361** the index hash table and free all memory structures associated
362** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000363*/
drh9bb575f2004-09-06 17:24:11 +0000364void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000365 Index *pIndex;
366 int len;
danielk1977da184232006-01-05 11:34:32 +0000367 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
drh956bc922004-07-24 17:38:29 +0000368
369 len = strlen(zIdxName);
danielk1977da184232006-01-05 11:34:32 +0000370 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
drh956bc922004-07-24 17:38:29 +0000371 if( pIndex ){
372 if( pIndex->pTable->pIndex==pIndex ){
373 pIndex->pTable->pIndex = pIndex->pNext;
374 }else{
375 Index *p;
376 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
377 if( p && p->pNext==pIndex ){
378 p->pNext = pIndex->pNext;
379 }
drh5e00f6c2001-09-13 13:46:56 +0000380 }
drh956bc922004-07-24 17:38:29 +0000381 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000382 }
drh956bc922004-07-24 17:38:29 +0000383 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000384}
385
386/*
drhe0bc4042002-06-25 01:09:11 +0000387** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000388** a single database. This routine is called to reclaim memory
389** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000390** if there were schema changes during the transaction or if a
391** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000392**
393** If iDb<=0 then reset the internal schema tables for all database
394** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000395** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000396*/
drh9bb575f2004-09-06 17:24:11 +0000397void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drh1c2d8412003-03-31 00:30:47 +0000398 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000399
drh1c2d8412003-03-31 00:30:47 +0000400 assert( iDb>=0 && iDb<db->nDb );
drh1c2d8412003-03-31 00:30:47 +0000401 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000402 Db *pDb = &db->aDb[i];
danielk1977da184232006-01-05 11:34:32 +0000403 if( pDb->pSchema ){
danielk1977de0fe3e2006-01-06 06:33:12 +0000404 sqlite3SchemaFree(pDb->pSchema);
drhd24cc422003-03-27 12:51:24 +0000405 }
drh1c2d8412003-03-31 00:30:47 +0000406 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000407 }
drh1c2d8412003-03-31 00:30:47 +0000408 assert( iDb==0 );
409 db->flags &= ~SQLITE_InternChanges;
410
411 /* If one or more of the auxiliary database files has been closed,
danielk1977311019b2006-01-10 07:14:23 +0000412 ** then remove them from the auxiliary database list. We take the
drh1c2d8412003-03-31 00:30:47 +0000413 ** opportunity to do this here since we have just deleted all of the
414 ** schema hash tables and therefore do not have to make any changes
415 ** to any of those tables.
416 */
drh4d189ca2004-02-12 18:46:38 +0000417 for(i=0; i<db->nDb; i++){
418 struct Db *pDb = &db->aDb[i];
419 if( pDb->pBt==0 ){
420 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
421 pDb->pAux = 0;
422 }
423 }
drh1c2d8412003-03-31 00:30:47 +0000424 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000425 struct Db *pDb = &db->aDb[i];
426 if( pDb->pBt==0 ){
427 sqliteFree(pDb->zName);
428 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000429 continue;
430 }
431 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000432 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000433 }
drh8bf8dc92003-05-17 17:35:10 +0000434 j++;
drh1c2d8412003-03-31 00:30:47 +0000435 }
436 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
437 db->nDb = j;
438 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
439 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
440 sqliteFree(db->aDb);
441 db->aDb = db->aDbStatic;
442 }
drhe0bc4042002-06-25 01:09:11 +0000443}
444
445/*
446** This routine is called whenever a rollback occurs. If there were
447** schema changes during the transaction, then we have to reset the
448** internal hash tables and reload them from disk.
449*/
drh9bb575f2004-09-06 17:24:11 +0000450void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000451 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000452 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000453 }
454}
455
456/*
457** This routine is called when a commit occurs.
458*/
drh9bb575f2004-09-06 17:24:11 +0000459void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000460 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000461}
462
463/*
drh956bc922004-07-24 17:38:29 +0000464** Clear the column names from a table or view.
465*/
466static void sqliteResetColumnNames(Table *pTable){
467 int i;
468 Column *pCol;
469 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000470 if( (pCol = pTable->aCol)!=0 ){
471 for(i=0; i<pTable->nCol; i++, pCol++){
472 sqliteFree(pCol->zName);
473 sqlite3ExprDelete(pCol->pDflt);
474 sqliteFree(pCol->zType);
danielk1977b3bf5562006-01-10 17:58:23 +0000475 sqliteFree(pCol->zColl);
drhdd5b2fa2005-03-28 03:39:55 +0000476 }
477 sqliteFree(pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000478 }
drh956bc922004-07-24 17:38:29 +0000479 pTable->aCol = 0;
480 pTable->nCol = 0;
481}
482
483/*
drh75897232000-05-29 14:26:00 +0000484** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000485** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000486**
487** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000488** the table data structure from the hash table. Nor does it remove
489** foreign keys from the sqlite.aFKey hash table. But it does destroy
490** memory structures of the indices and foreign keys associated with
491** the table.
drhdaffd0e2001-04-11 14:28:42 +0000492**
493** Indices associated with the table are unlinked from the "db"
494** data structure if db!=NULL. If db==NULL, indices attached to
495** the table are deleted, but it is assumed they have already been
496** unlinked.
drh75897232000-05-29 14:26:00 +0000497*/
drh9bb575f2004-09-06 17:24:11 +0000498void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000499 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000500 FKey *pFKey, *pNextFKey;
501
danielk1977de0fe3e2006-01-06 06:33:12 +0000502 db = 0;
503
drh75897232000-05-29 14:26:00 +0000504 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000505
drhed8a3bb2005-06-06 21:19:56 +0000506 /* Do not delete the table until the reference count reaches zero. */
507 pTable->nRef--;
508 if( pTable->nRef>0 ){
509 return;
510 }
511 assert( pTable->nRef==0 );
512
drhc2eef3b2002-08-31 18:53:06 +0000513 /* Delete all indices associated with this table
514 */
515 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
516 pNext = pIndex->pNext;
danielk1977da184232006-01-05 11:34:32 +0000517 assert( pIndex->pSchema==pTable->pSchema );
drh74161702006-02-24 02:53:49 +0000518 sqliteDeleteIndex(pIndex);
drhc2eef3b2002-08-31 18:53:06 +0000519 }
520
danielk1977576ec6b2005-01-21 11:55:25 +0000521#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000522 /* Delete all foreign keys associated with this table. The keys
523 ** should have already been unlinked from the db->aFKey hash table
524 */
525 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
526 pNextFKey = pFKey->pNextFrom;
danielk1977da184232006-01-05 11:34:32 +0000527 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
drhd24cc422003-03-27 12:51:24 +0000528 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000529 sqliteFree(pFKey);
530 }
danielk1977576ec6b2005-01-21 11:55:25 +0000531#endif
drhc2eef3b2002-08-31 18:53:06 +0000532
533 /* Delete the Table structure itself.
534 */
drh956bc922004-07-24 17:38:29 +0000535 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000536 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000537 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000538 sqlite3SelectDelete(pTable->pSelect);
drhffe07b22005-11-03 00:41:17 +0000539#ifndef SQLITE_OMIT_CHECK
540 sqlite3ExprDelete(pTable->pCheck);
541#endif
drhb9bb7c12006-06-11 23:41:55 +0000542 sqlite3VtabClear(pTable);
drh75897232000-05-29 14:26:00 +0000543 sqliteFree(pTable);
544}
545
546/*
drh5edc3122001-09-13 21:53:09 +0000547** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000548** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000549*/
drh9bb575f2004-09-06 17:24:11 +0000550void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000551 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000552 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000553 Db *pDb;
554
drhd229ca92002-01-09 13:30:41 +0000555 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000556 assert( iDb>=0 && iDb<db->nDb );
557 assert( zTabName && zTabName[0] );
558 pDb = &db->aDb[iDb];
danielk1977da184232006-01-05 11:34:32 +0000559 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
drh956bc922004-07-24 17:38:29 +0000560 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000561#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000562 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
563 int nTo = strlen(pF1->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +0000564 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
drh956bc922004-07-24 17:38:29 +0000565 if( pF2==pF1 ){
danielk1977da184232006-01-05 11:34:32 +0000566 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
drh956bc922004-07-24 17:38:29 +0000567 }else{
568 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
569 if( pF2 ){
570 pF2->pNextTo = pF1->pNextTo;
571 }
drhc2eef3b2002-08-31 18:53:06 +0000572 }
573 }
danielk1977576ec6b2005-01-21 11:55:25 +0000574#endif
drh956bc922004-07-24 17:38:29 +0000575 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000576 }
drh956bc922004-07-24 17:38:29 +0000577 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000578}
579
580/*
drha99db3b2004-06-19 14:49:12 +0000581** Given a token, return a string that consists of the text of that
582** token with any quotations removed. Space to hold the returned string
583** is obtained from sqliteMalloc() and must be freed by the calling
584** function.
drh75897232000-05-29 14:26:00 +0000585**
drhc96d8532005-05-03 12:30:33 +0000586** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000587** are not \000 terminated and are not persistent. The returned string
588** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000589*/
drha99db3b2004-06-19 14:49:12 +0000590char *sqlite3NameFromToken(Token *pName){
591 char *zName;
592 if( pName ){
drh2646da72005-12-09 20:02:05 +0000593 zName = sqliteStrNDup((char*)pName->z, pName->n);
drha99db3b2004-06-19 14:49:12 +0000594 sqlite3Dequote(zName);
595 }else{
596 zName = 0;
597 }
drh75897232000-05-29 14:26:00 +0000598 return zName;
599}
600
601/*
danielk1977cbb18d22004-05-28 11:37:27 +0000602** Open the sqlite_master table stored in database number iDb for
603** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000604*/
danielk1977c00da102006-01-07 13:21:04 +0000605void sqlite3OpenMasterTable(Parse *p, int iDb){
606 Vdbe *v = sqlite3GetVdbe(p);
607 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
danielk1977cbb18d22004-05-28 11:37:27 +0000608 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000609 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000610 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000611}
612
613/*
danielk1977cbb18d22004-05-28 11:37:27 +0000614** The token *pName contains the name of a database (either "main" or
615** "temp" or the name of an attached db). This routine returns the
616** index of the named database in db->aDb[], or -1 if the named db
617** does not exist.
618*/
drhff2d5ea2005-07-23 00:41:48 +0000619int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000620 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000621 int n; /* Number of characters in the name */
622 Db *pDb; /* A database whose name space is being searched */
623 char *zName; /* Name we are searching for */
624
625 zName = sqlite3NameFromToken(pName);
626 if( zName ){
627 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000628 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000629 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
630 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000631 break;
drh73c42a12004-11-20 18:13:10 +0000632 }
danielk1977cbb18d22004-05-28 11:37:27 +0000633 }
drh73c42a12004-11-20 18:13:10 +0000634 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000635 }
danielk1977576ec6b2005-01-21 11:55:25 +0000636 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000637}
638
drh0e3d7472004-06-19 17:33:07 +0000639/* The table or view or trigger name is passed to this routine via tokens
640** pName1 and pName2. If the table name was fully qualified, for example:
641**
642** CREATE TABLE xxx.yyy (...);
643**
644** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
645** the table name is not fully qualified, i.e.:
646**
647** CREATE TABLE yyy(...);
648**
649** Then pName1 is set to "yyy" and pName2 is "".
650**
651** This routine sets the *ppUnqual pointer to point at the token (pName1 or
652** pName2) that stores the unqualified table name. The index of the
653** database "xxx" is returned.
654*/
danielk1977ef2cb632004-05-29 02:37:19 +0000655int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000656 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000657 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000658 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
659 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000660){
drh0e3d7472004-06-19 17:33:07 +0000661 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000662 sqlite3 *db = pParse->db;
663
664 if( pName2 && pName2->n>0 ){
665 assert( !db->init.busy );
666 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000667 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000668 if( iDb<0 ){
669 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
670 pParse->nErr++;
671 return -1;
672 }
673 }else{
674 assert( db->init.iDb==0 || db->init.busy );
675 iDb = db->init.iDb;
676 *pUnqual = pName1;
677 }
678 return iDb;
679}
680
681/*
danielk1977d8123362004-06-12 09:25:12 +0000682** This routine is used to check if the UTF-8 string zName is a legal
683** unqualified name for a new schema object (table, index, view or
684** trigger). All names are legal except those that begin with the string
685** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
686** is reserved for internal use.
687*/
688int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000689 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000690 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000691 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000692 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
693 return SQLITE_ERROR;
694 }
695 return SQLITE_OK;
696}
697
698/*
drh75897232000-05-29 14:26:00 +0000699** Begin constructing a new table representation in memory. This is
700** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000701** to a CREATE TABLE statement. In particular, this routine is called
drh74161702006-02-24 02:53:49 +0000702** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000703** flag is true if the table should be stored in the auxiliary database
704** file instead of in the main database file. This is normally the case
705** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000706** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000707**
drhf57b3392001-10-08 13:22:32 +0000708** The new table record is initialized and put in pParse->pNewTable.
709** As more of the CREATE TABLE statement is parsed, additional action
710** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000711** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000712** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000713*/
danielk19774adee202004-05-08 08:23:19 +0000714void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000715 Parse *pParse, /* Parser context */
danielk1977cbb18d22004-05-28 11:37:27 +0000716 Token *pName1, /* First part of the name of the table or view */
717 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000718 int isTemp, /* True if this is a TEMP table */
drhfaa59552005-12-29 23:33:54 +0000719 int isView, /* True if this is a VIEW */
danielk1977f1a381e2006-06-16 08:01:02 +0000720 int isVirtual, /* True if this is a VIRTUAL table */
drhfaa59552005-12-29 23:33:54 +0000721 int noErr /* Do nothing if table already exists */
drhe5f9c642003-01-13 23:27:31 +0000722){
drh75897232000-05-29 14:26:00 +0000723 Table *pTable;
drh23bf66d2004-12-14 03:34:34 +0000724 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000725 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000726 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000727 int iDb; /* Database number to create the table in */
728 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000729
danielk1977cbb18d22004-05-28 11:37:27 +0000730 /* The table or view name to create is passed to this routine via tokens
731 ** pName1 and pName2. If the table name was fully qualified, for example:
732 **
733 ** CREATE TABLE xxx.yyy (...);
734 **
735 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
736 ** the table name is not fully qualified, i.e.:
737 **
738 ** CREATE TABLE yyy(...);
739 **
740 ** Then pName1 is set to "yyy" and pName2 is "".
741 **
742 ** The call below sets the pName pointer to point at the token (pName1 or
743 ** pName2) that stores the unqualified table name. The variable iDb is
744 ** set to the index of the database that the table or view is to be
745 ** created in.
746 */
danielk1977ef2cb632004-05-29 02:37:19 +0000747 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000748 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000749 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000750 /* If creating a temp table, the name may not be qualified */
751 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000752 return;
753 }
danielk197753c0f742005-03-29 03:10:59 +0000754 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000755
756 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000757 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000758 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000759 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000760 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000761 }
drh1d85d932004-02-14 23:05:52 +0000762 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000763#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000764 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000765 {
766 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000767 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000768 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000769 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000770 }
drhe5f9c642003-01-13 23:27:31 +0000771 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000772 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000773 code = SQLITE_CREATE_TEMP_VIEW;
774 }else{
775 code = SQLITE_CREATE_VIEW;
776 }
777 }else{
danielk197753c0f742005-03-29 03:10:59 +0000778 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000779 code = SQLITE_CREATE_TEMP_TABLE;
780 }else{
781 code = SQLITE_CREATE_TABLE;
782 }
783 }
danielk1977f1a381e2006-06-16 08:01:02 +0000784 if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000785 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000786 }
787 }
788#endif
drhf57b3392001-10-08 13:22:32 +0000789
drhf57b3392001-10-08 13:22:32 +0000790 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000791 ** index or table name in the same database. Issue an error message if
danielk19777e6ebfb2006-06-12 11:24:37 +0000792 ** it does. The exception is if the statement being parsed was passed
793 ** to an sqlite3_declare_vtab() call. In that case only the column names
794 ** and types will be used, so there is no need to test for namespace
795 ** collisions.
drhf57b3392001-10-08 13:22:32 +0000796 */
danielk19777e6ebfb2006-06-12 11:24:37 +0000797 if( !IN_DECLARE_VTAB ){
798 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
799 goto begin_table_error;
drhfaa59552005-12-29 23:33:54 +0000800 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000801 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
802 if( pTable ){
803 if( !noErr ){
804 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
805 }
806 goto begin_table_error;
807 }
808 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
809 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
810 goto begin_table_error;
811 }
drh75897232000-05-29 14:26:00 +0000812 }
danielk19777e6ebfb2006-06-12 11:24:37 +0000813
drh75897232000-05-29 14:26:00 +0000814 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000815 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000816 pParse->rc = SQLITE_NOMEM;
817 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000818 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000819 }
drh75897232000-05-29 14:26:00 +0000820 pTable->zName = zName;
drh4a324312001-12-21 14:30:42 +0000821 pTable->iPKey = -1;
danielk1977da184232006-01-05 11:34:32 +0000822 pTable->pSchema = db->aDb[iDb].pSchema;
drhed8a3bb2005-06-06 21:19:56 +0000823 pTable->nRef = 1;
danielk19774adee202004-05-08 08:23:19 +0000824 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000825 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000826
drh4794f732004-11-05 17:17:50 +0000827 /* If this is the magic sqlite_sequence table used by autoincrement,
828 ** then record a pointer to this table in the main database structure
829 ** so that INSERT can find the table easily.
830 */
831#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000832 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
danielk1977da184232006-01-05 11:34:32 +0000833 pTable->pSchema->pSeqTab = pTable;
drh4794f732004-11-05 17:17:50 +0000834 }
835#endif
836
drh17f71932002-02-21 12:01:27 +0000837 /* Begin generating the code that will insert the table record into
838 ** the SQLITE_MASTER table. Note in particular that we must go ahead
839 ** and allocate the record number for the table entry now. Before any
840 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
841 ** indices to be created and the table record must come before the
842 ** indices. Hence, the record number for the table must be allocated
843 ** now.
844 */
danielk19774adee202004-05-08 08:23:19 +0000845 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk197736963fd2005-02-19 08:18:05 +0000846 int lbl;
drhe321c292006-01-12 01:56:43 +0000847 int fileFormat;
danielk1977cbb18d22004-05-28 11:37:27 +0000848 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000849
danielk197736963fd2005-02-19 08:18:05 +0000850 /* If the file format and encoding in the database have not been set,
851 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000852 */
danielk197736963fd2005-02-19 08:18:05 +0000853 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
854 lbl = sqlite3VdbeMakeLabel(v);
855 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
drhe321c292006-01-12 01:56:43 +0000856 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
857 1 : SQLITE_DEFAULT_FILE_FORMAT;
858 sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000859 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
danielk197714db2662006-01-09 16:12:04 +0000860 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
danielk1977d008cfe2004-06-19 02:22:10 +0000861 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000862 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000863
drh4794f732004-11-05 17:17:50 +0000864 /* This just creates a place-holder record in the sqlite_master table.
865 ** The record created does not contain anything yet. It will be replaced
866 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000867 **
868 ** The rowid for the new entry is left on the top of the stack.
869 ** The rowid value is needed by the code that sqlite3EndTable will
870 ** generate.
drh4794f732004-11-05 17:17:50 +0000871 */
danielk1977f1a381e2006-06-16 08:01:02 +0000872#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
873 if( isView || isVirtual ){
danielk1977a21c6b62005-01-24 10:25:59 +0000874 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
875 }else
876#endif
877 {
878 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
879 }
danielk1977c00da102006-01-07 13:21:04 +0000880 sqlite3OpenMasterTable(pParse, iDb);
drhf0863fe2005-06-12 21:35:51 +0000881 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000882 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000883 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
884 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000885 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000886 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000887 }
drh23bf66d2004-12-14 03:34:34 +0000888
889 /* Normal (non-error) return. */
890 return;
891
892 /* If an error occurs, we jump here */
893begin_table_error:
894 sqliteFree(zName);
895 return;
drh75897232000-05-29 14:26:00 +0000896}
897
898/*
danielk1977c60e9b82005-01-31 12:42:29 +0000899** This macro is used to compare two strings in a case-insensitive manner.
900** It is slightly faster than calling sqlite3StrICmp() directly, but
901** produces larger code.
902**
903** WARNING: This macro is not compatible with the strcmp() family. It
904** returns true if the two strings are equal, otherwise false.
905*/
906#define STRICMP(x, y) (\
907sqlite3UpperToLower[*(unsigned char *)(x)]== \
908sqlite3UpperToLower[*(unsigned char *)(y)] \
909&& sqlite3StrICmp((x)+1,(y)+1)==0 )
910
911/*
drh75897232000-05-29 14:26:00 +0000912** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000913**
914** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000915** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000916** first to get things going. Then this routine is called for each
917** column.
drh75897232000-05-29 14:26:00 +0000918*/
danielk19774adee202004-05-08 08:23:19 +0000919void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000920 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000921 int i;
drha99db3b2004-06-19 14:49:12 +0000922 char *z;
drhc9b84a12002-06-20 11:36:48 +0000923 Column *pCol;
drh75897232000-05-29 14:26:00 +0000924 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000925 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000926 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000927 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000928 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000929 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000930 sqliteFree(z);
931 return;
932 }
933 }
drh75897232000-05-29 14:26:00 +0000934 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000935 Column *aNew;
936 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000937 if( aNew==0 ){
938 sqliteFree(z);
939 return;
940 }
drh6d4abfb2001-10-22 02:58:08 +0000941 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000942 }
drhc9b84a12002-06-20 11:36:48 +0000943 pCol = &p->aCol[p->nCol];
944 memset(pCol, 0, sizeof(p->aCol[0]));
945 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000946
947 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000948 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
949 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000950 */
danielk19774f057f92004-06-08 00:02:33 +0000951 pCol->affinity = SQLITE_AFF_NONE;
drhc9b84a12002-06-20 11:36:48 +0000952 p->nCol++;
drh75897232000-05-29 14:26:00 +0000953}
954
955/*
drh382c0242001-10-06 16:33:02 +0000956** This routine is called by the parser while in the middle of
957** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
958** been seen on a column. This routine sets the notNull flag on
959** the column currently under construction.
960*/
danielk19774adee202004-05-08 08:23:19 +0000961void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000962 Table *p;
963 int i;
964 if( (p = pParse->pNewTable)==0 ) return;
965 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000966 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000967}
968
969/*
danielk197752a83fb2005-01-31 12:56:44 +0000970** Scan the column type name zType (length nType) and return the
971** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000972**
973** This routine does a case-independent search of zType for the
974** substrings in the following table. If one of the substrings is
975** found, the corresponding affinity is returned. If zType contains
976** more than one of the substrings, entries toward the top of
977** the table take priority. For example, if zType is 'BLOBINT',
drh8a512562005-11-14 22:29:05 +0000978** SQLITE_AFF_INTEGER is returned.
danielk1977b3dff962005-02-01 01:21:55 +0000979**
980** Substring | Affinity
981** --------------------------------
982** 'INT' | SQLITE_AFF_INTEGER
983** 'CHAR' | SQLITE_AFF_TEXT
984** 'CLOB' | SQLITE_AFF_TEXT
985** 'TEXT' | SQLITE_AFF_TEXT
986** 'BLOB' | SQLITE_AFF_NONE
drh8a512562005-11-14 22:29:05 +0000987** 'REAL' | SQLITE_AFF_REAL
988** 'FLOA' | SQLITE_AFF_REAL
989** 'DOUB' | SQLITE_AFF_REAL
danielk1977b3dff962005-02-01 01:21:55 +0000990**
991** If none of the substrings in the above table are found,
992** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000993*/
drh8a512562005-11-14 22:29:05 +0000994char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000995 u32 h = 0;
996 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000997 const unsigned char *zIn = pType->z;
998 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000999
danielk1977b3dff962005-02-01 01:21:55 +00001000 while( zIn!=zEnd ){
1001 h = (h<<8) + sqlite3UpperToLower[*zIn];
1002 zIn++;
danielk1977201f7162005-02-01 02:13:29 +00001003 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1004 aff = SQLITE_AFF_TEXT;
1005 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1006 aff = SQLITE_AFF_TEXT;
1007 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1008 aff = SQLITE_AFF_TEXT;
1009 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
drh8a512562005-11-14 22:29:05 +00001010 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
danielk1977b3dff962005-02-01 01:21:55 +00001011 aff = SQLITE_AFF_NONE;
drh8a512562005-11-14 22:29:05 +00001012#ifndef SQLITE_OMIT_FLOATING_POINT
1013 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1014 && aff==SQLITE_AFF_NUMERIC ){
1015 aff = SQLITE_AFF_REAL;
1016 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1017 && aff==SQLITE_AFF_NUMERIC ){
1018 aff = SQLITE_AFF_REAL;
1019 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1020 && aff==SQLITE_AFF_NUMERIC ){
1021 aff = SQLITE_AFF_REAL;
1022#endif
danielk1977201f7162005-02-01 02:13:29 +00001023 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
drh8a512562005-11-14 22:29:05 +00001024 aff = SQLITE_AFF_INTEGER;
danielk1977b3dff962005-02-01 01:21:55 +00001025 break;
danielk197752a83fb2005-01-31 12:56:44 +00001026 }
1027 }
danielk1977b3dff962005-02-01 01:21:55 +00001028
1029 return aff;
danielk197752a83fb2005-01-31 12:56:44 +00001030}
1031
1032/*
drh382c0242001-10-06 16:33:02 +00001033** This routine is called by the parser while in the middle of
1034** parsing a CREATE TABLE statement. The pFirst token is the first
1035** token in the sequence of tokens that describe the type of the
1036** column currently under construction. pLast is the last token
1037** in the sequence. Use this information to construct a string
1038** that contains the typename of the column and store that string
1039** in zType.
1040*/
drh487e2622005-06-25 18:42:14 +00001041void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +00001042 Table *p;
drh487e2622005-06-25 18:42:14 +00001043 int i;
drhc9b84a12002-06-20 11:36:48 +00001044 Column *pCol;
drh487e2622005-06-25 18:42:14 +00001045
drh382c0242001-10-06 16:33:02 +00001046 if( (p = pParse->pNewTable)==0 ) return;
1047 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +00001048 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +00001049 pCol = &p->aCol[i];
drhd8919672005-09-10 15:35:06 +00001050 sqliteFree(pCol->zType);
drh487e2622005-06-25 18:42:14 +00001051 pCol->zType = sqlite3NameFromToken(pType);
drh8a512562005-11-14 22:29:05 +00001052 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +00001053}
1054
1055/*
danielk19777977a172004-11-09 12:44:37 +00001056** The expression is the default value for the most recently added column
1057** of the table currently under construction.
1058**
1059** Default value expressions must be constant. Raise an exception if this
1060** is not the case.
drhd9b02572001-04-15 00:37:09 +00001061**
1062** This routine is called by the parser while in the middle of
1063** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +00001064*/
danielk19777977a172004-11-09 12:44:37 +00001065void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +00001066 Table *p;
danielk19777977a172004-11-09 12:44:37 +00001067 Column *pCol;
drh42b9d7c2005-08-13 00:56:27 +00001068 if( (p = pParse->pNewTable)!=0 ){
1069 pCol = &(p->aCol[p->nCol-1]);
1070 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
1071 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1072 pCol->zName);
1073 }else{
1074 sqlite3ExprDelete(pCol->pDflt);
1075 pCol->pDflt = sqlite3ExprDup(pExpr);
1076 }
danielk19777977a172004-11-09 12:44:37 +00001077 }
1078 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +00001079}
1080
1081/*
drh4a324312001-12-21 14:30:42 +00001082** Designate the PRIMARY KEY for the table. pList is a list of names
1083** of columns that form the primary key. If pList is NULL, then the
1084** most recently added column of the table is the primary key.
1085**
1086** A table can have at most one primary key. If the table already has
1087** a primary key (and this is the second primary key) then create an
1088** error.
1089**
1090** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001091** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001092** field of the table under construction to be the index of the
1093** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1094** no INTEGER PRIMARY KEY.
1095**
1096** If the key is not an INTEGER PRIMARY KEY, then create a unique
1097** index for the key. No index is created for INTEGER PRIMARY KEYs.
1098*/
drh205f48e2004-11-05 00:43:11 +00001099void sqlite3AddPrimaryKey(
1100 Parse *pParse, /* Parsing context */
1101 ExprList *pList, /* List of field names to be indexed */
1102 int onError, /* What to do with a uniqueness conflict */
drhfdd6e852005-12-16 01:06:16 +00001103 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1104 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
drh205f48e2004-11-05 00:43:11 +00001105){
drh4a324312001-12-21 14:30:42 +00001106 Table *pTab = pParse->pNewTable;
1107 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001108 int iCol = -1, i;
danielk1977c7d54102006-06-15 07:29:00 +00001109 if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001110 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001111 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001112 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001113 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001114 }
1115 pTab->hasPrimKey = 1;
1116 if( pList==0 ){
1117 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001118 pTab->aCol[iCol].isPrimKey = 1;
1119 }else{
danielk19770202b292004-06-09 09:55:16 +00001120 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001121 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001122 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1123 break;
1124 }
drh78100cc2003-08-23 22:40:53 +00001125 }
drh6e4fc2c2005-09-15 21:24:51 +00001126 if( iCol<pTab->nCol ){
drh688c9f02005-09-16 02:48:01 +00001127 pTab->aCol[iCol].isPrimKey = 1;
drh6e4fc2c2005-09-15 21:24:51 +00001128 }
drh4a324312001-12-21 14:30:42 +00001129 }
danielk19770202b292004-06-09 09:55:16 +00001130 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001131 }
1132 if( iCol>=0 && iCol<pTab->nCol ){
1133 zType = pTab->aCol[iCol].zType;
1134 }
drhfdd6e852005-12-16 01:06:16 +00001135 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
1136 && sortOrder==SQLITE_SO_ASC ){
drh4a324312001-12-21 14:30:42 +00001137 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001138 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001139 pTab->autoInc = autoInc;
1140 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001141#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001142 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1143 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001144#endif
drh4a324312001-12-21 14:30:42 +00001145 }else{
drh4d91a702006-01-04 15:54:36 +00001146 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
drhe0194f22003-02-26 13:52:51 +00001147 pList = 0;
drh4a324312001-12-21 14:30:42 +00001148 }
drhe0194f22003-02-26 13:52:51 +00001149
1150primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001151 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001152 return;
drh4a324312001-12-21 14:30:42 +00001153}
1154
1155/*
drhffe07b22005-11-03 00:41:17 +00001156** Add a new CHECK constraint to the table currently under construction.
1157*/
1158void sqlite3AddCheckConstraint(
1159 Parse *pParse, /* Parsing context */
1160 Expr *pCheckExpr /* The check expression */
1161){
1162#ifndef SQLITE_OMIT_CHECK
1163 Table *pTab = pParse->pNewTable;
danielk1977c7d54102006-06-15 07:29:00 +00001164 if( pTab && !IN_DECLARE_VTAB ){
drhffe07b22005-11-03 00:41:17 +00001165 /* The CHECK expression must be duplicated so that tokens refer
1166 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
1167 ** statement */
1168 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
1169 }
1170#endif
1171 sqlite3ExprDelete(pCheckExpr);
1172}
1173
1174/*
drhd3d39e92004-05-20 22:16:29 +00001175** Set the collation function of the most recently parsed table column
1176** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001177*/
drhd3d39e92004-05-20 22:16:29 +00001178void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001179 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001180 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001181
danielk1977b8cbb872006-06-19 05:33:45 +00001182 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001183 i = p->nCol-1;
1184
danielk1977b3bf5562006-01-10 17:58:23 +00001185 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
1186 Index *pIdx;
danielk1977e7259292006-01-13 06:33:23 +00001187 p->aCol[i].zColl = sqliteStrNDup(zType, nType);
danielk1977b3bf5562006-01-10 17:58:23 +00001188
1189 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1190 ** then an index may have been created on this column before the
1191 ** collation type was added. Correct this if it is the case.
1192 */
1193 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1194 assert( pIdx->nColumn==1 );
1195 if( pIdx->aiColumn[0]==i ){
1196 pIdx->azColl[0] = p->aCol[i].zColl;
danielk19777cedc8d2004-06-10 10:50:08 +00001197 }
1198 }
1199 }
danielk19777cedc8d2004-06-10 10:50:08 +00001200}
1201
danielk1977466be562004-06-10 02:16:01 +00001202/*
1203** This function returns the collation sequence for database native text
1204** encoding identified by the string zName, length nName.
1205**
1206** If the requested collation sequence is not available, or not available
1207** in the database native encoding, the collation factory is invoked to
1208** request it. If the collation factory does not supply such a sequence,
1209** and the sequence is available in another text encoding, then that is
1210** returned instead.
1211**
1212** If no versions of the requested collations sequence are available, or
1213** another error occurs, NULL is returned and an error message written into
1214** pParse.
1215*/
danielk19770202b292004-06-09 09:55:16 +00001216CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001217 sqlite3 *db = pParse->db;
danielk197714db2662006-01-09 16:12:04 +00001218 u8 enc = ENC(db);
danielk19774dade032005-05-25 10:45:10 +00001219 u8 initbusy = db->init.busy;
danielk1977b3bf5562006-01-10 17:58:23 +00001220 CollSeq *pColl;
danielk19774dade032005-05-25 10:45:10 +00001221
danielk1977b3bf5562006-01-10 17:58:23 +00001222 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001223 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001224 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1225 if( !pColl ){
1226 if( nName<0 ){
1227 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001228 }
danielk19774dade032005-05-25 10:45:10 +00001229 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1230 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001231 }
1232 }
1233
danielk19770202b292004-06-09 09:55:16 +00001234 return pColl;
1235}
1236
1237
drh8e2ca022002-06-17 17:07:19 +00001238/*
drh3f7d4e42004-07-24 14:35:58 +00001239** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001240**
1241** The schema cookie is used to determine when the schema for the
1242** database changes. After each schema change, the cookie value
1243** changes. When a process first reads the schema it records the
1244** cookie. Thereafter, whenever it goes to access the database,
1245** it checks the cookie to make sure the schema has not changed
1246** since it was last read.
1247**
1248** This plan is not completely bullet-proof. It is possible for
1249** the schema to change multiple times and for the cookie to be
1250** set back to prior value. But schema changes are infrequent
1251** and the probability of hitting the same cookie value is only
1252** 1 chance in 2^32. So we're safe enough.
1253*/
drh9bb575f2004-09-06 17:24:11 +00001254void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
danielk1977da184232006-01-05 11:34:32 +00001255 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001256 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001257}
1258
1259/*
drh969fa7c2002-02-18 18:30:32 +00001260** Measure the number of characters needed to output the given
1261** identifier. The number returned includes any quotes used
1262** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001263**
1264** The estimate is conservative. It might be larger that what is
1265** really needed.
drh969fa7c2002-02-18 18:30:32 +00001266*/
1267static int identLength(const char *z){
1268 int n;
drh17f71932002-02-21 12:01:27 +00001269 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001270 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001271 }
drh234c39d2004-07-24 03:30:47 +00001272 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001273}
1274
1275/*
1276** Write an identifier onto the end of the given string. Add
1277** quote characters as needed.
1278*/
drh4c755c02004-08-08 20:22:17 +00001279static void identPut(char *z, int *pIdx, char *zSignedIdent){
1280 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001281 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001282 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001283 for(j=0; zIdent[j]; j++){
1284 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1285 }
1286 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001287 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001288 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001289 for(j=0; zIdent[j]; j++){
1290 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001291 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001292 }
drh234c39d2004-07-24 03:30:47 +00001293 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001294 z[i] = 0;
1295 *pIdx = i;
1296}
1297
1298/*
1299** Generate a CREATE TABLE statement appropriate for the given
1300** table. Memory to hold the text of the statement is obtained
1301** from sqliteMalloc() and must be freed by the calling function.
1302*/
danielk1977da184232006-01-05 11:34:32 +00001303static char *createTableStmt(Table *p, int isTemp){
drh969fa7c2002-02-18 18:30:32 +00001304 int i, k, n;
1305 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001306 char *zSep, *zSep2, *zEnd, *z;
1307 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001308 n = 0;
drh234c39d2004-07-24 03:30:47 +00001309 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1310 n += identLength(pCol->zName);
1311 z = pCol->zType;
1312 if( z ){
1313 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001314 }
drh969fa7c2002-02-18 18:30:32 +00001315 }
1316 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001317 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001318 zSep = "";
1319 zSep2 = ",";
1320 zEnd = ")";
1321 }else{
1322 zSep = "\n ";
1323 zSep2 = ",\n ";
1324 zEnd = "\n)";
1325 }
drhe0bc4042002-06-25 01:09:11 +00001326 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001327 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001328 if( zStmt==0 ) return 0;
danielk1977da184232006-01-05 11:34:32 +00001329 strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001330 k = strlen(zStmt);
1331 identPut(zStmt, &k, p->zName);
1332 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001333 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001334 strcpy(&zStmt[k], zSep);
1335 k += strlen(&zStmt[k]);
1336 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001337 identPut(zStmt, &k, pCol->zName);
1338 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001339 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001340 strcpy(&zStmt[k], z);
1341 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001342 }
drh969fa7c2002-02-18 18:30:32 +00001343 }
1344 strcpy(&zStmt[k], zEnd);
1345 return zStmt;
1346}
1347
1348/*
drh75897232000-05-29 14:26:00 +00001349** This routine is called to report the final ")" that terminates
1350** a CREATE TABLE statement.
1351**
drhf57b3392001-10-08 13:22:32 +00001352** The table structure that other action routines have been building
1353** is added to the internal hash tables, assuming no errors have
1354** occurred.
drh75897232000-05-29 14:26:00 +00001355**
drh1d85d932004-02-14 23:05:52 +00001356** An entry for the table is made in the master table on disk, unless
1357** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001358** it means we are reading the sqlite_master table because we just
1359** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001360** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001361** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001362**
1363** If the pSelect argument is not NULL, it means that this routine
1364** was called to create a table generated from a
1365** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1366** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001367*/
danielk197719a8e7e2005-03-17 05:03:38 +00001368void sqlite3EndTable(
1369 Parse *pParse, /* Parse context */
1370 Token *pCons, /* The ',' token after the last column defn. */
1371 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1372 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1373){
drh75897232000-05-29 14:26:00 +00001374 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001375 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00001376 int iDb;
drh75897232000-05-29 14:26:00 +00001377
danielk19779e128002006-01-18 16:51:35 +00001378 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) {
danielk1977261919c2005-12-06 12:52:59 +00001379 return;
1380 }
drh28037572000-08-02 13:47:41 +00001381 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001382 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001383
danielk1977517eb642004-06-07 10:00:31 +00001384 assert( !db->init.busy || !pSelect );
1385
drhb9bb7c12006-06-11 23:41:55 +00001386 iDb = sqlite3SchemaToIndex(db, p->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001387
drhffe07b22005-11-03 00:41:17 +00001388#ifndef SQLITE_OMIT_CHECK
1389 /* Resolve names in all CHECK constraint expressions.
1390 */
1391 if( p->pCheck ){
1392 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1393 NameContext sNC; /* Name context for pParse->pNewTable */
1394
1395 memset(&sNC, 0, sizeof(sNC));
1396 memset(&sSrc, 0, sizeof(sSrc));
1397 sSrc.nSrc = 1;
1398 sSrc.a[0].zName = p->zName;
1399 sSrc.a[0].pTab = p;
1400 sSrc.a[0].iCursor = -1;
1401 sNC.pParse = pParse;
1402 sNC.pSrcList = &sSrc;
drh06f65412005-11-03 02:03:13 +00001403 sNC.isCheck = 1;
drhffe07b22005-11-03 00:41:17 +00001404 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
1405 return;
1406 }
1407 }
1408#endif /* !defined(SQLITE_OMIT_CHECK) */
1409
drh1d85d932004-02-14 23:05:52 +00001410 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001411 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1412 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001413 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001414 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001415 */
drh1d85d932004-02-14 23:05:52 +00001416 if( db->init.busy ){
1417 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001418 }
1419
drhe3c41372001-09-17 20:25:58 +00001420 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001421 ** in the SQLITE_MASTER table of the database. The record number
1422 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001423 **
drhe0bc4042002-06-25 01:09:11 +00001424 ** If this is a TEMPORARY table, write the entry into the auxiliary
1425 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001426 */
drh1d85d932004-02-14 23:05:52 +00001427 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001428 int n;
drhd8bc7082000-06-07 23:51:50 +00001429 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001430 char *zType; /* "view" or "table" */
1431 char *zType2; /* "VIEW" or "TABLE" */
1432 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001433
danielk19774adee202004-05-08 08:23:19 +00001434 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001435 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001436
danielk1977e6efa742004-11-10 11:55:10 +00001437 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1438
drh4794f732004-11-05 17:17:50 +00001439 /* Create the rootpage for the new table and push it onto the stack.
1440 ** A view has no rootpage, so just push a zero onto the stack for
1441 ** views. Initialize zType at the same time.
1442 */
drh4ff6dfa2002-03-03 23:06:00 +00001443 if( p->pSelect==0 ){
1444 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001445 zType = "table";
1446 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001447#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001448 }else{
1449 /* A view */
drh4794f732004-11-05 17:17:50 +00001450 zType = "view";
1451 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001452#endif
drh4ff6dfa2002-03-03 23:06:00 +00001453 }
danielk1977517eb642004-06-07 10:00:31 +00001454
danielk1977517eb642004-06-07 10:00:31 +00001455 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1456 ** statement to populate the new table. The root-page number for the
1457 ** new table is on the top of the vdbe stack.
1458 **
1459 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1460 ** suitable state to query for the column names and types to be used
1461 ** by the new table.
danielk1977c00da102006-01-07 13:21:04 +00001462 **
1463 ** A shared-cache write-lock is not required to write to the new table,
1464 ** as a schema-lock must have already been obtained to create it. Since
1465 ** a schema-lock excludes all other database users, the write-lock would
1466 ** be redundant.
danielk1977517eb642004-06-07 10:00:31 +00001467 */
1468 if( pSelect ){
1469 Table *pSelTab;
1470 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
danielk1977da184232006-01-05 11:34:32 +00001471 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977517eb642004-06-07 10:00:31 +00001472 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1473 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001474 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001475 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1476 if( pParse->nErr==0 ){
1477 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1478 if( pSelTab==0 ) return;
1479 assert( p->aCol==0 );
1480 p->nCol = pSelTab->nCol;
1481 p->aCol = pSelTab->aCol;
1482 pSelTab->nCol = 0;
1483 pSelTab->aCol = 0;
1484 sqlite3DeleteTable(0, pSelTab);
1485 }
1486 }
drh4794f732004-11-05 17:17:50 +00001487
drh4794f732004-11-05 17:17:50 +00001488 /* Compute the complete text of the CREATE statement */
1489 if( pSelect ){
danielk1977da184232006-01-05 11:34:32 +00001490 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
drh4794f732004-11-05 17:17:50 +00001491 }else{
drh97903fe2005-05-24 20:19:57 +00001492 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001493 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1494 }
1495
1496 /* A slot for the record has already been allocated in the
1497 ** SQLITE_MASTER table. We just need to update that slot with all
1498 ** the information we've collected. The rowid for the preallocated
1499 ** slot is the 2nd item on the stack. The top of the stack is the
1500 ** root page for the new table (or a 0 if this is a view).
1501 */
1502 sqlite3NestedParse(pParse,
1503 "UPDATE %Q.%s "
1504 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1505 "WHERE rowid=#1",
danielk1977da184232006-01-05 11:34:32 +00001506 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
drh4794f732004-11-05 17:17:50 +00001507 zType,
1508 p->zName,
1509 p->zName,
1510 zStmt
1511 );
1512 sqliteFree(zStmt);
danielk1977da184232006-01-05 11:34:32 +00001513 sqlite3ChangeCookie(db, v, iDb);
drh2958a4e2004-11-12 03:56:15 +00001514
1515#ifndef SQLITE_OMIT_AUTOINCREMENT
1516 /* Check to see if we need to create an sqlite_sequence table for
1517 ** keeping track of autoincrement keys.
1518 */
1519 if( p->autoInc ){
danielk1977da184232006-01-05 11:34:32 +00001520 Db *pDb = &db->aDb[iDb];
1521 if( pDb->pSchema->pSeqTab==0 ){
drh2958a4e2004-11-12 03:56:15 +00001522 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001523 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1524 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001525 );
1526 }
1527 }
1528#endif
drh4794f732004-11-05 17:17:50 +00001529
1530 /* Reparse everything to update our internal data structures */
danielk1977da184232006-01-05 11:34:32 +00001531 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
drh234c39d2004-07-24 03:30:47 +00001532 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001533 }
drh17e9e292003-02-01 13:53:28 +00001534
drh2958a4e2004-11-12 03:56:15 +00001535
drh17e9e292003-02-01 13:53:28 +00001536 /* Add the table to the in-memory representation of the database.
1537 */
drh234c39d2004-07-24 03:30:47 +00001538 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001539 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001540 FKey *pFKey;
danielk1977e501b892006-01-09 06:29:47 +00001541 Schema *pSchema = p->pSchema;
danielk1977da184232006-01-05 11:34:32 +00001542 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
drh17e9e292003-02-01 13:53:28 +00001543 if( pOld ){
1544 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1545 return;
1546 }
danielk1977576ec6b2005-01-21 11:55:25 +00001547#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001548 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1549 int nTo = strlen(pFKey->zTo) + 1;
danielk1977da184232006-01-05 11:34:32 +00001550 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
1551 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001552 }
danielk1977576ec6b2005-01-21 11:55:25 +00001553#endif
drh17e9e292003-02-01 13:53:28 +00001554 pParse->pNewTable = 0;
1555 db->nTable++;
1556 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001557
1558#ifndef SQLITE_OMIT_ALTERTABLE
1559 if( !p->pSelect ){
danielk1977bab45c62006-01-16 15:14:27 +00001560 const char *zName = (const char *)pParse->sNameToken.z;
1561 int nName;
danielk197719a8e7e2005-03-17 05:03:38 +00001562 assert( !pSelect && pCons && pEnd );
danielk1977bab45c62006-01-16 15:14:27 +00001563 if( pCons->z==0 ){
1564 pCons = pEnd;
1565 }
1566 nName = (const char *)pCons->z - zName;
1567 p->addColOffset = 13 + sqlite3utf8CharLen(zName, nName);
danielk197719a8e7e2005-03-17 05:03:38 +00001568 }
1569#endif
drh17e9e292003-02-01 13:53:28 +00001570 }
drh75897232000-05-29 14:26:00 +00001571}
1572
drhb7f91642004-10-31 02:22:47 +00001573#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001574/*
drha76b5df2002-02-23 02:32:10 +00001575** The parser calls this routine in order to create a new VIEW
1576*/
danielk19774adee202004-05-08 08:23:19 +00001577void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001578 Parse *pParse, /* The parsing context */
1579 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001580 Token *pName1, /* The token that holds the name of the view */
1581 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001582 Select *pSelect, /* A SELECT statement that will become the new view */
1583 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001584){
drha76b5df2002-02-23 02:32:10 +00001585 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001586 int n;
drh4c755c02004-08-08 20:22:17 +00001587 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001588 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001589 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001590 Token *pName;
danielk1977da184232006-01-05 11:34:32 +00001591 int iDb;
drha76b5df2002-02-23 02:32:10 +00001592
drh7c3d64f2005-06-06 15:32:08 +00001593 if( pParse->nVar>0 ){
1594 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1595 sqlite3SelectDelete(pSelect);
1596 return;
1597 }
danielk1977f1a381e2006-06-16 08:01:02 +00001598 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, 0);
drha76b5df2002-02-23 02:32:10 +00001599 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001600 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001601 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001602 return;
1603 }
danielk1977ef2cb632004-05-29 02:37:19 +00001604 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977da184232006-01-05 11:34:32 +00001605 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
1606 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
danielk19774adee202004-05-08 08:23:19 +00001607 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001608 ){
danielk19774adee202004-05-08 08:23:19 +00001609 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001610 return;
1611 }
drh174b6192002-12-03 02:22:52 +00001612
drh4b59ab52002-08-24 18:24:51 +00001613 /* Make a copy of the entire SELECT statement that defines the view.
1614 ** This will force all the Expr.token.z values to be dynamically
1615 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001616 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001617 */
danielk19774adee202004-05-08 08:23:19 +00001618 p->pSelect = sqlite3SelectDup(pSelect);
1619 sqlite3SelectDelete(pSelect);
danielk19779e128002006-01-18 16:51:35 +00001620 if( sqlite3MallocFailed() ){
danielk1977261919c2005-12-06 12:52:59 +00001621 return;
1622 }
drh1d85d932004-02-14 23:05:52 +00001623 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001624 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001625 }
drh4b59ab52002-08-24 18:24:51 +00001626
1627 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1628 ** the end.
1629 */
drha76b5df2002-02-23 02:32:10 +00001630 sEnd = pParse->sLastToken;
1631 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1632 sEnd.z += sEnd.n;
1633 }
1634 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001635 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001636 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001637 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1638 sEnd.z = &z[n-1];
1639 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001640
danielk19774adee202004-05-08 08:23:19 +00001641 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001642 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001643 return;
drh417be792002-03-03 18:59:40 +00001644}
drhb7f91642004-10-31 02:22:47 +00001645#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001646
danielk1977fe3fcbe22006-06-12 12:08:45 +00001647#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
drh417be792002-03-03 18:59:40 +00001648/*
1649** The Table structure pTable is really a VIEW. Fill in the names of
1650** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001651** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001652*/
danielk19774adee202004-05-08 08:23:19 +00001653int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001654 Table *pSelTab; /* A fake table from which we get the result set */
1655 Select *pSel; /* Copy of the SELECT that implements the view */
1656 int nErr = 0; /* Number of errors encountered */
1657 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001658
1659 assert( pTable );
1660
danielk1977fe3fcbe22006-06-12 12:08:45 +00001661#ifndef SQLITE_OMIT_VIRTUALTABLE
1662 if( sqlite3VtabCallConnect(pParse, pTable) ){
1663 return SQLITE_ERROR;
1664 }
drh4cbdda92006-06-14 19:00:20 +00001665 if( IsVirtual(pTable) ) return 0;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001666#endif
1667
1668#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001669 /* A positive nCol means the columns names for this view are
1670 ** already known.
1671 */
1672 if( pTable->nCol>0 ) return 0;
1673
1674 /* A negative nCol is a special marker meaning that we are currently
1675 ** trying to compute the column names. If we enter this routine with
1676 ** a negative nCol, it means two or more views form a loop, like this:
1677 **
1678 ** CREATE VIEW one AS SELECT * FROM two;
1679 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001680 **
1681 ** Actually, this error is caught previously and so the following test
1682 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001683 */
1684 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001685 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001686 return 1;
1687 }
drh85c23c62005-08-20 03:03:04 +00001688 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001689
1690 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001691 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1692 ** "*" elements in the results set of the view and will assign cursors
1693 ** to the elements of the FROM clause. But we do not want these changes
1694 ** to be permanent. So the computation is done on a copy of the SELECT
1695 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001696 */
drh9b3187e2005-01-18 14:45:47 +00001697 assert( pTable->pSelect );
1698 pSel = sqlite3SelectDup(pTable->pSelect);
danielk1977261919c2005-12-06 12:52:59 +00001699 if( pSel ){
1700 n = pParse->nTab;
1701 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
1702 pTable->nCol = -1;
1703 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
1704 pParse->nTab = n;
1705 if( pSelTab ){
1706 assert( pTable->aCol==0 );
1707 pTable->nCol = pSelTab->nCol;
1708 pTable->aCol = pSelTab->aCol;
1709 pSelTab->nCol = 0;
1710 pSelTab->aCol = 0;
1711 sqlite3DeleteTable(0, pSelTab);
danielk1977da184232006-01-05 11:34:32 +00001712 pTable->pSchema->flags |= DB_UnresetViews;
danielk1977261919c2005-12-06 12:52:59 +00001713 }else{
1714 pTable->nCol = 0;
1715 nErr++;
1716 }
1717 sqlite3SelectDelete(pSel);
1718 } else {
drh417be792002-03-03 18:59:40 +00001719 nErr++;
1720 }
drhb7f91642004-10-31 02:22:47 +00001721#endif /* SQLITE_OMIT_VIEW */
danielk19774b2688a2006-06-20 11:01:07 +00001722 return nErr;
danielk1977fe3fcbe22006-06-12 12:08:45 +00001723}
1724#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
drh417be792002-03-03 18:59:40 +00001725
drhb7f91642004-10-31 02:22:47 +00001726#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001727/*
drh8bf8dc92003-05-17 17:35:10 +00001728** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001729*/
drh9bb575f2004-09-06 17:24:11 +00001730static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001731 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001732 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
danielk1977da184232006-01-05 11:34:32 +00001733 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001734 Table *pTab = sqliteHashData(i);
1735 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001736 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001737 }
1738 }
drh8bf8dc92003-05-17 17:35:10 +00001739 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001740}
drhb7f91642004-10-31 02:22:47 +00001741#else
1742# define sqliteViewResetAll(A,B)
1743#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001744
drh75897232000-05-29 14:26:00 +00001745/*
danielk1977a0bf2652004-11-04 14:30:04 +00001746** This function is called by the VDBE to adjust the internal schema
1747** used by SQLite when the btree layer moves a table root page. The
1748** root-page of a table or index in database iDb has changed from iFrom
1749** to iTo.
drh6205d4a2006-03-24 03:36:26 +00001750**
1751** Ticket #1728: The symbol table might still contain information
1752** on tables and/or indices that are the process of being deleted.
1753** If you are unlucky, one of those deleted indices or tables might
1754** have the same rootpage number as the real table or index that is
1755** being moved. So we cannot stop searching after the first match
1756** because the first match might be for one of the deleted indices
1757** or tables and not the table/index that is actually being moved.
1758** We must continue looping until all tables and indices with
1759** rootpage==iFrom have been converted to have a rootpage of iTo
1760** in order to be certain that we got the right one.
danielk1977a0bf2652004-11-04 14:30:04 +00001761*/
1762#ifndef SQLITE_OMIT_AUTOVACUUM
1763void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1764 HashElem *pElem;
danielk1977da184232006-01-05 11:34:32 +00001765 Hash *pHash;
1766
1767 pHash = &pDb->pSchema->tblHash;
1768 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001769 Table *pTab = sqliteHashData(pElem);
1770 if( pTab->tnum==iFrom ){
1771 pTab->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001772 }
1773 }
danielk1977da184232006-01-05 11:34:32 +00001774 pHash = &pDb->pSchema->idxHash;
1775 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
danielk1977a0bf2652004-11-04 14:30:04 +00001776 Index *pIdx = sqliteHashData(pElem);
1777 if( pIdx->tnum==iFrom ){
1778 pIdx->tnum = iTo;
danielk1977a0bf2652004-11-04 14:30:04 +00001779 }
1780 }
danielk1977a0bf2652004-11-04 14:30:04 +00001781}
1782#endif
1783
1784/*
1785** Write code to erase the table with root-page iTable from database iDb.
1786** Also write code to modify the sqlite_master table and internal schema
1787** if a root-page of another table is moved by the btree-layer whilst
1788** erasing iTable (this can happen with an auto-vacuum database).
1789*/
drh4e0cff62004-11-05 05:10:28 +00001790static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1791 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001792 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1793#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001794 /* OP_Destroy pushes an integer onto the stack. If this integer
1795 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001796 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001797 ** reflect this.
1798 **
1799 ** The "#0" in the SQL is a special constant that means whatever value
1800 ** is on the top of the stack. See sqlite3RegisterExpr().
1801 */
danielk197763e3e9f2004-11-05 09:19:27 +00001802 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001803 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001804 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001805#endif
1806}
1807
1808/*
1809** Write VDBE code to erase table pTab and all associated indices on disk.
1810** Code to update the sqlite_master tables and internal schema definitions
1811** in case a root-page belonging to another table is moved by the btree layer
1812** is also added (this can happen with an auto-vacuum database).
1813*/
drh4e0cff62004-11-05 05:10:28 +00001814static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001815#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001816 Index *pIdx;
drh29c636b2006-01-09 23:40:25 +00001817 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1818 destroyRootPage(pParse, pTab->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001819 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh29c636b2006-01-09 23:40:25 +00001820 destroyRootPage(pParse, pIdx->tnum, iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001821 }
1822#else
1823 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1824 ** is not defined), then it is important to call OP_Destroy on the
1825 ** table and index root-pages in order, starting with the numerically
1826 ** largest root-page number. This guarantees that none of the root-pages
1827 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1828 ** following were coded:
1829 **
1830 ** OP_Destroy 4 0
1831 ** ...
1832 ** OP_Destroy 5 0
1833 **
1834 ** and root page 5 happened to be the largest root-page number in the
1835 ** database, then root page 5 would be moved to page 4 by the
1836 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1837 ** a free-list page.
1838 */
1839 int iTab = pTab->tnum;
1840 int iDestroyed = 0;
1841
1842 while( 1 ){
1843 Index *pIdx;
1844 int iLargest = 0;
1845
1846 if( iDestroyed==0 || iTab<iDestroyed ){
1847 iLargest = iTab;
1848 }
1849 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1850 int iIdx = pIdx->tnum;
danielk1977da184232006-01-05 11:34:32 +00001851 assert( pIdx->pSchema==pTab->pSchema );
danielk1977a0bf2652004-11-04 14:30:04 +00001852 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1853 iLargest = iIdx;
1854 }
1855 }
danielk1977da184232006-01-05 11:34:32 +00001856 if( iLargest==0 ){
1857 return;
1858 }else{
1859 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1860 destroyRootPage(pParse, iLargest, iDb);
1861 iDestroyed = iLargest;
1862 }
danielk1977a0bf2652004-11-04 14:30:04 +00001863 }
1864#endif
1865}
1866
1867/*
drh75897232000-05-29 14:26:00 +00001868** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001869** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001870*/
drha0733842005-12-29 01:11:36 +00001871void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
danielk1977a8858102004-05-28 12:11:21 +00001872 Table *pTab;
drh75897232000-05-29 14:26:00 +00001873 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001874 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001875 int iDb;
drh75897232000-05-29 14:26:00 +00001876
danielk19779e128002006-01-18 16:51:35 +00001877 if( pParse->nErr || sqlite3MallocFailed() ){
drh6f7adc82006-01-11 21:41:20 +00001878 goto exit_drop_table;
1879 }
danielk1977a8858102004-05-28 12:11:21 +00001880 assert( pName->nSrc==1 );
1881 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1882
drha0733842005-12-29 01:11:36 +00001883 if( pTab==0 ){
1884 if( noErr ){
1885 sqlite3ErrorClear(pParse);
1886 }
1887 goto exit_drop_table;
1888 }
danielk1977da184232006-01-05 11:34:32 +00001889 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drhe22a3342003-04-22 20:30:37 +00001890 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001891#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001892 {
1893 int code;
danielk1977da184232006-01-05 11:34:32 +00001894 const char *zTab = SCHEMA_TABLE(iDb);
1895 const char *zDb = db->aDb[iDb].zName;
danielk1977f1a381e2006-06-16 08:01:02 +00001896 const char *zArg2 = 0;
danielk19774adee202004-05-08 08:23:19 +00001897 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001898 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001899 }
drhe5f9c642003-01-13 23:27:31 +00001900 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001901 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001902 code = SQLITE_DROP_TEMP_VIEW;
1903 }else{
1904 code = SQLITE_DROP_VIEW;
1905 }
danielk19774b2688a2006-06-20 11:01:07 +00001906#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977f1a381e2006-06-16 08:01:02 +00001907 }else if( IsVirtual(pTab) ){
danielk19779d1b2a22006-06-21 07:34:11 +00001908 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
1909 goto exit_drop_table;
1910 }
danielk1977f1a381e2006-06-16 08:01:02 +00001911 code = SQLITE_DROP_VTABLE;
1912 zArg2 = pTab->pMod->zName;
danielk19774b2688a2006-06-20 11:01:07 +00001913#endif
drhe5f9c642003-01-13 23:27:31 +00001914 }else{
danielk197753c0f742005-03-29 03:10:59 +00001915 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001916 code = SQLITE_DROP_TEMP_TABLE;
1917 }else{
1918 code = SQLITE_DROP_TABLE;
1919 }
1920 }
danielk1977f1a381e2006-06-16 08:01:02 +00001921 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
danielk1977a8858102004-05-28 12:11:21 +00001922 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001923 }
danielk1977a8858102004-05-28 12:11:21 +00001924 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1925 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001926 }
drhe5f9c642003-01-13 23:27:31 +00001927 }
1928#endif
danielk1977da184232006-01-05 11:34:32 +00001929 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001930 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001931 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001932 }
danielk1977576ec6b2005-01-21 11:55:25 +00001933
1934#ifndef SQLITE_OMIT_VIEW
1935 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1936 ** on a table.
1937 */
danielk1977a8858102004-05-28 12:11:21 +00001938 if( isView && pTab->pSelect==0 ){
1939 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1940 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001941 }
danielk1977a8858102004-05-28 12:11:21 +00001942 if( !isView && pTab->pSelect ){
1943 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1944 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001945 }
danielk1977576ec6b2005-01-21 11:55:25 +00001946#endif
drh75897232000-05-29 14:26:00 +00001947
drh1ccde152000-06-17 13:12:39 +00001948 /* Generate code to remove the table from the master table
1949 ** on disk.
1950 */
danielk19774adee202004-05-08 08:23:19 +00001951 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001952 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001953 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001954 Db *pDb = &db->aDb[iDb];
1955 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001956
danielk19778e227872004-06-07 07:52:17 +00001957 /* Drop all triggers associated with the table being dropped. Code
1958 ** is generated to remove entries from sqlite_master and/or
1959 ** sqlite_temp_master if required.
1960 */
danielk1977a8858102004-05-28 12:11:21 +00001961 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001962 while( pTrigger ){
danielk1977da184232006-01-05 11:34:32 +00001963 assert( pTrigger->pSchema==pTab->pSchema ||
1964 pTrigger->pSchema==db->aDb[1].pSchema );
drh74161702006-02-24 02:53:49 +00001965 sqlite3DropTriggerPtr(pParse, pTrigger);
drh956bc922004-07-24 17:38:29 +00001966 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001967 }
drh8bf8dc92003-05-17 17:35:10 +00001968
danielk19774d36b812004-11-19 07:07:30 +00001969#ifndef SQLITE_OMIT_AUTOINCREMENT
1970 /* Remove any entries of the sqlite_sequence table associated with
1971 ** the table being dropped. This is done before the table is dropped
1972 ** at the btree level, in case the sqlite_sequence table needs to
1973 ** move as a result of the drop (can happen in auto-vacuum mode).
1974 */
1975 if( pTab->autoInc ){
1976 sqlite3NestedParse(pParse,
1977 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1978 pDb->zName, pTab->zName
1979 );
1980 }
1981#endif
1982
danielk19778e227872004-06-07 07:52:17 +00001983 /* Drop all SQLITE_MASTER table and index entries that refer to the
1984 ** table. The program name loops through the master table and deletes
1985 ** every row that refers to a table of the same name as the one being
1986 ** dropped. Triggers are handled seperately because a trigger can be
1987 ** created in the temp database that refers to a table in another
1988 ** database.
1989 */
drhf1974842004-11-05 03:56:00 +00001990 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001991 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001992 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
danielk19774b2688a2006-06-20 11:01:07 +00001993 if( !isView && !IsVirtual(pTab) ){
drh4e0cff62004-11-05 05:10:28 +00001994 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001995 }
drh2958a4e2004-11-12 03:56:15 +00001996
danielk1977a21c6b62005-01-24 10:25:59 +00001997 /* Remove the table entry from SQLite's internal schema and modify
1998 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001999 */
drh4cbdda92006-06-14 19:00:20 +00002000 if( IsVirtual(pTab) ){
drhb9bb7c12006-06-11 23:41:55 +00002001 sqlite3VdbeOp3(v, OP_VDestroy, iDb, 0, pTab->zName, 0);
drhb9bb7c12006-06-11 23:41:55 +00002002 }
danielk19779e39ce82006-06-12 16:01:21 +00002003 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00002004 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00002005 }
drhd24cc422003-03-27 12:51:24 +00002006 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00002007
2008exit_drop_table:
2009 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002010}
2011
2012/*
drhc2eef3b2002-08-31 18:53:06 +00002013** This routine is called to create a new foreign key on the table
2014** currently under construction. pFromCol determines which columns
2015** in the current table point to the foreign key. If pFromCol==0 then
2016** connect the key to the last column inserted. pTo is the name of
2017** the table referred to. pToCol is a list of tables in the other
2018** pTo table that the foreign key points to. flags contains all
2019** information about the conflict resolution algorithms specified
2020** in the ON DELETE, ON UPDATE and ON INSERT clauses.
2021**
2022** An FKey structure is created and added to the table currently
2023** under construction in the pParse->pNewTable field. The new FKey
2024** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00002025** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00002026**
2027** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00002028** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00002029*/
danielk19774adee202004-05-08 08:23:19 +00002030void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00002031 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00002032 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00002033 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00002034 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00002035 int flags /* Conflict resolution algorithms. */
2036){
drhb7f91642004-10-31 02:22:47 +00002037#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00002038 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00002039 Table *p = pParse->pNewTable;
2040 int nByte;
2041 int i;
2042 int nCol;
2043 char *z;
drhc2eef3b2002-08-31 18:53:06 +00002044
2045 assert( pTo!=0 );
danielk1977c7d54102006-06-15 07:29:00 +00002046 if( p==0 || pParse->nErr || IN_DECLARE_VTAB ) goto fk_end;
drhc2eef3b2002-08-31 18:53:06 +00002047 if( pFromCol==0 ){
2048 int iCol = p->nCol-1;
2049 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00002050 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00002051 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00002052 " should reference only one column of table %T",
2053 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00002054 goto fk_end;
2055 }
2056 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00002057 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00002058 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00002059 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00002060 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00002061 goto fk_end;
2062 }else{
danielk19770202b292004-06-09 09:55:16 +00002063 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00002064 }
2065 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
2066 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00002067 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00002068 nByte += strlen(pToCol->a[i].zName) + 1;
2069 }
2070 }
2071 pFKey = sqliteMalloc( nByte );
2072 if( pFKey==0 ) goto fk_end;
2073 pFKey->pFrom = p;
2074 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00002075 z = (char*)&pFKey[1];
2076 pFKey->aCol = (struct sColMap*)z;
2077 z += sizeof(struct sColMap)*nCol;
2078 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00002079 memcpy(z, pTo->z, pTo->n);
2080 z[pTo->n] = 0;
2081 z += pTo->n+1;
2082 pFKey->pNextTo = 0;
2083 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00002084 if( pFromCol==0 ){
2085 pFKey->aCol[0].iFrom = p->nCol-1;
2086 }else{
2087 for(i=0; i<nCol; i++){
2088 int j;
2089 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002090 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00002091 pFKey->aCol[i].iFrom = j;
2092 break;
2093 }
2094 }
2095 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002096 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00002097 "unknown column \"%s\" in foreign key definition",
2098 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00002099 goto fk_end;
2100 }
2101 }
2102 }
2103 if( pToCol ){
2104 for(i=0; i<nCol; i++){
2105 int n = strlen(pToCol->a[i].zName);
2106 pFKey->aCol[i].zCol = z;
2107 memcpy(z, pToCol->a[i].zName, n);
2108 z[n] = 0;
2109 z += n+1;
2110 }
2111 }
2112 pFKey->isDeferred = 0;
2113 pFKey->deleteConf = flags & 0xff;
2114 pFKey->updateConf = (flags >> 8 ) & 0xff;
2115 pFKey->insertConf = (flags >> 16 ) & 0xff;
2116
2117 /* Link the foreign key to the table as the last step.
2118 */
2119 p->pFKey = pFKey;
2120 pFKey = 0;
2121
2122fk_end:
2123 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00002124#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00002125 sqlite3ExprListDelete(pFromCol);
2126 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002127}
2128
2129/*
2130** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2131** clause is seen as part of a foreign key definition. The isDeferred
2132** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2133** The behavior of the most recently created foreign key is adjusted
2134** accordingly.
2135*/
danielk19774adee202004-05-08 08:23:19 +00002136void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002137#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002138 Table *pTab;
2139 FKey *pFKey;
2140 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2141 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002142#endif
drhc2eef3b2002-08-31 18:53:06 +00002143}
2144
2145/*
drh063336a2004-11-05 20:58:39 +00002146** Generate code that will erase and refill index *pIdx. This is
2147** used to initialize a newly created index or to recompute the
2148** content of an index in response to a REINDEX command.
2149**
2150** if memRootPage is not negative, it means that the index is newly
2151** created. The memory cell specified by memRootPage contains the
2152** root page number of the index. If memRootPage is negative, then
2153** the index already exists and must be cleared before being refilled and
2154** the root page number of the index is taken from pIndex->tnum.
2155*/
2156static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2157 Table *pTab = pIndex->pTable; /* The table that is indexed */
2158 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2159 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2160 int addr1; /* Address of top of loop */
2161 int tnum; /* Root page of index */
2162 Vdbe *v; /* Generate code into this virtual machine */
danielk1977b3bf5562006-01-10 17:58:23 +00002163 KeyInfo *pKey; /* KeyInfo for index */
danielk1977da184232006-01-05 11:34:32 +00002164 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
drh063336a2004-11-05 20:58:39 +00002165
danielk19771d54df82004-11-23 15:41:16 +00002166#ifndef SQLITE_OMIT_AUTHORIZATION
2167 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
danielk1977da184232006-01-05 11:34:32 +00002168 pParse->db->aDb[iDb].zName ) ){
danielk19771d54df82004-11-23 15:41:16 +00002169 return;
2170 }
2171#endif
2172
danielk1977c00da102006-01-07 13:21:04 +00002173 /* Require a write-lock on the table to perform this operation */
2174 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
2175
drh063336a2004-11-05 20:58:39 +00002176 v = sqlite3GetVdbe(pParse);
2177 if( v==0 ) return;
2178 if( memRootPage>=0 ){
2179 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2180 tnum = 0;
2181 }else{
2182 tnum = pIndex->tnum;
danielk1977da184232006-01-05 11:34:32 +00002183 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
drh063336a2004-11-05 20:58:39 +00002184 }
danielk1977da184232006-01-05 11:34:32 +00002185 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk1977b3bf5562006-01-10 17:58:23 +00002186 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
2187 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
danielk1977c00da102006-01-07 13:21:04 +00002188 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
drh063336a2004-11-05 20:58:39 +00002189 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2190 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00002191 if( pIndex->onError!=OE_None ){
2192 int curaddr = sqlite3VdbeCurrentAddr(v);
2193 int addr2 = curaddr+4;
2194 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2195 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2196 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2197 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2198 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2199 "indexed columns are not unique", P3_STATIC);
2200 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002201 }
drh7f057c92005-06-24 03:53:06 +00002202 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002203 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
drhd654be82005-09-20 17:42:23 +00002204 sqlite3VdbeJumpHere(v, addr1);
drh063336a2004-11-05 20:58:39 +00002205 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2206 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2207}
2208
2209/*
drh23bf66d2004-12-14 03:34:34 +00002210** Create a new index for an SQL table. pName1.pName2 is the name of the index
2211** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002212** be NULL for a primary key or an index that is created to satisfy a
2213** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002214** as the table to be indexed. pParse->pNewTable is a table that is
2215** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002216**
drh382c0242001-10-06 16:33:02 +00002217** pList is a list of columns to be indexed. pList will be NULL if this
2218** is a primary key or unique-constraint on the most recent column added
2219** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002220*/
danielk19774adee202004-05-08 08:23:19 +00002221void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002222 Parse *pParse, /* All information about this parse */
2223 Token *pName1, /* First part of index name. May be NULL */
2224 Token *pName2, /* Second part of index name. May be NULL */
2225 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002226 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002227 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2228 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
drhfdd6e852005-12-16 01:06:16 +00002229 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
drh4d91a702006-01-04 15:54:36 +00002230 int sortOrder, /* Sort order of primary key when pList==NULL */
2231 int ifNotExist /* Omit error if index already exists */
drh75897232000-05-29 14:26:00 +00002232){
drhfdd6e852005-12-16 01:06:16 +00002233 Table *pTab = 0; /* Table to be indexed */
2234 Index *pIndex = 0; /* The index to be created */
2235 char *zName = 0; /* Name of the index */
2236 int nName; /* Number of characters in zName */
drhbeae3192001-09-22 18:12:08 +00002237 int i, j;
drhfdd6e852005-12-16 01:06:16 +00002238 Token nullId; /* Fake token for an empty ID list */
2239 DbFixer sFix; /* For assigning database names to pTable */
2240 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
drh9bb575f2004-09-06 17:24:11 +00002241 sqlite3 *db = pParse->db;
drhfdd6e852005-12-16 01:06:16 +00002242 Db *pDb; /* The specific table containing the indexed database */
2243 int iDb; /* Index of the database that is being written */
2244 Token *pName = 0; /* Unqualified name of the index to create */
2245 struct ExprList_item *pListItem; /* For looping over pList */
danielk1977b3bf5562006-01-10 17:58:23 +00002246 int nCol;
2247 int nExtra = 0;
2248 char *zExtra;
danielk1977cbb18d22004-05-28 11:37:27 +00002249
danielk1977f1a381e2006-06-16 08:01:02 +00002250 if( pParse->nErr || sqlite3MallocFailed() || IN_DECLARE_VTAB ){
danielk1977e501b892006-01-09 06:29:47 +00002251 goto exit_create_index;
2252 }
drhdaffd0e2001-04-11 14:28:42 +00002253
drh75897232000-05-29 14:26:00 +00002254 /*
2255 ** Find the table that is to be indexed. Return early if not found.
2256 */
danielk1977cbb18d22004-05-28 11:37:27 +00002257 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002258
2259 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002260 ** to search for the table. 'Fix' the table name to this db
2261 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002262 */
2263 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002264 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002265 if( iDb<0 ) goto exit_create_index;
2266
danielk197753c0f742005-03-29 03:10:59 +00002267#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002268 /* If the index name was unqualified, check if the the table
2269 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002270 */
danielk1977ef2cb632004-05-29 02:37:19 +00002271 pTab = sqlite3SrcListLookup(pParse, pTblName);
danielk1977da184232006-01-05 11:34:32 +00002272 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
danielk1977ef2cb632004-05-29 02:37:19 +00002273 iDb = 1;
2274 }
danielk197753c0f742005-03-29 03:10:59 +00002275#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002276
2277 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2278 sqlite3FixSrcList(&sFix, pTblName)
2279 ){
drh85c23c62005-08-20 03:03:04 +00002280 /* Because the parser constructs pTblName from a single identifier,
2281 ** sqlite3FixSrcList can never fail. */
2282 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002283 }
danielk1977ef2cb632004-05-29 02:37:19 +00002284 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2285 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002286 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002287 assert( db->aDb[iDb].pSchema==pTab->pSchema );
drh75897232000-05-29 14:26:00 +00002288 }else{
drhe3c41372001-09-17 20:25:58 +00002289 assert( pName==0 );
danielk1977da184232006-01-05 11:34:32 +00002290 pTab = pParse->pNewTable;
drha6370df2006-01-04 21:40:06 +00002291 if( !pTab ) goto exit_create_index;
danielk1977da184232006-01-05 11:34:32 +00002292 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
drh75897232000-05-29 14:26:00 +00002293 }
drhfdd6e852005-12-16 01:06:16 +00002294 pDb = &db->aDb[iDb];
danielk1977cbb18d22004-05-28 11:37:27 +00002295
drh75897232000-05-29 14:26:00 +00002296 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002297 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002298 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002299 goto exit_create_index;
2300 }
danielk1977576ec6b2005-01-21 11:55:25 +00002301#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002302 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002303 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002304 goto exit_create_index;
2305 }
danielk1977576ec6b2005-01-21 11:55:25 +00002306#endif
drh75897232000-05-29 14:26:00 +00002307
2308 /*
2309 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002310 ** index or table with the same name.
2311 **
2312 ** Exception: If we are reading the names of permanent indices from the
2313 ** sqlite_master table (because some other process changed the schema) and
2314 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002315 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002316 **
2317 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002318 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2319 ** own name.
drh75897232000-05-29 14:26:00 +00002320 */
danielk1977d8123362004-06-12 09:25:12 +00002321 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002322 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002323 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002324 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002325 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002326 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002327 }
danielk1977d8123362004-06-12 09:25:12 +00002328 if( !db->init.busy ){
danielk19778a414492004-06-29 08:59:35 +00002329 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002330 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
drh4d91a702006-01-04 15:54:36 +00002331 if( !ifNotExist ){
2332 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2333 }
danielk1977d8123362004-06-12 09:25:12 +00002334 goto exit_create_index;
2335 }
drh4f26bb62005-09-08 14:17:20 +00002336 if( sqlite3FindTable(db, zName, 0)!=0 ){
danielk1977d8123362004-06-12 09:25:12 +00002337 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2338 goto exit_create_index;
2339 }
drhe3c41372001-09-17 20:25:58 +00002340 }
danielk1977a21c6b62005-01-24 10:25:59 +00002341 }else{
drhadbca9c2001-09-27 15:11:53 +00002342 char zBuf[30];
2343 int n;
2344 Index *pLoop;
2345 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002346 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002347 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002348 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002349 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002350 }
2351
drhe5f9c642003-01-13 23:27:31 +00002352 /* Check for authorization to create an index.
2353 */
2354#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002355 {
drhfdd6e852005-12-16 01:06:16 +00002356 const char *zDb = pDb->zName;
danielk197753c0f742005-03-29 03:10:59 +00002357 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002358 goto exit_create_index;
2359 }
2360 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002361 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002362 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002363 goto exit_create_index;
2364 }
drhe5f9c642003-01-13 23:27:31 +00002365 }
2366#endif
2367
drh75897232000-05-29 14:26:00 +00002368 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002369 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002370 ** So create a fake list to simulate this.
2371 */
2372 if( pList==0 ){
drh2646da72005-12-09 20:02:05 +00002373 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
2374 nullId.n = strlen((char*)nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002375 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002376 if( pList==0 ) goto exit_create_index;
drhfdd6e852005-12-16 01:06:16 +00002377 pList->a[0].sortOrder = sortOrder;
drh75897232000-05-29 14:26:00 +00002378 }
2379
danielk1977b3bf5562006-01-10 17:58:23 +00002380 /* Figure out how many bytes of space are required to store explicitly
2381 ** specified collation sequence names.
2382 */
2383 for(i=0; i<pList->nExpr; i++){
2384 Expr *pExpr = pList->a[i].pExpr;
2385 if( pExpr ){
2386 nExtra += (1 + strlen(pExpr->pColl->zName));
2387 }
2388 }
2389
drh75897232000-05-29 14:26:00 +00002390 /*
2391 ** Allocate the index structure.
2392 */
drhfdd6e852005-12-16 01:06:16 +00002393 nName = strlen(zName);
danielk1977b3bf5562006-01-10 17:58:23 +00002394 nCol = pList->nExpr;
2395 pIndex = sqliteMalloc(
2396 sizeof(Index) + /* Index structure */
2397 sizeof(int)*nCol + /* Index.aiColumn */
2398 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
2399 sizeof(char *)*nCol + /* Index.azColl */
2400 sizeof(u8)*nCol + /* Index.aSortOrder */
2401 nName + 1 + /* Index.zName */
2402 nExtra /* Collation sequence names */
2403 );
danielk19779e128002006-01-18 16:51:35 +00002404 if( sqlite3MallocFailed() ) goto exit_create_index;
drh78aecb72006-02-10 18:08:09 +00002405 pIndex->azColl = (char**)(&pIndex[1]);
2406 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
danielk1977bab45c62006-01-16 15:14:27 +00002407 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
drh78aecb72006-02-10 18:08:09 +00002408 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
danielk1977b3bf5562006-01-10 17:58:23 +00002409 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
2410 zExtra = (char *)(&pIndex->zName[nName+1]);
drh75897232000-05-29 14:26:00 +00002411 strcpy(pIndex->zName, zName);
2412 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002413 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002414 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002415 pIndex->autoIndex = pName==0;
danielk1977da184232006-01-05 11:34:32 +00002416 pIndex->pSchema = db->aDb[iDb].pSchema;
drh75897232000-05-29 14:26:00 +00002417
drhfdd6e852005-12-16 01:06:16 +00002418 /* Check to see if we should honor DESC requests on index columns
2419 */
danielk1977da184232006-01-05 11:34:32 +00002420 if( pDb->pSchema->file_format>=4 ){
drhfdd6e852005-12-16 01:06:16 +00002421 sortOrderMask = -1; /* Honor DESC */
drhfdd6e852005-12-16 01:06:16 +00002422 }else{
2423 sortOrderMask = 0; /* Ignore DESC */
2424 }
2425
drh1ccde152000-06-17 13:12:39 +00002426 /* Scan the names of the columns of the table to be indexed and
2427 ** load the column indices into the Index structure. Report an error
2428 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002429 */
drhfdd6e852005-12-16 01:06:16 +00002430 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
2431 const char *zColName = pListItem->zName;
2432 Column *pTabCol;
drh85eeb692005-12-21 03:16:42 +00002433 int requestedSortOrder;
danielk1977b3bf5562006-01-10 17:58:23 +00002434 char *zColl; /* Collation sequence */
2435
drhfdd6e852005-12-16 01:06:16 +00002436 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
2437 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002438 }
2439 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002440 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhfdd6e852005-12-16 01:06:16 +00002441 pTab->zName, zColName);
drh75897232000-05-29 14:26:00 +00002442 goto exit_create_index;
2443 }
drh967e8b72000-06-21 13:59:10 +00002444 pIndex->aiColumn[i] = j;
drhfdd6e852005-12-16 01:06:16 +00002445 if( pListItem->pExpr ){
2446 assert( pListItem->pExpr->pColl );
danielk1977b3bf5562006-01-10 17:58:23 +00002447 zColl = zExtra;
2448 strcpy(zExtra, pListItem->pExpr->pColl->zName);
2449 zExtra += (strlen(zColl) + 1);
danielk19770202b292004-06-09 09:55:16 +00002450 }else{
danielk1977b3bf5562006-01-10 17:58:23 +00002451 zColl = pTab->aCol[j].zColl;
2452 if( !zColl ){
2453 zColl = db->pDfltColl->zName;
2454 }
danielk19770202b292004-06-09 09:55:16 +00002455 }
danielk1977b3bf5562006-01-10 17:58:23 +00002456 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
danielk19777cedc8d2004-06-10 10:50:08 +00002457 goto exit_create_index;
2458 }
danielk1977b3bf5562006-01-10 17:58:23 +00002459 pIndex->azColl[i] = zColl;
drhd946db02005-12-29 19:23:06 +00002460 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
danielk1977b3bf5562006-01-10 17:58:23 +00002461 pIndex->aSortOrder[i] = requestedSortOrder;
drh75897232000-05-29 14:26:00 +00002462 }
drh51147ba2005-07-23 22:59:55 +00002463 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002464
danielk1977d8123362004-06-12 09:25:12 +00002465 if( pTab==pParse->pNewTable ){
2466 /* This routine has been called to create an automatic index as a
2467 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2468 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2469 ** i.e. one of:
2470 **
2471 ** CREATE TABLE t(x PRIMARY KEY, y);
2472 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2473 **
2474 ** Either way, check to see if the table already has such an index. If
2475 ** so, don't bother creating this one. This only applies to
2476 ** automatically created indices. Users can do as they wish with
2477 ** explicit indices.
2478 */
2479 Index *pIdx;
2480 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2481 int k;
2482 assert( pIdx->onError!=OE_None );
2483 assert( pIdx->autoIndex );
2484 assert( pIndex->onError!=OE_None );
2485
2486 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2487 for(k=0; k<pIdx->nColumn; k++){
danielk1977b3bf5562006-01-10 17:58:23 +00002488 const char *z1 = pIdx->azColl[k];
2489 const char *z2 = pIndex->azColl[k];
danielk1977d8123362004-06-12 09:25:12 +00002490 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
danielk1977b3bf5562006-01-10 17:58:23 +00002491 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
2492 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
danielk1977d8123362004-06-12 09:25:12 +00002493 }
2494 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002495 if( pIdx->onError!=pIndex->onError ){
2496 /* This constraint creates the same index as a previous
2497 ** constraint specified somewhere in the CREATE TABLE statement.
2498 ** However the ON CONFLICT clauses are different. If both this
2499 ** constraint and the previous equivalent constraint have explicit
2500 ** ON CONFLICT clauses this is an error. Otherwise, use the
2501 ** explicitly specified behaviour for the index.
2502 */
2503 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2504 sqlite3ErrorMsg(pParse,
2505 "conflicting ON CONFLICT clauses specified", 0);
2506 }
2507 if( pIdx->onError==OE_Default ){
2508 pIdx->onError = pIndex->onError;
2509 }
2510 }
danielk1977d8123362004-06-12 09:25:12 +00002511 goto exit_create_index;
2512 }
2513 }
2514 }
2515
drh75897232000-05-29 14:26:00 +00002516 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002517 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002518 */
drh234c39d2004-07-24 03:30:47 +00002519 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002520 Index *p;
danielk1977da184232006-01-05 11:34:32 +00002521 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
drh3c8bf552003-07-01 18:13:14 +00002522 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002523 if( p ){
2524 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002525 goto exit_create_index;
2526 }
drh5e00f6c2001-09-13 13:46:56 +00002527 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002528 if( pTblName!=0 ){
2529 pIndex->tnum = db->init.newTnum;
2530 }
drhd78eeee2001-09-13 16:18:53 +00002531 }
2532
drh1d85d932004-02-14 23:05:52 +00002533 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002534 ** involves writing the index into the master table and filling in the
2535 ** index with the current table contents.
2536 **
drh1d85d932004-02-14 23:05:52 +00002537 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2538 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002539 ** CREATE INDEX statements are read out of the master table. In
2540 ** the latter case the index already exists on disk, which is why
2541 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002542 **
danielk1977cbb18d22004-05-28 11:37:27 +00002543 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002544 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2545 ** has just been created, it contains no data and the index initialization
2546 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002547 */
drh1d85d932004-02-14 23:05:52 +00002548 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002549 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002550 char *zStmt;
2551 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002552
danielk19774adee202004-05-08 08:23:19 +00002553 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002554 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002555
drhfdd6e852005-12-16 01:06:16 +00002556
drh063336a2004-11-05 20:58:39 +00002557 /* Create the rootpage for the index
2558 */
drhaee128d2005-02-14 20:48:18 +00002559 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002560 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002561 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2562
2563 /* Gather the complete text of the CREATE INDEX statement into
2564 ** the zStmt variable
2565 */
drhe0bc4042002-06-25 01:09:11 +00002566 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002567 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002568 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002569 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002570 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002571 pName->z);
2572 }else{
2573 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002574 /* zStmt = sqlite3MPrintf(""); */
2575 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002576 }
drh063336a2004-11-05 20:58:39 +00002577
2578 /* Add an entry in sqlite_master for this index
2579 */
2580 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002581 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002582 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2583 pIndex->zName,
2584 pTab->zName,
2585 zStmt
2586 );
2587 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2588 sqliteFree(zStmt);
2589
danielk1977a21c6b62005-01-24 10:25:59 +00002590 /* Fill the index with data and reparse the schema. Code an OP_Expire
2591 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002592 */
danielk1977cbb18d22004-05-28 11:37:27 +00002593 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002594 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002595 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002596 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2597 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002598 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002599 }
drh75897232000-05-29 14:26:00 +00002600 }
2601
danielk1977d8123362004-06-12 09:25:12 +00002602 /* When adding an index to the list of indices for a table, make
2603 ** sure all indices labeled OE_Replace come after all those labeled
2604 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2605 ** and INSERT.
2606 */
drh234c39d2004-07-24 03:30:47 +00002607 if( db->init.busy || pTblName==0 ){
2608 if( onError!=OE_Replace || pTab->pIndex==0
2609 || pTab->pIndex->onError==OE_Replace){
2610 pIndex->pNext = pTab->pIndex;
2611 pTab->pIndex = pIndex;
2612 }else{
2613 Index *pOther = pTab->pIndex;
2614 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2615 pOther = pOther->pNext;
2616 }
2617 pIndex->pNext = pOther->pNext;
2618 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002619 }
drh234c39d2004-07-24 03:30:47 +00002620 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002621 }
danielk1977d8123362004-06-12 09:25:12 +00002622
drh75897232000-05-29 14:26:00 +00002623 /* Clean up before exiting */
2624exit_create_index:
drh956bc922004-07-24 17:38:29 +00002625 if( pIndex ){
2626 freeIndex(pIndex);
2627 }
danielk19770202b292004-06-09 09:55:16 +00002628 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002629 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002630 sqliteFree(zName);
2631 return;
2632}
2633
2634/*
drhd28bcb32005-12-21 14:43:11 +00002635** Generate code to make sure the file format number is at least minFormat.
2636** The generated code will increase the file format number if necessary.
2637*/
2638void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
2639 Vdbe *v;
2640 v = sqlite3GetVdbe(pParse);
2641 if( v ){
2642 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
2643 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2644 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
2645 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
2646 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
2647 }
2648}
2649
2650/*
drh51147ba2005-07-23 22:59:55 +00002651** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002652** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002653**
2654** aiRowEst[0] is suppose to contain the number of elements in the index.
2655** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2656** number of rows in the table that match any particular value of the
2657** first column of the index. aiRowEst[2] is an estimate of the number
2658** of rows that match any particular combiniation of the first 2 columns
2659** of the index. And so forth. It must always be the case that
2660*
2661** aiRowEst[N]<=aiRowEst[N-1]
2662** aiRowEst[N]>=1
2663**
2664** Apart from that, we have little to go on besides intuition as to
2665** how aiRowEst[] should be initialized. The numbers generated here
2666** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002667*/
2668void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002669 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002670 int i;
drh28c4cf42005-07-27 20:41:43 +00002671 assert( a!=0 );
2672 a[0] = 1000000;
drhdb513882006-05-11 23:14:59 +00002673 for(i=pIdx->nColumn; i>=5; i--){
2674 a[i] = 5;
2675 }
2676 while( i>=1 ){
2677 a[i] = 11 - i;
2678 i--;
drh28c4cf42005-07-27 20:41:43 +00002679 }
2680 if( pIdx->onError!=OE_None ){
2681 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002682 }
2683}
2684
2685/*
drh74e24cd2002-01-09 03:19:59 +00002686** This routine will drop an existing named index. This routine
2687** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002688*/
drh4d91a702006-01-04 15:54:36 +00002689void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
drh75897232000-05-29 14:26:00 +00002690 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002691 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002692 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +00002693 int iDb;
drh75897232000-05-29 14:26:00 +00002694
danielk19779e128002006-01-18 16:51:35 +00002695 if( pParse->nErr || sqlite3MallocFailed() ){
danielk1977d5d56522005-03-16 12:15:20 +00002696 goto exit_drop_index;
2697 }
drhd24cc422003-03-27 12:51:24 +00002698 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002699 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2700 goto exit_drop_index;
2701 }
danielk19774adee202004-05-08 08:23:19 +00002702 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002703 if( pIndex==0 ){
drh4d91a702006-01-04 15:54:36 +00002704 if( !ifExists ){
2705 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
2706 }
drha6ecd332004-06-10 00:29:09 +00002707 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002708 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002709 }
drh485b39b2002-07-13 03:11:52 +00002710 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002711 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002712 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002713 goto exit_drop_index;
2714 }
danielk1977da184232006-01-05 11:34:32 +00002715 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
drhe5f9c642003-01-13 23:27:31 +00002716#ifndef SQLITE_OMIT_AUTHORIZATION
2717 {
2718 int code = SQLITE_DROP_INDEX;
2719 Table *pTab = pIndex->pTable;
danielk1977da184232006-01-05 11:34:32 +00002720 const char *zDb = db->aDb[iDb].zName;
2721 const char *zTab = SCHEMA_TABLE(iDb);
danielk19774adee202004-05-08 08:23:19 +00002722 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002723 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002724 }
danielk1977da184232006-01-05 11:34:32 +00002725 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002726 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002727 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002728 }
drhed6c8672003-01-12 18:02:16 +00002729 }
drhe5f9c642003-01-13 23:27:31 +00002730#endif
drh75897232000-05-29 14:26:00 +00002731
2732 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002733 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002734 if( v ){
drhb17131a2004-11-05 22:18:49 +00002735 sqlite3NestedParse(pParse,
2736 "DELETE FROM %Q.%s WHERE name=%Q",
2737 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2738 pIndex->zName
2739 );
2740 sqlite3ChangeCookie(db, v, iDb);
2741 destroyRootPage(pParse, pIndex->tnum, iDb);
2742 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002743 }
2744
drhd24cc422003-03-27 12:51:24 +00002745exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002746 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002747}
2748
2749/*
drh13449892005-09-07 21:22:45 +00002750** ppArray points into a structure where there is an array pointer
2751** followed by two integers. The first integer is the
2752** number of elements in the structure array. The second integer
2753** is the number of allocated slots in the array.
2754**
2755** In other words, the structure looks something like this:
2756**
2757** struct Example1 {
2758** struct subElem *aEntry;
2759** int nEntry;
2760** int nAlloc;
2761** }
2762**
2763** The pnEntry parameter points to the equivalent of Example1.nEntry.
2764**
2765** This routine allocates a new slot in the array, zeros it out,
2766** and returns its index. If malloc fails a negative number is returned.
2767**
2768** szEntry is the sizeof of a single array entry. initSize is the
2769** number of array entries allocated on the initial allocation.
2770*/
2771int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
2772 char *p;
2773 int *an = (int*)&ppArray[1];
2774 if( an[0]>=an[1] ){
2775 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002776 int newSize;
2777 newSize = an[1]*2 + initSize;
2778 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002779 if( pNew==0 ){
2780 return -1;
2781 }
drh5360ad32005-09-08 00:13:27 +00002782 an[1] = newSize;
drh13449892005-09-07 21:22:45 +00002783 *ppArray = pNew;
2784 }
2785 p = *ppArray;
2786 memset(&p[an[0]*szEntry], 0, szEntry);
2787 return an[0]++;
2788}
2789
2790/*
drh75897232000-05-29 14:26:00 +00002791** Append a new element to the given IdList. Create a new IdList if
2792** need be.
drhdaffd0e2001-04-11 14:28:42 +00002793**
2794** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002795*/
danielk19774adee202004-05-08 08:23:19 +00002796IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002797 int i;
drh75897232000-05-29 14:26:00 +00002798 if( pList==0 ){
2799 pList = sqliteMalloc( sizeof(IdList) );
2800 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002801 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002802 }
drh13449892005-09-07 21:22:45 +00002803 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
2804 if( i<0 ){
2805 sqlite3IdListDelete(pList);
2806 return 0;
drh75897232000-05-29 14:26:00 +00002807 }
drh13449892005-09-07 21:22:45 +00002808 pList->a[i].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002809 return pList;
2810}
2811
2812/*
drhfe05af82005-07-21 03:14:59 +00002813** Delete an IdList.
2814*/
2815void sqlite3IdListDelete(IdList *pList){
2816 int i;
2817 if( pList==0 ) return;
2818 for(i=0; i<pList->nId; i++){
2819 sqliteFree(pList->a[i].zName);
2820 }
2821 sqliteFree(pList->a);
2822 sqliteFree(pList);
2823}
2824
2825/*
2826** Return the index in pList of the identifier named zId. Return -1
2827** if not found.
2828*/
2829int sqlite3IdListIndex(IdList *pList, const char *zName){
2830 int i;
2831 if( pList==0 ) return -1;
2832 for(i=0; i<pList->nId; i++){
2833 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2834 }
2835 return -1;
2836}
2837
2838/*
drhad3cab52002-05-24 02:04:32 +00002839** Append a new table name to the given SrcList. Create a new SrcList if
2840** need be. A new entry is created in the SrcList even if pToken is NULL.
2841**
2842** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002843**
2844** If pDatabase is not null, it means that the table has an optional
2845** database name prefix. Like this: "database.table". The pDatabase
2846** points to the table name and the pTable points to the database name.
2847** The SrcList.a[].zName field is filled with the table name which might
2848** come from pTable (if pDatabase is NULL) or from pDatabase.
2849** SrcList.a[].zDatabase is filled with the database name from pTable,
2850** or with NULL if no database is specified.
2851**
2852** In other words, if call like this:
2853**
danielk19774adee202004-05-08 08:23:19 +00002854** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002855**
2856** Then B is a table name and the database name is unspecified. If called
2857** like this:
2858**
danielk19774adee202004-05-08 08:23:19 +00002859** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002860**
2861** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002862*/
danielk19774adee202004-05-08 08:23:19 +00002863SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002864 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002865 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002866 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002867 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002868 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002869 }
drh4305d102003-07-30 12:34:12 +00002870 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002871 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002872 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002873 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002874 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002875 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002876 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002877 return 0;
2878 }
drh113088e2003-03-20 01:16:58 +00002879 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002880 }
drha99db3b2004-06-19 14:49:12 +00002881 pItem = &pList->a[pList->nSrc];
2882 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002883 if( pDatabase && pDatabase->z==0 ){
2884 pDatabase = 0;
2885 }
2886 if( pDatabase && pTable ){
2887 Token *pTemp = pDatabase;
2888 pDatabase = pTable;
2889 pTable = pTemp;
2890 }
drha99db3b2004-06-19 14:49:12 +00002891 pItem->zName = sqlite3NameFromToken(pTable);
2892 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2893 pItem->iCursor = -1;
danielk19771787cca2006-02-10 07:07:14 +00002894 pItem->isPopulated = 0;
drhad3cab52002-05-24 02:04:32 +00002895 pList->nSrc++;
2896 return pList;
2897}
2898
2899/*
drh63eb5f22003-04-29 16:20:44 +00002900** Assign cursors to all tables in a SrcList
2901*/
danielk19774adee202004-05-08 08:23:19 +00002902void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002903 int i;
drh9b3187e2005-01-18 14:45:47 +00002904 struct SrcList_item *pItem;
danielk19779e128002006-01-18 16:51:35 +00002905 assert(pList || sqlite3MallocFailed() );
danielk1977261919c2005-12-06 12:52:59 +00002906 if( pList ){
2907 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2908 if( pItem->iCursor>=0 ) break;
2909 pItem->iCursor = pParse->nTab++;
2910 if( pItem->pSelect ){
2911 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
2912 }
drh63eb5f22003-04-29 16:20:44 +00002913 }
2914 }
2915}
2916
2917/*
drh75897232000-05-29 14:26:00 +00002918** Add an alias to the last identifier on the given identifier list.
2919*/
danielk19774adee202004-05-08 08:23:19 +00002920void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002921 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002922 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002923 }
2924}
2925
2926/*
drhad3cab52002-05-24 02:04:32 +00002927** Delete an entire SrcList including all its substructure.
2928*/
danielk19774adee202004-05-08 08:23:19 +00002929void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002930 int i;
drhbe5c89a2004-07-26 00:31:09 +00002931 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002932 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002933 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2934 sqliteFree(pItem->zDatabase);
2935 sqliteFree(pItem->zName);
2936 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002937 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002938 sqlite3SelectDelete(pItem->pSelect);
2939 sqlite3ExprDelete(pItem->pOn);
2940 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002941 }
drh75897232000-05-29 14:26:00 +00002942 sqliteFree(pList);
2943}
2944
drh982cef72000-05-30 16:27:03 +00002945/*
drhc4a3c772001-04-04 11:48:57 +00002946** Begin a transaction
2947*/
drh684917c2004-10-05 02:41:42 +00002948void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002949 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002950 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002951 int i;
drh5e00f6c2001-09-13 13:46:56 +00002952
drh001bbcb2003-03-19 03:14:00 +00002953 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk19779e128002006-01-18 16:51:35 +00002954 if( pParse->nErr || sqlite3MallocFailed() ) return;
danielk19774adee202004-05-08 08:23:19 +00002955 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002956
2957 v = sqlite3GetVdbe(pParse);
2958 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002959 if( type!=TK_DEFERRED ){
2960 for(i=0; i<db->nDb; i++){
2961 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2962 }
2963 }
danielk19771d850a72004-05-31 08:26:49 +00002964 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002965}
2966
2967/*
2968** Commit a transaction
2969*/
danielk19774adee202004-05-08 08:23:19 +00002970void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002971 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002972 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002973
drh001bbcb2003-03-19 03:14:00 +00002974 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk19779e128002006-01-18 16:51:35 +00002975 if( pParse->nErr || sqlite3MallocFailed() ) return;
danielk19774adee202004-05-08 08:23:19 +00002976 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002977
2978 v = sqlite3GetVdbe(pParse);
2979 if( v ){
2980 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002981 }
drhc4a3c772001-04-04 11:48:57 +00002982}
2983
2984/*
2985** Rollback a transaction
2986*/
danielk19774adee202004-05-08 08:23:19 +00002987void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002988 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002989 Vdbe *v;
2990
drh001bbcb2003-03-19 03:14:00 +00002991 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk19779e128002006-01-18 16:51:35 +00002992 if( pParse->nErr || sqlite3MallocFailed() ) return;
danielk19774adee202004-05-08 08:23:19 +00002993 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002994
danielk19774adee202004-05-08 08:23:19 +00002995 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002996 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002997 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002998 }
drhc4a3c772001-04-04 11:48:57 +00002999}
drhf57b14a2001-09-14 18:54:08 +00003000
3001/*
drhdc3ff9c2004-08-18 02:10:15 +00003002** Make sure the TEMP database is open and available for use. Return
3003** the number of errors. Leave any error messages in the pParse structure.
3004*/
danielk1977ddfb2f02006-02-17 12:25:14 +00003005int sqlite3OpenTempDatabase(Parse *pParse){
drhdc3ff9c2004-08-18 02:10:15 +00003006 sqlite3 *db = pParse->db;
3007 if( db->aDb[1].pBt==0 && !pParse->explain ){
3008 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
3009 if( rc!=SQLITE_OK ){
3010 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
3011 "file for storing temporary tables");
3012 pParse->rc = rc;
3013 return 1;
3014 }
3015 if( db->flags & !db->autoCommit ){
3016 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
3017 if( rc!=SQLITE_OK ){
3018 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
3019 "the temporary database file");
3020 pParse->rc = rc;
3021 return 1;
3022 }
3023 }
danielk197714db2662006-01-09 16:12:04 +00003024 assert( db->aDb[1].pSchema );
drhdc3ff9c2004-08-18 02:10:15 +00003025 }
3026 return 0;
3027}
3028
3029/*
drh80242052004-06-09 00:48:12 +00003030** Generate VDBE code that will verify the schema cookie and start
3031** a read-transaction for all named database files.
3032**
3033** It is important that all schema cookies be verified and all
3034** read transactions be started before anything else happens in
3035** the VDBE program. But this routine can be called after much other
3036** code has been generated. So here is what we do:
3037**
drhc275b4e2004-07-19 17:25:24 +00003038** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00003039** will jump to a subroutine at the end of the program. Then we
3040** record every database that needs its schema verified in the
3041** pParse->cookieMask field. Later, after all other code has been
3042** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00003043** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00003044** will be made to point to that subroutine. The generation of the
3045** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00003046**
3047** If iDb<0 then code the OP_Goto only - don't set flag to verify the
3048** schema on any databases. This can be used to position the OP_Goto
3049** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00003050*/
danielk19774adee202004-05-08 08:23:19 +00003051void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00003052 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00003053 Vdbe *v;
3054 int mask;
3055
3056 v = sqlite3GetVdbe(pParse);
3057 if( v==0 ) return; /* This only happens if there was a prior error */
3058 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00003059 if( pParse->cookieGoto==0 ){
3060 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00003061 }
drhc275b4e2004-07-19 17:25:24 +00003062 if( iDb>=0 ){
3063 assert( iDb<db->nDb );
3064 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
drh8aa34ae2006-03-13 12:54:09 +00003065 assert( iDb<MAX_ATTACHED+2 );
drhc275b4e2004-07-19 17:25:24 +00003066 mask = 1<<iDb;
3067 if( (pParse->cookieMask & mask)==0 ){
3068 pParse->cookieMask |= mask;
danielk1977da184232006-01-05 11:34:32 +00003069 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00003070 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00003071 sqlite3OpenTempDatabase(pParse);
3072 }
drhc275b4e2004-07-19 17:25:24 +00003073 }
drh001bbcb2003-03-19 03:14:00 +00003074 }
drh001bbcb2003-03-19 03:14:00 +00003075}
3076
3077/*
drh1c928532002-01-31 15:54:21 +00003078** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00003079** might change the database.
3080**
3081** This routine starts a new transaction if we are not already within
3082** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00003083** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00003084** be set for operations that might fail (due to a constraint) part of
3085** the way through and which will need to undo some writes without having to
3086** rollback the whole transaction. For operations where all constraints
3087** can be checked before any changes are made to the database, it is never
3088** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00003089**
drh8bf8dc92003-05-17 17:35:10 +00003090** Only database iDb and the temp database are made writable by this call.
3091** If iDb==0, then the main and temp databases are made writable. If
3092** iDb==1 then only the temp database is made writable. If iDb>1 then the
3093** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00003094*/
drh7f0f12e2004-05-21 13:39:50 +00003095void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00003096 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00003097 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00003098 sqlite3CodeVerifySchema(pParse, iDb);
3099 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00003100 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00003101 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00003102 }
danielk197753c0f742005-03-29 03:10:59 +00003103 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00003104 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00003105 }
3106}
3107
drh4343fea2004-11-05 23:46:15 +00003108/*
3109** Check to see if pIndex uses the collating sequence pColl. Return
3110** true if it does and false if it does not.
3111*/
3112#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003113static int collationMatch(const char *zColl, Index *pIndex){
3114 int i;
3115 for(i=0; i<pIndex->nColumn; i++){
3116 const char *z = pIndex->azColl[i];
3117 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
3118 return 1;
3119 }
drh4343fea2004-11-05 23:46:15 +00003120 }
3121 return 0;
3122}
3123#endif
3124
3125/*
3126** Recompute all indices of pTab that use the collating sequence pColl.
3127** If pColl==0 then recompute all indices of pTab.
3128*/
3129#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003130static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003131 Index *pIndex; /* An index associated with pTab */
3132
3133 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
danielk1977b3bf5562006-01-10 17:58:23 +00003134 if( zColl==0 || collationMatch(zColl, pIndex) ){
danielk1977da184232006-01-05 11:34:32 +00003135 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3136 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh4343fea2004-11-05 23:46:15 +00003137 sqlite3RefillIndex(pParse, pIndex, -1);
3138 }
3139 }
3140}
3141#endif
3142
3143/*
3144** Recompute all indices of all tables in all databases where the
3145** indices use the collating sequence pColl. If pColl==0 then recompute
3146** all indices everywhere.
3147*/
3148#ifndef SQLITE_OMIT_REINDEX
danielk1977b3bf5562006-01-10 17:58:23 +00003149static void reindexDatabases(Parse *pParse, char const *zColl){
drh4343fea2004-11-05 23:46:15 +00003150 Db *pDb; /* A single database */
3151 int iDb; /* The database index number */
3152 sqlite3 *db = pParse->db; /* The database connection */
3153 HashElem *k; /* For looping over tables in pDb */
3154 Table *pTab; /* A table in the database */
3155
3156 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
drh43617e92006-03-06 20:55:46 +00003157 assert( pDb!=0 );
danielk1977da184232006-01-05 11:34:32 +00003158 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00003159 pTab = (Table*)sqliteHashData(k);
danielk1977b3bf5562006-01-10 17:58:23 +00003160 reindexTable(pParse, pTab, zColl);
drh4343fea2004-11-05 23:46:15 +00003161 }
3162 }
3163}
3164#endif
3165
3166/*
drheee46cf2004-11-06 00:02:48 +00003167** Generate code for the REINDEX command.
3168**
3169** REINDEX -- 1
3170** REINDEX <collation> -- 2
3171** REINDEX ?<database>.?<tablename> -- 3
3172** REINDEX ?<database>.?<indexname> -- 4
3173**
3174** Form 1 causes all indices in all attached databases to be rebuilt.
3175** Form 2 rebuilds all indices in all databases that use the named
3176** collating function. Forms 3 and 4 rebuild the named index or all
3177** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00003178*/
3179#ifndef SQLITE_OMIT_REINDEX
3180void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
3181 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
3182 char *z; /* Name of a table or index */
3183 const char *zDb; /* Name of the database */
3184 Table *pTab; /* A table in the database */
3185 Index *pIndex; /* An index associated with pTab */
3186 int iDb; /* The database index number */
3187 sqlite3 *db = pParse->db; /* The database connection */
3188 Token *pObjName; /* Name of the table or index to be reindexed */
3189
danielk197733a5edc2005-01-27 00:22:02 +00003190 /* Read the database schema. If an error occurs, leave an error message
3191 ** and code in pParse and return NULL. */
3192 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00003193 return;
danielk197733a5edc2005-01-27 00:22:02 +00003194 }
3195
drhe497f002004-11-07 13:01:49 +00003196 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00003197 reindexDatabases(pParse, 0);
3198 return;
drhe497f002004-11-07 13:01:49 +00003199 }else if( pName2==0 || pName2->z==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00003200 assert( pName1->z );
danielk197714db2662006-01-09 16:12:04 +00003201 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
drh4343fea2004-11-05 23:46:15 +00003202 if( pColl ){
danielk1977f0113002006-01-24 12:09:17 +00003203 char *zColl = sqliteStrNDup((const char *)pName1->z, pName1->n);
3204 if( zColl ){
3205 reindexDatabases(pParse, zColl);
3206 sqliteFree(zColl);
danielk1977b3bf5562006-01-10 17:58:23 +00003207 }
drh4343fea2004-11-05 23:46:15 +00003208 return;
3209 }
3210 }
3211 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
3212 if( iDb<0 ) return;
3213 z = sqlite3NameFromToken(pObjName);
3214 zDb = db->aDb[iDb].zName;
3215 pTab = sqlite3FindTable(db, z, zDb);
3216 if( pTab ){
3217 reindexTable(pParse, pTab, 0);
3218 sqliteFree(z);
3219 return;
3220 }
3221 pIndex = sqlite3FindIndex(db, z, zDb);
3222 sqliteFree(z);
3223 if( pIndex ){
3224 sqlite3BeginWriteOperation(pParse, 0, iDb);
3225 sqlite3RefillIndex(pParse, pIndex, -1);
3226 return;
3227 }
3228 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
3229}
3230#endif
danielk1977b3bf5562006-01-10 17:58:23 +00003231
3232/*
3233** Return a dynamicly allocated KeyInfo structure that can be used
3234** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
3235**
3236** If successful, a pointer to the new structure is returned. In this case
3237** the caller is responsible for calling sqliteFree() on the returned
3238** pointer. If an error occurs (out of memory or missing collation
3239** sequence), NULL is returned and the state of pParse updated to reflect
3240** the error.
3241*/
3242KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
3243 int i;
3244 int nCol = pIdx->nColumn;
3245 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
3246 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
3247
3248 if( pKey ){
3249 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
3250 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
3251 for(i=0; i<nCol; i++){
3252 char *zColl = pIdx->azColl[i];
3253 assert( zColl );
3254 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
3255 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
3256 }
3257 pKey->nField = nCol;
3258 }
3259
3260 if( pParse->nErr ){
3261 sqliteFree(pKey);
3262 pKey = 0;
3263 }
3264 return pKey;
3265}