blob: e6c914c2441a6d488f7362e937640137f18ce8dd [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**
drh5360ad32005-09-08 00:13:27 +000025** $Id: build.c,v 1.346 2005/09/08 00:13:27 drh Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
drhf57b14a2001-09-14 18:54:08 +000028#include <ctype.h>
drh75897232000-05-29 14:26:00 +000029
30/*
drhe0bc4042002-06-25 01:09:11 +000031** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000032** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000033*/
danielk19774adee202004-05-08 08:23:19 +000034void sqlite3BeginParse(Parse *pParse, int explainFlag){
drhe0bc4042002-06-25 01:09:11 +000035 pParse->explain = explainFlag;
drh7c972de2003-09-06 22:18:07 +000036 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000037}
38
39/*
drh75897232000-05-29 14:26:00 +000040** This routine is called after a single SQL statement has been
drh80242052004-06-09 00:48:12 +000041** parsed and a VDBE program to execute that statement has been
42** prepared. This routine puts the finishing touches on the
43** VDBE program and resets the pParse structure for the next
44** parse.
drh75897232000-05-29 14:26:00 +000045**
46** Note that if an error occurred, it might be the case that
47** no VDBE code was generated.
48*/
drh80242052004-06-09 00:48:12 +000049void sqlite3FinishCoding(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +000050 sqlite3 *db;
drh80242052004-06-09 00:48:12 +000051 Vdbe *v;
drhb86ccfb2003-01-28 23:13:10 +000052
danielk197724b03fd2004-05-10 10:34:34 +000053 if( sqlite3_malloc_failed ) return;
drh205f48e2004-11-05 00:43:11 +000054 if( pParse->nested ) return;
danielk1977441daf62005-02-01 03:46:43 +000055 if( !pParse->pVdbe ){
danielk1977c30f9e72005-02-09 07:05:46 +000056 if( pParse->rc==SQLITE_OK && pParse->nErr ){
57 pParse->rc = SQLITE_ERROR;
58 }
danielk1977441daf62005-02-01 03:46:43 +000059 return;
60 }
danielk197748d0d862005-02-01 03:09:52 +000061
drh80242052004-06-09 00:48:12 +000062 /* Begin by generating some termination code at the end of the
63 ** vdbe program
64 */
65 db = pParse->db;
66 v = sqlite3GetVdbe(pParse);
67 if( v ){
68 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
drh0e3d7472004-06-19 17:33:07 +000069
70 /* The cookie mask contains one bit for each database file open.
71 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
72 ** set for each database that is used. Generate code to start a
73 ** transaction on each used database and to verify the schema cookie
74 ** on each used database.
75 */
drhc275b4e2004-07-19 17:25:24 +000076 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +000077 u32 mask;
78 int iDb;
drhc275b4e2004-07-19 17:25:24 +000079 sqlite3VdbeChangeP2(v, pParse->cookieGoto-1, sqlite3VdbeCurrentAddr(v));
drh80242052004-06-09 00:48:12 +000080 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
81 if( (mask & pParse->cookieMask)==0 ) continue;
82 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drhc275b4e2004-07-19 17:25:24 +000083 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +000084 }
drhc275b4e2004-07-19 17:25:24 +000085 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +000086 }
drh80242052004-06-09 00:48:12 +000087
drh19e2d372005-08-29 23:00:03 +000088#ifndef SQLITE_OMIT_TRACE
drh71c697e2004-08-08 23:39:19 +000089 /* Add a No-op that contains the complete text of the compiled SQL
90 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +000091 ** of the program.
92 **
drh23bf66d2004-12-14 03:34:34 +000093 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +000094 */
95 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh19e2d372005-08-29 23:00:03 +000096#endif /* SQLITE_OMIT_TRACE */
drh71c697e2004-08-08 23:39:19 +000097 }
98
drh3f7d4e42004-07-24 14:35:58 +000099
drh80242052004-06-09 00:48:12 +0000100 /* Get the VDBE program ready for execution
101 */
drhb86ccfb2003-01-28 23:13:10 +0000102 if( v && pParse->nErr==0 ){
103 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000104 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +0000105 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
drh13449892005-09-07 21:22:45 +0000106 pParse->nTab+3, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000107 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000108 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000109 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000110 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000111 }
drha226d052002-09-25 19:04:07 +0000112 pParse->nTab = 0;
113 pParse->nMem = 0;
114 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000115 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000116 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000117 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000118}
119
120/*
drh205f48e2004-11-05 00:43:11 +0000121** Run the parser and code generator recursively in order to generate
122** code for the SQL statement given onto the end of the pParse context
123** currently under construction. When the parser is run recursively
124** this way, the final OP_Halt is not appended and other initialization
125** and finalization steps are omitted because those are handling by the
126** outermost parser.
127**
128** Not everything is nestable. This facility is designed to permit
129** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000130** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000131*/
132void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
133 va_list ap;
134 char *zSql;
135 int rc;
drhf1974842004-11-05 03:56:00 +0000136# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
137 char saveBuf[SAVE_SZ];
138
drh205f48e2004-11-05 00:43:11 +0000139 if( pParse->nErr ) return;
140 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
141 va_start(ap, zFormat);
142 zSql = sqlite3VMPrintf(zFormat, ap);
143 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000144 if( zSql==0 ){
145 return; /* A malloc must have failed */
146 }
drh205f48e2004-11-05 00:43:11 +0000147 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000148 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
149 memset(&pParse->nVar, 0, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000150 rc = sqlite3RunParser(pParse, zSql, 0);
151 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000152 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000153 pParse->nested--;
154}
155
156/*
danielk19778a414492004-06-29 08:59:35 +0000157** Locate the in-memory structure that describes a particular database
158** table given the name of that table and (optionally) the name of the
159** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000160**
danielk19778a414492004-06-29 08:59:35 +0000161** If zDatabase is 0, all databases are searched for the table and the
162** first matching table is returned. (No checking for duplicate table
163** names is done.) The search order is TEMP first, then MAIN, then any
164** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000165**
danielk19774adee202004-05-08 08:23:19 +0000166** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000167*/
drh9bb575f2004-09-06 17:24:11 +0000168Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000169 Table *p = 0;
170 int i;
drh645f63e2004-06-22 13:22:40 +0000171 assert( zName!=0 );
danielk19778a414492004-06-29 08:59:35 +0000172 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
danielk197753c0f742005-03-29 03:10:59 +0000173 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000174 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000175 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
176 p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000177 if( p ) break;
178 }
drh74e24cd2002-01-09 03:19:59 +0000179 return p;
drh75897232000-05-29 14:26:00 +0000180}
181
182/*
danielk19778a414492004-06-29 08:59:35 +0000183** Locate the in-memory structure that describes a particular database
184** table given the name of that table and (optionally) the name of the
185** database containing the table. Return NULL if not found. Also leave an
186** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000187**
danielk19778a414492004-06-29 08:59:35 +0000188** The difference between this routine and sqlite3FindTable() is that this
189** routine leaves an error message in pParse->zErrMsg where
190** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000191*/
danielk19774adee202004-05-08 08:23:19 +0000192Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000193 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000194
danielk19778a414492004-06-29 08:59:35 +0000195 /* Read the database schema. If an error occurs, leave an error message
196 ** and code in pParse and return NULL. */
197 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
198 return 0;
199 }
200
danielk19774adee202004-05-08 08:23:19 +0000201 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000202 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000203 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000204 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
drha69d9162003-04-17 22:57:53 +0000205 }else{
danielk19774adee202004-05-08 08:23:19 +0000206 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000207 }
drha6ecd332004-06-10 00:29:09 +0000208 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000209 }
210 return p;
211}
212
213/*
214** Locate the in-memory structure that describes
215** a particular index given the name of that index
216** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000217** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000218**
219** If zDatabase is 0, all databases are searched for the
220** table and the first matching index is returned. (No checking
221** for duplicate index names is done.) The search order is
222** TEMP first, then MAIN, then any auxiliary databases added
223** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000224*/
drh9bb575f2004-09-06 17:24:11 +0000225Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000226 Index *p = 0;
227 int i;
danielk19778a414492004-06-29 08:59:35 +0000228 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
danielk197753c0f742005-03-29 03:10:59 +0000229 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000230 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000231 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
232 p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000233 if( p ) break;
234 }
drh74e24cd2002-01-09 03:19:59 +0000235 return p;
drh75897232000-05-29 14:26:00 +0000236}
237
238/*
drh956bc922004-07-24 17:38:29 +0000239** Reclaim the memory used by an index
240*/
241static void freeIndex(Index *p){
242 sqliteFree(p->zColAff);
243 sqliteFree(p);
244}
245
246/*
drh75897232000-05-29 14:26:00 +0000247** Remove the given index from the index hash table, and free
248** its memory structures.
249**
drhd229ca92002-01-09 13:30:41 +0000250** The index is removed from the database hash tables but
251** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000252** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000253*/
drh9bb575f2004-09-06 17:24:11 +0000254static void sqliteDeleteIndex(sqlite3 *db, Index *p){
drhd229ca92002-01-09 13:30:41 +0000255 Index *pOld;
drhd24cc422003-03-27 12:51:24 +0000256
drhd229ca92002-01-09 13:30:41 +0000257 assert( db!=0 && p->zName!=0 );
danielk19774adee202004-05-08 08:23:19 +0000258 pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
drhd24cc422003-03-27 12:51:24 +0000259 strlen(p->zName)+1, 0);
drh85c23c62005-08-20 03:03:04 +0000260 assert( pOld==0 || pOld==p );
drh956bc922004-07-24 17:38:29 +0000261 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000262}
263
264/*
drhc96d8532005-05-03 12:30:33 +0000265** For the index called zIdxName which is found in the database iDb,
266** unlike that index from its Table then remove the index from
267** the index hash table and free all memory structures associated
268** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000269*/
drh9bb575f2004-09-06 17:24:11 +0000270void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000271 Index *pIndex;
272 int len;
273
274 len = strlen(zIdxName);
275 pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0);
276 if( pIndex ){
277 if( pIndex->pTable->pIndex==pIndex ){
278 pIndex->pTable->pIndex = pIndex->pNext;
279 }else{
280 Index *p;
281 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
282 if( p && p->pNext==pIndex ){
283 p->pNext = pIndex->pNext;
284 }
drh5e00f6c2001-09-13 13:46:56 +0000285 }
drh956bc922004-07-24 17:38:29 +0000286 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000287 }
drh956bc922004-07-24 17:38:29 +0000288 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000289}
290
291/*
drhe0bc4042002-06-25 01:09:11 +0000292** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000293** a single database. This routine is called to reclaim memory
294** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000295** if there were schema changes during the transaction or if a
296** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000297**
298** If iDb<=0 then reset the internal schema tables for all database
299** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000300** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000301*/
drh9bb575f2004-09-06 17:24:11 +0000302void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drhe0bc4042002-06-25 01:09:11 +0000303 HashElem *pElem;
304 Hash temp1;
305 Hash temp2;
drh1c2d8412003-03-31 00:30:47 +0000306 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000307
drh1c2d8412003-03-31 00:30:47 +0000308 assert( iDb>=0 && iDb<db->nDb );
309 db->flags &= ~SQLITE_Initialized;
310 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000311 Db *pDb = &db->aDb[i];
312 temp1 = pDb->tblHash;
313 temp2 = pDb->trigHash;
danielk19774adee202004-05-08 08:23:19 +0000314 sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
315 sqlite3HashClear(&pDb->aFKey);
316 sqlite3HashClear(&pDb->idxHash);
drhd24cc422003-03-27 12:51:24 +0000317 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
drh40e016e2004-11-04 14:47:11 +0000318 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
drhd24cc422003-03-27 12:51:24 +0000319 }
danielk19774adee202004-05-08 08:23:19 +0000320 sqlite3HashClear(&temp2);
321 sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
drhd24cc422003-03-27 12:51:24 +0000322 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
323 Table *pTab = sqliteHashData(pElem);
danielk19774adee202004-05-08 08:23:19 +0000324 sqlite3DeleteTable(db, pTab);
drhd24cc422003-03-27 12:51:24 +0000325 }
danielk19774adee202004-05-08 08:23:19 +0000326 sqlite3HashClear(&temp1);
drh2958a4e2004-11-12 03:56:15 +0000327 pDb->pSeqTab = 0;
drh8bf8dc92003-05-17 17:35:10 +0000328 DbClearProperty(db, i, DB_SchemaLoaded);
drh1c2d8412003-03-31 00:30:47 +0000329 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000330 }
drh1c2d8412003-03-31 00:30:47 +0000331 assert( iDb==0 );
332 db->flags &= ~SQLITE_InternChanges;
333
334 /* If one or more of the auxiliary database files has been closed,
335 ** then remove then from the auxiliary database list. We take the
336 ** opportunity to do this here since we have just deleted all of the
337 ** schema hash tables and therefore do not have to make any changes
338 ** to any of those tables.
339 */
drh4d189ca2004-02-12 18:46:38 +0000340 for(i=0; i<db->nDb; i++){
341 struct Db *pDb = &db->aDb[i];
342 if( pDb->pBt==0 ){
343 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
344 pDb->pAux = 0;
345 }
346 }
drh1c2d8412003-03-31 00:30:47 +0000347 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000348 struct Db *pDb = &db->aDb[i];
349 if( pDb->pBt==0 ){
350 sqliteFree(pDb->zName);
351 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000352 continue;
353 }
354 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000355 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000356 }
drh8bf8dc92003-05-17 17:35:10 +0000357 j++;
drh1c2d8412003-03-31 00:30:47 +0000358 }
359 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
360 db->nDb = j;
361 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
362 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
363 sqliteFree(db->aDb);
364 db->aDb = db->aDbStatic;
365 }
drhe0bc4042002-06-25 01:09:11 +0000366}
367
368/*
369** This routine is called whenever a rollback occurs. If there were
370** schema changes during the transaction, then we have to reset the
371** internal hash tables and reload them from disk.
372*/
drh9bb575f2004-09-06 17:24:11 +0000373void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000374 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000375 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000376 }
377}
378
379/*
380** This routine is called when a commit occurs.
381*/
drh9bb575f2004-09-06 17:24:11 +0000382void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000383 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000384}
385
386/*
drh956bc922004-07-24 17:38:29 +0000387** Clear the column names from a table or view.
388*/
389static void sqliteResetColumnNames(Table *pTable){
390 int i;
391 Column *pCol;
392 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000393 if( (pCol = pTable->aCol)!=0 ){
394 for(i=0; i<pTable->nCol; i++, pCol++){
395 sqliteFree(pCol->zName);
396 sqlite3ExprDelete(pCol->pDflt);
397 sqliteFree(pCol->zType);
398 }
399 sqliteFree(pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000400 }
drh956bc922004-07-24 17:38:29 +0000401 pTable->aCol = 0;
402 pTable->nCol = 0;
403}
404
405/*
drh75897232000-05-29 14:26:00 +0000406** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000407** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000408**
409** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000410** the table data structure from the hash table. Nor does it remove
411** foreign keys from the sqlite.aFKey hash table. But it does destroy
412** memory structures of the indices and foreign keys associated with
413** the table.
drhdaffd0e2001-04-11 14:28:42 +0000414**
415** Indices associated with the table are unlinked from the "db"
416** data structure if db!=NULL. If db==NULL, indices attached to
417** the table are deleted, but it is assumed they have already been
418** unlinked.
drh75897232000-05-29 14:26:00 +0000419*/
drh9bb575f2004-09-06 17:24:11 +0000420void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000421 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000422 FKey *pFKey, *pNextFKey;
423
drh75897232000-05-29 14:26:00 +0000424 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000425
drhed8a3bb2005-06-06 21:19:56 +0000426 /* Do not delete the table until the reference count reaches zero. */
427 pTable->nRef--;
428 if( pTable->nRef>0 ){
429 return;
430 }
431 assert( pTable->nRef==0 );
432
drhc2eef3b2002-08-31 18:53:06 +0000433 /* Delete all indices associated with this table
434 */
435 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
436 pNext = pIndex->pNext;
drhd24cc422003-03-27 12:51:24 +0000437 assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
drhc2eef3b2002-08-31 18:53:06 +0000438 sqliteDeleteIndex(db, pIndex);
439 }
440
danielk1977576ec6b2005-01-21 11:55:25 +0000441#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000442 /* Delete all foreign keys associated with this table. The keys
443 ** should have already been unlinked from the db->aFKey hash table
444 */
445 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
446 pNextFKey = pFKey->pNextFrom;
drhd24cc422003-03-27 12:51:24 +0000447 assert( pTable->iDb<db->nDb );
danielk19774adee202004-05-08 08:23:19 +0000448 assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
drhd24cc422003-03-27 12:51:24 +0000449 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000450 sqliteFree(pFKey);
451 }
danielk1977576ec6b2005-01-21 11:55:25 +0000452#endif
drhc2eef3b2002-08-31 18:53:06 +0000453
454 /* Delete the Table structure itself.
455 */
drh956bc922004-07-24 17:38:29 +0000456 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000457 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000458 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000459 sqlite3SelectDelete(pTable->pSelect);
drh75897232000-05-29 14:26:00 +0000460 sqliteFree(pTable);
461}
462
463/*
drh5edc3122001-09-13 21:53:09 +0000464** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000465** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000466*/
drh9bb575f2004-09-06 17:24:11 +0000467void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000468 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000469 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000470 Db *pDb;
471
drhd229ca92002-01-09 13:30:41 +0000472 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000473 assert( iDb>=0 && iDb<db->nDb );
474 assert( zTabName && zTabName[0] );
475 pDb = &db->aDb[iDb];
476 p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0);
477 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000478#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000479 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
480 int nTo = strlen(pF1->zTo) + 1;
481 pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo);
482 if( pF2==pF1 ){
483 sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo);
484 }else{
485 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
486 if( pF2 ){
487 pF2->pNextTo = pF1->pNextTo;
488 }
drhc2eef3b2002-08-31 18:53:06 +0000489 }
490 }
danielk1977576ec6b2005-01-21 11:55:25 +0000491#endif
drh956bc922004-07-24 17:38:29 +0000492 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000493 }
drh956bc922004-07-24 17:38:29 +0000494 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000495}
496
497/*
drha99db3b2004-06-19 14:49:12 +0000498** Given a token, return a string that consists of the text of that
499** token with any quotations removed. Space to hold the returned string
500** is obtained from sqliteMalloc() and must be freed by the calling
501** function.
drh75897232000-05-29 14:26:00 +0000502**
drhc96d8532005-05-03 12:30:33 +0000503** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000504** are not \000 terminated and are not persistent. The returned string
505** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000506*/
drha99db3b2004-06-19 14:49:12 +0000507char *sqlite3NameFromToken(Token *pName){
508 char *zName;
509 if( pName ){
510 zName = sqliteStrNDup(pName->z, pName->n);
511 sqlite3Dequote(zName);
512 }else{
513 zName = 0;
514 }
drh75897232000-05-29 14:26:00 +0000515 return zName;
516}
517
518/*
danielk1977cbb18d22004-05-28 11:37:27 +0000519** Open the sqlite_master table stored in database number iDb for
520** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000521*/
danielk1977cbb18d22004-05-28 11:37:27 +0000522void sqlite3OpenMasterTable(Vdbe *v, int iDb){
523 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000524 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000525 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000526}
527
528/*
danielk1977cbb18d22004-05-28 11:37:27 +0000529** The token *pName contains the name of a database (either "main" or
530** "temp" or the name of an attached db). This routine returns the
531** index of the named database in db->aDb[], or -1 if the named db
532** does not exist.
533*/
drhff2d5ea2005-07-23 00:41:48 +0000534int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000535 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000536 int n; /* Number of characters in the name */
537 Db *pDb; /* A database whose name space is being searched */
538 char *zName; /* Name we are searching for */
539
540 zName = sqlite3NameFromToken(pName);
541 if( zName ){
542 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000543 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000544 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
545 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000546 break;
drh73c42a12004-11-20 18:13:10 +0000547 }
danielk1977cbb18d22004-05-28 11:37:27 +0000548 }
drh73c42a12004-11-20 18:13:10 +0000549 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000550 }
danielk1977576ec6b2005-01-21 11:55:25 +0000551 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000552}
553
drh0e3d7472004-06-19 17:33:07 +0000554/* The table or view or trigger name is passed to this routine via tokens
555** pName1 and pName2. If the table name was fully qualified, for example:
556**
557** CREATE TABLE xxx.yyy (...);
558**
559** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
560** the table name is not fully qualified, i.e.:
561**
562** CREATE TABLE yyy(...);
563**
564** Then pName1 is set to "yyy" and pName2 is "".
565**
566** This routine sets the *ppUnqual pointer to point at the token (pName1 or
567** pName2) that stores the unqualified table name. The index of the
568** database "xxx" is returned.
569*/
danielk1977ef2cb632004-05-29 02:37:19 +0000570int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000571 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000572 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000573 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
574 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000575){
drh0e3d7472004-06-19 17:33:07 +0000576 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000577 sqlite3 *db = pParse->db;
578
579 if( pName2 && pName2->n>0 ){
580 assert( !db->init.busy );
581 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000582 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000583 if( iDb<0 ){
584 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
585 pParse->nErr++;
586 return -1;
587 }
588 }else{
589 assert( db->init.iDb==0 || db->init.busy );
590 iDb = db->init.iDb;
591 *pUnqual = pName1;
592 }
593 return iDb;
594}
595
596/*
danielk1977d8123362004-06-12 09:25:12 +0000597** This routine is used to check if the UTF-8 string zName is a legal
598** unqualified name for a new schema object (table, index, view or
599** trigger). All names are legal except those that begin with the string
600** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
601** is reserved for internal use.
602*/
603int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000604 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000605 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000606 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000607 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
608 return SQLITE_ERROR;
609 }
610 return SQLITE_OK;
611}
612
613/*
drh75897232000-05-29 14:26:00 +0000614** Begin constructing a new table representation in memory. This is
615** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000616** to a CREATE TABLE statement. In particular, this routine is called
617** after seeing tokens "CREATE" and "TABLE" and the table name. The
drhf57b3392001-10-08 13:22:32 +0000618** pStart token is the CREATE and pName is the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000619** flag is true if the table should be stored in the auxiliary database
620** file instead of in the main database file. This is normally the case
621** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000622** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000623**
drhf57b3392001-10-08 13:22:32 +0000624** The new table record is initialized and put in pParse->pNewTable.
625** As more of the CREATE TABLE statement is parsed, additional action
626** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000627** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000628** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000629*/
danielk19774adee202004-05-08 08:23:19 +0000630void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000631 Parse *pParse, /* Parser context */
632 Token *pStart, /* The "CREATE" token */
danielk1977cbb18d22004-05-28 11:37:27 +0000633 Token *pName1, /* First part of the name of the table or view */
634 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000635 int isTemp, /* True if this is a TEMP table */
636 int isView /* True if this is a VIEW */
637){
drh75897232000-05-29 14:26:00 +0000638 Table *pTable;
drhf57b3392001-10-08 13:22:32 +0000639 Index *pIdx;
drh23bf66d2004-12-14 03:34:34 +0000640 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000641 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000642 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000643 int iDb; /* Database number to create the table in */
644 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000645
danielk1977cbb18d22004-05-28 11:37:27 +0000646 /* The table or view name to create is passed to this routine via tokens
647 ** pName1 and pName2. If the table name was fully qualified, for example:
648 **
649 ** CREATE TABLE xxx.yyy (...);
650 **
651 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
652 ** the table name is not fully qualified, i.e.:
653 **
654 ** CREATE TABLE yyy(...);
655 **
656 ** Then pName1 is set to "yyy" and pName2 is "".
657 **
658 ** The call below sets the pName pointer to point at the token (pName1 or
659 ** pName2) that stores the unqualified table name. The variable iDb is
660 ** set to the index of the database that the table or view is to be
661 ** created in.
662 */
danielk1977ef2cb632004-05-29 02:37:19 +0000663 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000664 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000665 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000666 /* If creating a temp table, the name may not be qualified */
667 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000668 return;
669 }
danielk197753c0f742005-03-29 03:10:59 +0000670 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000671
672 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000673 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000674 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000675 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000676 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000677 }
drh1d85d932004-02-14 23:05:52 +0000678 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000679#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000680 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000681 {
682 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000683 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000684 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000685 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000686 }
drhe5f9c642003-01-13 23:27:31 +0000687 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000688 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000689 code = SQLITE_CREATE_TEMP_VIEW;
690 }else{
691 code = SQLITE_CREATE_VIEW;
692 }
693 }else{
danielk197753c0f742005-03-29 03:10:59 +0000694 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000695 code = SQLITE_CREATE_TEMP_TABLE;
696 }else{
697 code = SQLITE_CREATE_TABLE;
698 }
699 }
danielk19774adee202004-05-08 08:23:19 +0000700 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000701 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000702 }
703 }
704#endif
drhf57b3392001-10-08 13:22:32 +0000705
drhf57b3392001-10-08 13:22:32 +0000706 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000707 ** index or table name in the same database. Issue an error message if
708 ** it does.
drhf57b3392001-10-08 13:22:32 +0000709 */
danielk19775558a8a2005-01-17 07:53:44 +0000710 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
711 goto begin_table_error;
712 }
danielk19773df6b252004-05-29 10:23:19 +0000713 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
714 if( pTable ){
danielk19774adee202004-05-08 08:23:19 +0000715 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
drh23bf66d2004-12-14 03:34:34 +0000716 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000717 }
danielk19778a414492004-06-29 08:59:35 +0000718 if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 &&
719 ( iDb==0 || !db->init.busy) ){
danielk19774adee202004-05-08 08:23:19 +0000720 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
drh23bf66d2004-12-14 03:34:34 +0000721 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000722 }
723 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000724 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000725 pParse->rc = SQLITE_NOMEM;
726 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000727 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000728 }
drh75897232000-05-29 14:26:00 +0000729 pTable->zName = zName;
drh75897232000-05-29 14:26:00 +0000730 pTable->nCol = 0;
drh7020f652000-06-03 18:06:52 +0000731 pTable->aCol = 0;
drh4a324312001-12-21 14:30:42 +0000732 pTable->iPKey = -1;
drh75897232000-05-29 14:26:00 +0000733 pTable->pIndex = 0;
drh1c2d8412003-03-31 00:30:47 +0000734 pTable->iDb = iDb;
drhed8a3bb2005-06-06 21:19:56 +0000735 pTable->nRef = 1;
danielk19774adee202004-05-08 08:23:19 +0000736 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000737 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000738
drh4794f732004-11-05 17:17:50 +0000739 /* If this is the magic sqlite_sequence table used by autoincrement,
740 ** then record a pointer to this table in the main database structure
741 ** so that INSERT can find the table easily.
742 */
743#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000744 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh4794f732004-11-05 17:17:50 +0000745 db->aDb[iDb].pSeqTab = pTable;
746 }
747#endif
748
drh17f71932002-02-21 12:01:27 +0000749 /* Begin generating the code that will insert the table record into
750 ** the SQLITE_MASTER table. Note in particular that we must go ahead
751 ** and allocate the record number for the table entry now. Before any
752 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
753 ** indices to be created and the table record must come before the
754 ** indices. Hence, the record number for the table must be allocated
755 ** now.
756 */
danielk19774adee202004-05-08 08:23:19 +0000757 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk197736963fd2005-02-19 08:18:05 +0000758 int lbl;
danielk1977cbb18d22004-05-28 11:37:27 +0000759 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000760
danielk197736963fd2005-02-19 08:18:05 +0000761 /* If the file format and encoding in the database have not been set,
762 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000763 */
danielk197736963fd2005-02-19 08:18:05 +0000764 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
765 lbl = sqlite3VdbeMakeLabel(v);
766 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000767 sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
768 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
769 sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
770 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000771 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000772
drh4794f732004-11-05 17:17:50 +0000773 /* This just creates a place-holder record in the sqlite_master table.
774 ** The record created does not contain anything yet. It will be replaced
775 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000776 **
777 ** The rowid for the new entry is left on the top of the stack.
778 ** The rowid value is needed by the code that sqlite3EndTable will
779 ** generate.
drh4794f732004-11-05 17:17:50 +0000780 */
danielk1977a21c6b62005-01-24 10:25:59 +0000781#ifndef SQLITE_OMIT_VIEW
782 if( isView ){
783 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
784 }else
785#endif
786 {
787 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
788 }
danielk1977cbb18d22004-05-28 11:37:27 +0000789 sqlite3OpenMasterTable(v, iDb);
drhf0863fe2005-06-12 21:35:51 +0000790 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000791 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000792 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
793 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000794 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000795 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000796 }
drh23bf66d2004-12-14 03:34:34 +0000797
798 /* Normal (non-error) return. */
799 return;
800
801 /* If an error occurs, we jump here */
802begin_table_error:
803 sqliteFree(zName);
804 return;
drh75897232000-05-29 14:26:00 +0000805}
806
807/*
danielk1977c60e9b82005-01-31 12:42:29 +0000808** This macro is used to compare two strings in a case-insensitive manner.
809** It is slightly faster than calling sqlite3StrICmp() directly, but
810** produces larger code.
811**
812** WARNING: This macro is not compatible with the strcmp() family. It
813** returns true if the two strings are equal, otherwise false.
814*/
815#define STRICMP(x, y) (\
816sqlite3UpperToLower[*(unsigned char *)(x)]== \
817sqlite3UpperToLower[*(unsigned char *)(y)] \
818&& sqlite3StrICmp((x)+1,(y)+1)==0 )
819
820/*
drh75897232000-05-29 14:26:00 +0000821** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000822**
823** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000824** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000825** first to get things going. Then this routine is called for each
826** column.
drh75897232000-05-29 14:26:00 +0000827*/
danielk19774adee202004-05-08 08:23:19 +0000828void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000829 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000830 int i;
drha99db3b2004-06-19 14:49:12 +0000831 char *z;
drhc9b84a12002-06-20 11:36:48 +0000832 Column *pCol;
drh75897232000-05-29 14:26:00 +0000833 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000834 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000835 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000836 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000837 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000838 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000839 sqliteFree(z);
840 return;
841 }
842 }
drh75897232000-05-29 14:26:00 +0000843 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000844 Column *aNew;
845 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000846 if( aNew==0 ){
847 sqliteFree(z);
848 return;
849 }
drh6d4abfb2001-10-22 02:58:08 +0000850 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000851 }
drhc9b84a12002-06-20 11:36:48 +0000852 pCol = &p->aCol[p->nCol];
853 memset(pCol, 0, sizeof(p->aCol[0]));
854 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000855
856 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000857 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
858 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000859 */
danielk19774f057f92004-06-08 00:02:33 +0000860 pCol->affinity = SQLITE_AFF_NONE;
drhd3d39e92004-05-20 22:16:29 +0000861 pCol->pColl = pParse->db->pDfltColl;
drhc9b84a12002-06-20 11:36:48 +0000862 p->nCol++;
drh75897232000-05-29 14:26:00 +0000863}
864
865/*
drh382c0242001-10-06 16:33:02 +0000866** This routine is called by the parser while in the middle of
867** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
868** been seen on a column. This routine sets the notNull flag on
869** the column currently under construction.
870*/
danielk19774adee202004-05-08 08:23:19 +0000871void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000872 Table *p;
873 int i;
874 if( (p = pParse->pNewTable)==0 ) return;
875 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000876 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000877}
878
879/*
danielk197752a83fb2005-01-31 12:56:44 +0000880** Scan the column type name zType (length nType) and return the
881** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000882**
883** This routine does a case-independent search of zType for the
884** substrings in the following table. If one of the substrings is
885** found, the corresponding affinity is returned. If zType contains
886** more than one of the substrings, entries toward the top of
887** the table take priority. For example, if zType is 'BLOBINT',
888** SQLITE_AFF_INTEGER is returned.
889**
890** Substring | Affinity
891** --------------------------------
892** 'INT' | SQLITE_AFF_INTEGER
893** 'CHAR' | SQLITE_AFF_TEXT
894** 'CLOB' | SQLITE_AFF_TEXT
895** 'TEXT' | SQLITE_AFF_TEXT
896** 'BLOB' | SQLITE_AFF_NONE
897**
898** If none of the substrings in the above table are found,
899** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000900*/
drh487e2622005-06-25 18:42:14 +0000901char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000902 u32 h = 0;
903 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000904 const unsigned char *zIn = pType->z;
905 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000906
danielk1977b3dff962005-02-01 01:21:55 +0000907 while( zIn!=zEnd ){
908 h = (h<<8) + sqlite3UpperToLower[*zIn];
909 zIn++;
danielk1977201f7162005-02-01 02:13:29 +0000910 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
911 aff = SQLITE_AFF_TEXT;
912 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
913 aff = SQLITE_AFF_TEXT;
914 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
915 aff = SQLITE_AFF_TEXT;
916 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
917 && aff==SQLITE_AFF_NUMERIC ){
danielk1977b3dff962005-02-01 01:21:55 +0000918 aff = SQLITE_AFF_NONE;
danielk1977201f7162005-02-01 02:13:29 +0000919 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
danielk1977b3dff962005-02-01 01:21:55 +0000920 aff = SQLITE_AFF_INTEGER;
921 break;
danielk197752a83fb2005-01-31 12:56:44 +0000922 }
923 }
danielk1977b3dff962005-02-01 01:21:55 +0000924
925 return aff;
danielk197752a83fb2005-01-31 12:56:44 +0000926}
927
928/*
drh382c0242001-10-06 16:33:02 +0000929** This routine is called by the parser while in the middle of
930** parsing a CREATE TABLE statement. The pFirst token is the first
931** token in the sequence of tokens that describe the type of the
932** column currently under construction. pLast is the last token
933** in the sequence. Use this information to construct a string
934** that contains the typename of the column and store that string
935** in zType.
936*/
drh487e2622005-06-25 18:42:14 +0000937void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +0000938 Table *p;
drh487e2622005-06-25 18:42:14 +0000939 int i;
drhc9b84a12002-06-20 11:36:48 +0000940 Column *pCol;
drh487e2622005-06-25 18:42:14 +0000941
drh382c0242001-10-06 16:33:02 +0000942 if( (p = pParse->pNewTable)==0 ) return;
943 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +0000944 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +0000945 pCol = &p->aCol[i];
drhae29ffb2004-09-25 14:39:18 +0000946 assert( pCol->zType==0 );
drh487e2622005-06-25 18:42:14 +0000947 pCol->zType = sqlite3NameFromToken(pType);
948 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +0000949}
950
951/*
danielk19777977a172004-11-09 12:44:37 +0000952** The expression is the default value for the most recently added column
953** of the table currently under construction.
954**
955** Default value expressions must be constant. Raise an exception if this
956** is not the case.
drhd9b02572001-04-15 00:37:09 +0000957**
958** This routine is called by the parser while in the middle of
959** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +0000960*/
danielk19777977a172004-11-09 12:44:37 +0000961void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +0000962 Table *p;
danielk19777977a172004-11-09 12:44:37 +0000963 Column *pCol;
drh42b9d7c2005-08-13 00:56:27 +0000964 if( (p = pParse->pNewTable)!=0 ){
965 pCol = &(p->aCol[p->nCol-1]);
966 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
967 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
968 pCol->zName);
969 }else{
970 sqlite3ExprDelete(pCol->pDflt);
971 pCol->pDflt = sqlite3ExprDup(pExpr);
972 }
danielk19777977a172004-11-09 12:44:37 +0000973 }
974 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +0000975}
976
977/*
drh4a324312001-12-21 14:30:42 +0000978** Designate the PRIMARY KEY for the table. pList is a list of names
979** of columns that form the primary key. If pList is NULL, then the
980** most recently added column of the table is the primary key.
981**
982** A table can have at most one primary key. If the table already has
983** a primary key (and this is the second primary key) then create an
984** error.
985**
986** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +0000987** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +0000988** field of the table under construction to be the index of the
989** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
990** no INTEGER PRIMARY KEY.
991**
992** If the key is not an INTEGER PRIMARY KEY, then create a unique
993** index for the key. No index is created for INTEGER PRIMARY KEYs.
994*/
drh205f48e2004-11-05 00:43:11 +0000995void sqlite3AddPrimaryKey(
996 Parse *pParse, /* Parsing context */
997 ExprList *pList, /* List of field names to be indexed */
998 int onError, /* What to do with a uniqueness conflict */
999 int autoInc /* True if the AUTOINCREMENT keyword is present */
1000){
drh4a324312001-12-21 14:30:42 +00001001 Table *pTab = pParse->pNewTable;
1002 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001003 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +00001004 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001005 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001006 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001007 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001008 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001009 }
1010 pTab->hasPrimKey = 1;
1011 if( pList==0 ){
1012 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001013 pTab->aCol[iCol].isPrimKey = 1;
1014 }else{
danielk19770202b292004-06-09 09:55:16 +00001015 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001016 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001017 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1018 break;
1019 }
drh78100cc2003-08-23 22:40:53 +00001020 }
1021 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
drh4a324312001-12-21 14:30:42 +00001022 }
danielk19770202b292004-06-09 09:55:16 +00001023 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001024 }
1025 if( iCol>=0 && iCol<pTab->nCol ){
1026 zType = pTab->aCol[iCol].zType;
1027 }
danielk19773d68f032004-05-11 07:11:51 +00001028 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
drh4a324312001-12-21 14:30:42 +00001029 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001030 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001031 pTab->autoInc = autoInc;
1032 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001033#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001034 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1035 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001036#endif
drh4a324312001-12-21 14:30:42 +00001037 }else{
danielk1977cbb18d22004-05-28 11:37:27 +00001038 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
drhe0194f22003-02-26 13:52:51 +00001039 pList = 0;
drh4a324312001-12-21 14:30:42 +00001040 }
drhe0194f22003-02-26 13:52:51 +00001041
1042primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001043 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001044 return;
drh4a324312001-12-21 14:30:42 +00001045}
1046
1047/*
drhd3d39e92004-05-20 22:16:29 +00001048** Set the collation function of the most recently parsed table column
1049** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001050*/
drhd3d39e92004-05-20 22:16:29 +00001051void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001052 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001053 Index *pIdx;
drhd3d39e92004-05-20 22:16:29 +00001054 CollSeq *pColl;
danielk19770202b292004-06-09 09:55:16 +00001055 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001056
drhd3d39e92004-05-20 22:16:29 +00001057 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001058 i = p->nCol-1;
1059
1060 pColl = sqlite3LocateCollSeq(pParse, zType, nType);
1061 p->aCol[i].pColl = pColl;
1062
1063 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1064 ** then an index may have been created on this column before the
1065 ** collation type was added. Correct this if it is the case.
1066 */
1067 for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){
1068 assert( pIdx->nColumn==1 );
1069 if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl;
drhd3d39e92004-05-20 22:16:29 +00001070 }
1071}
1072
1073/*
drhda71ce12004-06-21 18:14:45 +00001074** Call sqlite3CheckCollSeq() for all collating sequences in an index,
1075** in order to verify that all the necessary collating sequences are
1076** loaded.
1077*/
danielk19777cedc8d2004-06-10 10:50:08 +00001078int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){
1079 if( pIdx ){
1080 int i;
1081 for(i=0; i<pIdx->nColumn; i++){
1082 if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){
1083 return SQLITE_ERROR;
1084 }
1085 }
1086 }
1087 return SQLITE_OK;
1088}
1089
danielk1977466be562004-06-10 02:16:01 +00001090/*
1091** This function returns the collation sequence for database native text
1092** encoding identified by the string zName, length nName.
1093**
1094** If the requested collation sequence is not available, or not available
1095** in the database native encoding, the collation factory is invoked to
1096** request it. If the collation factory does not supply such a sequence,
1097** and the sequence is available in another text encoding, then that is
1098** returned instead.
1099**
1100** If no versions of the requested collations sequence are available, or
1101** another error occurs, NULL is returned and an error message written into
1102** pParse.
1103*/
danielk19770202b292004-06-09 09:55:16 +00001104CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001105 sqlite3 *db = pParse->db;
1106 u8 enc = db->enc;
1107 u8 initbusy = db->init.busy;
1108
1109 CollSeq *pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001110 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001111 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1112 if( !pColl ){
1113 if( nName<0 ){
1114 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001115 }
danielk19774dade032005-05-25 10:45:10 +00001116 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1117 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001118 }
1119 }
1120
danielk19770202b292004-06-09 09:55:16 +00001121 return pColl;
1122}
1123
1124
drh8e2ca022002-06-17 17:07:19 +00001125/*
drh3f7d4e42004-07-24 14:35:58 +00001126** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001127**
1128** The schema cookie is used to determine when the schema for the
1129** database changes. After each schema change, the cookie value
1130** changes. When a process first reads the schema it records the
1131** cookie. Thereafter, whenever it goes to access the database,
1132** it checks the cookie to make sure the schema has not changed
1133** since it was last read.
1134**
1135** This plan is not completely bullet-proof. It is possible for
1136** the schema to change multiple times and for the cookie to be
1137** set back to prior value. But schema changes are infrequent
1138** and the probability of hitting the same cookie value is only
1139** 1 chance in 2^32. So we're safe enough.
1140*/
drh9bb575f2004-09-06 17:24:11 +00001141void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
drh3f7d4e42004-07-24 14:35:58 +00001142 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001143 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001144}
1145
1146/*
drh969fa7c2002-02-18 18:30:32 +00001147** Measure the number of characters needed to output the given
1148** identifier. The number returned includes any quotes used
1149** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001150**
1151** The estimate is conservative. It might be larger that what is
1152** really needed.
drh969fa7c2002-02-18 18:30:32 +00001153*/
1154static int identLength(const char *z){
1155 int n;
drh17f71932002-02-21 12:01:27 +00001156 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001157 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001158 }
drh234c39d2004-07-24 03:30:47 +00001159 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001160}
1161
1162/*
1163** Write an identifier onto the end of the given string. Add
1164** quote characters as needed.
1165*/
drh4c755c02004-08-08 20:22:17 +00001166static void identPut(char *z, int *pIdx, char *zSignedIdent){
1167 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001168 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001169 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001170 for(j=0; zIdent[j]; j++){
1171 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1172 }
1173 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001174 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001175 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001176 for(j=0; zIdent[j]; j++){
1177 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001178 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001179 }
drh234c39d2004-07-24 03:30:47 +00001180 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001181 z[i] = 0;
1182 *pIdx = i;
1183}
1184
1185/*
1186** Generate a CREATE TABLE statement appropriate for the given
1187** table. Memory to hold the text of the statement is obtained
1188** from sqliteMalloc() and must be freed by the calling function.
1189*/
1190static char *createTableStmt(Table *p){
1191 int i, k, n;
1192 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001193 char *zSep, *zSep2, *zEnd, *z;
1194 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001195 n = 0;
drh234c39d2004-07-24 03:30:47 +00001196 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1197 n += identLength(pCol->zName);
1198 z = pCol->zType;
1199 if( z ){
1200 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001201 }
drh969fa7c2002-02-18 18:30:32 +00001202 }
1203 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001204 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001205 zSep = "";
1206 zSep2 = ",";
1207 zEnd = ")";
1208 }else{
1209 zSep = "\n ";
1210 zSep2 = ",\n ";
1211 zEnd = "\n)";
1212 }
drhe0bc4042002-06-25 01:09:11 +00001213 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001214 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001215 if( zStmt==0 ) return 0;
danielk197753c0f742005-03-29 03:10:59 +00001216 strcpy(zStmt, !OMIT_TEMPDB&&p->iDb==1 ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001217 k = strlen(zStmt);
1218 identPut(zStmt, &k, p->zName);
1219 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001220 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001221 strcpy(&zStmt[k], zSep);
1222 k += strlen(&zStmt[k]);
1223 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001224 identPut(zStmt, &k, pCol->zName);
1225 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001226 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001227 strcpy(&zStmt[k], z);
1228 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001229 }
drh969fa7c2002-02-18 18:30:32 +00001230 }
1231 strcpy(&zStmt[k], zEnd);
1232 return zStmt;
1233}
1234
1235/*
drh75897232000-05-29 14:26:00 +00001236** This routine is called to report the final ")" that terminates
1237** a CREATE TABLE statement.
1238**
drhf57b3392001-10-08 13:22:32 +00001239** The table structure that other action routines have been building
1240** is added to the internal hash tables, assuming no errors have
1241** occurred.
drh75897232000-05-29 14:26:00 +00001242**
drh1d85d932004-02-14 23:05:52 +00001243** An entry for the table is made in the master table on disk, unless
1244** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001245** it means we are reading the sqlite_master table because we just
1246** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001247** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001248** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001249**
1250** If the pSelect argument is not NULL, it means that this routine
1251** was called to create a table generated from a
1252** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1253** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001254*/
danielk197719a8e7e2005-03-17 05:03:38 +00001255void sqlite3EndTable(
1256 Parse *pParse, /* Parse context */
1257 Token *pCons, /* The ',' token after the last column defn. */
1258 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1259 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1260){
drh75897232000-05-29 14:26:00 +00001261 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001262 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001263
danielk197724b03fd2004-05-10 10:34:34 +00001264 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
drh28037572000-08-02 13:47:41 +00001265 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001266 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001267
danielk1977517eb642004-06-07 10:00:31 +00001268 assert( !db->init.busy || !pSelect );
1269
drh1d85d932004-02-14 23:05:52 +00001270 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001271 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1272 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001273 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001274 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001275 */
drh1d85d932004-02-14 23:05:52 +00001276 if( db->init.busy ){
1277 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001278 }
1279
drhe3c41372001-09-17 20:25:58 +00001280 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001281 ** in the SQLITE_MASTER table of the database. The record number
1282 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001283 **
drhe0bc4042002-06-25 01:09:11 +00001284 ** If this is a TEMPORARY table, write the entry into the auxiliary
1285 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001286 */
drh1d85d932004-02-14 23:05:52 +00001287 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001288 int n;
drhd8bc7082000-06-07 23:51:50 +00001289 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001290 char *zType; /* "view" or "table" */
1291 char *zType2; /* "VIEW" or "TABLE" */
1292 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001293
danielk19774adee202004-05-08 08:23:19 +00001294 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001295 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001296
danielk1977e6efa742004-11-10 11:55:10 +00001297 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1298
drh4794f732004-11-05 17:17:50 +00001299 /* Create the rootpage for the new table and push it onto the stack.
1300 ** A view has no rootpage, so just push a zero onto the stack for
1301 ** views. Initialize zType at the same time.
1302 */
drh4ff6dfa2002-03-03 23:06:00 +00001303 if( p->pSelect==0 ){
1304 /* A regular table */
drh4794f732004-11-05 17:17:50 +00001305 zType = "table";
1306 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001307#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001308 }else{
1309 /* A view */
drh4794f732004-11-05 17:17:50 +00001310 zType = "view";
1311 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001312#endif
drh4ff6dfa2002-03-03 23:06:00 +00001313 }
danielk1977517eb642004-06-07 10:00:31 +00001314
danielk1977517eb642004-06-07 10:00:31 +00001315 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1316 ** statement to populate the new table. The root-page number for the
1317 ** new table is on the top of the vdbe stack.
1318 **
1319 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1320 ** suitable state to query for the column names and types to be used
1321 ** by the new table.
1322 */
1323 if( pSelect ){
1324 Table *pSelTab;
1325 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1326 sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
1327 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1328 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001329 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001330 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1331 if( pParse->nErr==0 ){
1332 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1333 if( pSelTab==0 ) return;
1334 assert( p->aCol==0 );
1335 p->nCol = pSelTab->nCol;
1336 p->aCol = pSelTab->aCol;
1337 pSelTab->nCol = 0;
1338 pSelTab->aCol = 0;
1339 sqlite3DeleteTable(0, pSelTab);
1340 }
1341 }
drh4794f732004-11-05 17:17:50 +00001342
drh4794f732004-11-05 17:17:50 +00001343 /* Compute the complete text of the CREATE statement */
1344 if( pSelect ){
1345 zStmt = createTableStmt(p);
1346 }else{
drh97903fe2005-05-24 20:19:57 +00001347 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001348 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1349 }
1350
1351 /* A slot for the record has already been allocated in the
1352 ** SQLITE_MASTER table. We just need to update that slot with all
1353 ** the information we've collected. The rowid for the preallocated
1354 ** slot is the 2nd item on the stack. The top of the stack is the
1355 ** root page for the new table (or a 0 if this is a view).
1356 */
1357 sqlite3NestedParse(pParse,
1358 "UPDATE %Q.%s "
1359 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1360 "WHERE rowid=#1",
1361 db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb),
1362 zType,
1363 p->zName,
1364 p->zName,
1365 zStmt
1366 );
1367 sqliteFree(zStmt);
drh2958a4e2004-11-12 03:56:15 +00001368 sqlite3ChangeCookie(db, v, p->iDb);
1369
1370#ifndef SQLITE_OMIT_AUTOINCREMENT
1371 /* Check to see if we need to create an sqlite_sequence table for
1372 ** keeping track of autoincrement keys.
1373 */
1374 if( p->autoInc ){
1375 Db *pDb = &db->aDb[p->iDb];
1376 if( pDb->pSeqTab==0 ){
1377 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001378 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1379 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001380 );
1381 }
1382 }
1383#endif
drh4794f732004-11-05 17:17:50 +00001384
1385 /* Reparse everything to update our internal data structures */
drh234c39d2004-07-24 03:30:47 +00001386 sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0,
1387 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001388 }
drh17e9e292003-02-01 13:53:28 +00001389
drh2958a4e2004-11-12 03:56:15 +00001390
drh17e9e292003-02-01 13:53:28 +00001391 /* Add the table to the in-memory representation of the database.
1392 */
drh234c39d2004-07-24 03:30:47 +00001393 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001394 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001395 FKey *pFKey;
1396 Db *pDb = &db->aDb[p->iDb];
1397 pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p);
drh17e9e292003-02-01 13:53:28 +00001398 if( pOld ){
1399 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1400 return;
1401 }
danielk1977576ec6b2005-01-21 11:55:25 +00001402#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001403 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1404 int nTo = strlen(pFKey->zTo) + 1;
drhbe5c89a2004-07-26 00:31:09 +00001405 pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo);
1406 sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001407 }
danielk1977576ec6b2005-01-21 11:55:25 +00001408#endif
drh17e9e292003-02-01 13:53:28 +00001409 pParse->pNewTable = 0;
1410 db->nTable++;
1411 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001412
1413#ifndef SQLITE_OMIT_ALTERTABLE
1414 if( !p->pSelect ){
1415 assert( !pSelect && pCons && pEnd );
1416 if( pCons->z==0 ) pCons = pEnd;
1417 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1418 }
1419#endif
drh17e9e292003-02-01 13:53:28 +00001420 }
drh75897232000-05-29 14:26:00 +00001421}
1422
drhb7f91642004-10-31 02:22:47 +00001423#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001424/*
drha76b5df2002-02-23 02:32:10 +00001425** The parser calls this routine in order to create a new VIEW
1426*/
danielk19774adee202004-05-08 08:23:19 +00001427void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001428 Parse *pParse, /* The parsing context */
1429 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001430 Token *pName1, /* The token that holds the name of the view */
1431 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001432 Select *pSelect, /* A SELECT statement that will become the new view */
1433 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001434){
drha76b5df2002-02-23 02:32:10 +00001435 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001436 int n;
drh4c755c02004-08-08 20:22:17 +00001437 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001438 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001439 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001440 Token *pName;
drha76b5df2002-02-23 02:32:10 +00001441
drh7c3d64f2005-06-06 15:32:08 +00001442 if( pParse->nVar>0 ){
1443 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1444 sqlite3SelectDelete(pSelect);
1445 return;
1446 }
danielk197748dec7e2004-05-28 12:33:30 +00001447 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
drha76b5df2002-02-23 02:32:10 +00001448 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001449 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001450 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001451 return;
1452 }
danielk1977ef2cb632004-05-29 02:37:19 +00001453 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk19774adee202004-05-08 08:23:19 +00001454 if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
1455 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001456 ){
danielk19774adee202004-05-08 08:23:19 +00001457 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001458 return;
1459 }
drh174b6192002-12-03 02:22:52 +00001460
drh4b59ab52002-08-24 18:24:51 +00001461 /* Make a copy of the entire SELECT statement that defines the view.
1462 ** This will force all the Expr.token.z values to be dynamically
1463 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001464 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001465 */
danielk19774adee202004-05-08 08:23:19 +00001466 p->pSelect = sqlite3SelectDup(pSelect);
1467 sqlite3SelectDelete(pSelect);
drh1d85d932004-02-14 23:05:52 +00001468 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001469 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001470 }
drh4b59ab52002-08-24 18:24:51 +00001471
1472 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1473 ** the end.
1474 */
drha76b5df2002-02-23 02:32:10 +00001475 sEnd = pParse->sLastToken;
1476 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1477 sEnd.z += sEnd.n;
1478 }
1479 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001480 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001481 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001482 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1483 sEnd.z = &z[n-1];
1484 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001485
danielk19774adee202004-05-08 08:23:19 +00001486 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001487 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001488 return;
drh417be792002-03-03 18:59:40 +00001489}
drhb7f91642004-10-31 02:22:47 +00001490#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001491
drhb7f91642004-10-31 02:22:47 +00001492#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001493/*
1494** The Table structure pTable is really a VIEW. Fill in the names of
1495** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001496** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001497*/
danielk19774adee202004-05-08 08:23:19 +00001498int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001499 Table *pSelTab; /* A fake table from which we get the result set */
1500 Select *pSel; /* Copy of the SELECT that implements the view */
1501 int nErr = 0; /* Number of errors encountered */
1502 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001503
1504 assert( pTable );
1505
1506 /* A positive nCol means the columns names for this view are
1507 ** already known.
1508 */
1509 if( pTable->nCol>0 ) return 0;
1510
1511 /* A negative nCol is a special marker meaning that we are currently
1512 ** trying to compute the column names. If we enter this routine with
1513 ** a negative nCol, it means two or more views form a loop, like this:
1514 **
1515 ** CREATE VIEW one AS SELECT * FROM two;
1516 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001517 **
1518 ** Actually, this error is caught previously and so the following test
1519 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001520 */
drh85c23c62005-08-20 03:03:04 +00001521#if 0
drh417be792002-03-03 18:59:40 +00001522 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001523 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001524 return 1;
1525 }
drh85c23c62005-08-20 03:03:04 +00001526#endif
1527 assert( pTable->nCol>=0 );
drh417be792002-03-03 18:59:40 +00001528
1529 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001530 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1531 ** "*" elements in the results set of the view and will assign cursors
1532 ** to the elements of the FROM clause. But we do not want these changes
1533 ** to be permanent. So the computation is done on a copy of the SELECT
1534 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001535 */
drh9b3187e2005-01-18 14:45:47 +00001536 assert( pTable->pSelect );
1537 pSel = sqlite3SelectDup(pTable->pSelect);
1538 n = pParse->nTab;
1539 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
drh417be792002-03-03 18:59:40 +00001540 pTable->nCol = -1;
danielk19774adee202004-05-08 08:23:19 +00001541 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
drh9b3187e2005-01-18 14:45:47 +00001542 pParse->nTab = n;
drh417be792002-03-03 18:59:40 +00001543 if( pSelTab ){
1544 assert( pTable->aCol==0 );
1545 pTable->nCol = pSelTab->nCol;
1546 pTable->aCol = pSelTab->aCol;
1547 pSelTab->nCol = 0;
1548 pSelTab->aCol = 0;
danielk19774adee202004-05-08 08:23:19 +00001549 sqlite3DeleteTable(0, pSelTab);
drh8bf8dc92003-05-17 17:35:10 +00001550 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
drh417be792002-03-03 18:59:40 +00001551 }else{
1552 pTable->nCol = 0;
1553 nErr++;
1554 }
drh9b3187e2005-01-18 14:45:47 +00001555 sqlite3SelectDelete(pSel);
drh417be792002-03-03 18:59:40 +00001556 return nErr;
1557}
drhb7f91642004-10-31 02:22:47 +00001558#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001559
drhb7f91642004-10-31 02:22:47 +00001560#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001561/*
drh8bf8dc92003-05-17 17:35:10 +00001562** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001563*/
drh9bb575f2004-09-06 17:24:11 +00001564static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001565 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001566 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
drhd24cc422003-03-27 12:51:24 +00001567 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001568 Table *pTab = sqliteHashData(i);
1569 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001570 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001571 }
1572 }
drh8bf8dc92003-05-17 17:35:10 +00001573 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001574}
drhb7f91642004-10-31 02:22:47 +00001575#else
1576# define sqliteViewResetAll(A,B)
1577#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001578
drh75897232000-05-29 14:26:00 +00001579/*
danielk1977a0bf2652004-11-04 14:30:04 +00001580** This function is called by the VDBE to adjust the internal schema
1581** used by SQLite when the btree layer moves a table root page. The
1582** root-page of a table or index in database iDb has changed from iFrom
1583** to iTo.
1584*/
1585#ifndef SQLITE_OMIT_AUTOVACUUM
1586void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1587 HashElem *pElem;
1588
1589 for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){
1590 Table *pTab = sqliteHashData(pElem);
1591 if( pTab->tnum==iFrom ){
1592 pTab->tnum = iTo;
1593 return;
1594 }
1595 }
1596 for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){
1597 Index *pIdx = sqliteHashData(pElem);
1598 if( pIdx->tnum==iFrom ){
1599 pIdx->tnum = iTo;
1600 return;
1601 }
1602 }
1603 assert(0);
1604}
1605#endif
1606
1607/*
1608** Write code to erase the table with root-page iTable from database iDb.
1609** Also write code to modify the sqlite_master table and internal schema
1610** if a root-page of another table is moved by the btree-layer whilst
1611** erasing iTable (this can happen with an auto-vacuum database).
1612*/
drh4e0cff62004-11-05 05:10:28 +00001613static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1614 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001615 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1616#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001617 /* OP_Destroy pushes an integer onto the stack. If this integer
1618 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001619 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001620 ** reflect this.
1621 **
1622 ** The "#0" in the SQL is a special constant that means whatever value
1623 ** is on the top of the stack. See sqlite3RegisterExpr().
1624 */
danielk197763e3e9f2004-11-05 09:19:27 +00001625 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001626 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001627 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001628#endif
1629}
1630
1631/*
1632** Write VDBE code to erase table pTab and all associated indices on disk.
1633** Code to update the sqlite_master tables and internal schema definitions
1634** in case a root-page belonging to another table is moved by the btree layer
1635** is also added (this can happen with an auto-vacuum database).
1636*/
drh4e0cff62004-11-05 05:10:28 +00001637static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001638#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001639 Index *pIdx;
drh4e0cff62004-11-05 05:10:28 +00001640 destroyRootPage(pParse, pTab->tnum, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001641 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh7a638582004-11-05 05:23:59 +00001642 destroyRootPage(pParse, pIdx->tnum, pIdx->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001643 }
1644#else
1645 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1646 ** is not defined), then it is important to call OP_Destroy on the
1647 ** table and index root-pages in order, starting with the numerically
1648 ** largest root-page number. This guarantees that none of the root-pages
1649 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1650 ** following were coded:
1651 **
1652 ** OP_Destroy 4 0
1653 ** ...
1654 ** OP_Destroy 5 0
1655 **
1656 ** and root page 5 happened to be the largest root-page number in the
1657 ** database, then root page 5 would be moved to page 4 by the
1658 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1659 ** a free-list page.
1660 */
1661 int iTab = pTab->tnum;
1662 int iDestroyed = 0;
1663
1664 while( 1 ){
1665 Index *pIdx;
1666 int iLargest = 0;
1667
1668 if( iDestroyed==0 || iTab<iDestroyed ){
1669 iLargest = iTab;
1670 }
1671 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1672 int iIdx = pIdx->tnum;
1673 assert( pIdx->iDb==pTab->iDb );
1674 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1675 iLargest = iIdx;
1676 }
1677 }
1678 if( iLargest==0 ) return;
drh4e0cff62004-11-05 05:10:28 +00001679 destroyRootPage(pParse, iLargest, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001680 iDestroyed = iLargest;
1681 }
1682#endif
1683}
1684
1685/*
drh75897232000-05-29 14:26:00 +00001686** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001687** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001688*/
danielk1977a8858102004-05-28 12:11:21 +00001689void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
1690 Table *pTab;
drh75897232000-05-29 14:26:00 +00001691 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001692 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001693 int iDb;
drh75897232000-05-29 14:26:00 +00001694
danielk1977a8858102004-05-28 12:11:21 +00001695 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
1696 assert( pName->nSrc==1 );
1697 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1698
1699 if( pTab==0 ) goto exit_drop_table;
1700 iDb = pTab->iDb;
drhe22a3342003-04-22 20:30:37 +00001701 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001702#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001703 {
1704 int code;
danielk1977a8858102004-05-28 12:11:21 +00001705 const char *zTab = SCHEMA_TABLE(pTab->iDb);
1706 const char *zDb = db->aDb[pTab->iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001707 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001708 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001709 }
drhe5f9c642003-01-13 23:27:31 +00001710 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001711 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001712 code = SQLITE_DROP_TEMP_VIEW;
1713 }else{
1714 code = SQLITE_DROP_VIEW;
1715 }
1716 }else{
danielk197753c0f742005-03-29 03:10:59 +00001717 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001718 code = SQLITE_DROP_TEMP_TABLE;
1719 }else{
1720 code = SQLITE_DROP_TABLE;
1721 }
1722 }
danielk1977a8858102004-05-28 12:11:21 +00001723 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1724 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001725 }
danielk1977a8858102004-05-28 12:11:21 +00001726 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1727 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001728 }
drhe5f9c642003-01-13 23:27:31 +00001729 }
1730#endif
drhf3388142004-11-13 03:48:06 +00001731 if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001732 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001733 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001734 }
danielk1977576ec6b2005-01-21 11:55:25 +00001735
1736#ifndef SQLITE_OMIT_VIEW
1737 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1738 ** on a table.
1739 */
danielk1977a8858102004-05-28 12:11:21 +00001740 if( isView && pTab->pSelect==0 ){
1741 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1742 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001743 }
danielk1977a8858102004-05-28 12:11:21 +00001744 if( !isView && pTab->pSelect ){
1745 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1746 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001747 }
danielk1977576ec6b2005-01-21 11:55:25 +00001748#endif
drh75897232000-05-29 14:26:00 +00001749
drh1ccde152000-06-17 13:12:39 +00001750 /* Generate code to remove the table from the master table
1751 ** on disk.
1752 */
danielk19774adee202004-05-08 08:23:19 +00001753 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001754 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001755 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001756 int iDb = pTab->iDb;
1757 Db *pDb = &db->aDb[iDb];
1758 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001759
danielk19778e227872004-06-07 07:52:17 +00001760 /* Drop all triggers associated with the table being dropped. Code
1761 ** is generated to remove entries from sqlite_master and/or
1762 ** sqlite_temp_master if required.
1763 */
danielk1977a8858102004-05-28 12:11:21 +00001764 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001765 while( pTrigger ){
drh2958a4e2004-11-12 03:56:15 +00001766 assert( pTrigger->iDb==iDb || pTrigger->iDb==1 );
danielk19774adee202004-05-08 08:23:19 +00001767 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001768 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001769 }
drh8bf8dc92003-05-17 17:35:10 +00001770
danielk19774d36b812004-11-19 07:07:30 +00001771#ifndef SQLITE_OMIT_AUTOINCREMENT
1772 /* Remove any entries of the sqlite_sequence table associated with
1773 ** the table being dropped. This is done before the table is dropped
1774 ** at the btree level, in case the sqlite_sequence table needs to
1775 ** move as a result of the drop (can happen in auto-vacuum mode).
1776 */
1777 if( pTab->autoInc ){
1778 sqlite3NestedParse(pParse,
1779 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1780 pDb->zName, pTab->zName
1781 );
1782 }
1783#endif
1784
danielk19778e227872004-06-07 07:52:17 +00001785 /* Drop all SQLITE_MASTER table and index entries that refer to the
1786 ** table. The program name loops through the master table and deletes
1787 ** every row that refers to a table of the same name as the one being
1788 ** dropped. Triggers are handled seperately because a trigger can be
1789 ** created in the temp database that refers to a table in another
1790 ** database.
1791 */
drhf1974842004-11-05 03:56:00 +00001792 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001793 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001794 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001795 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001796 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001797 }
drh2958a4e2004-11-12 03:56:15 +00001798
danielk1977a21c6b62005-01-24 10:25:59 +00001799 /* Remove the table entry from SQLite's internal schema and modify
1800 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001801 */
1802 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00001803 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00001804 }
drhd24cc422003-03-27 12:51:24 +00001805 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001806
1807exit_drop_table:
1808 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001809}
1810
1811/*
drhc2eef3b2002-08-31 18:53:06 +00001812** This routine is called to create a new foreign key on the table
1813** currently under construction. pFromCol determines which columns
1814** in the current table point to the foreign key. If pFromCol==0 then
1815** connect the key to the last column inserted. pTo is the name of
1816** the table referred to. pToCol is a list of tables in the other
1817** pTo table that the foreign key points to. flags contains all
1818** information about the conflict resolution algorithms specified
1819** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1820**
1821** An FKey structure is created and added to the table currently
1822** under construction in the pParse->pNewTable field. The new FKey
1823** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001824** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001825**
1826** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001827** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001828*/
danielk19774adee202004-05-08 08:23:19 +00001829void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001830 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001831 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001832 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001833 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001834 int flags /* Conflict resolution algorithms. */
1835){
drhb7f91642004-10-31 02:22:47 +00001836#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001837 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001838 Table *p = pParse->pNewTable;
1839 int nByte;
1840 int i;
1841 int nCol;
1842 char *z;
drhc2eef3b2002-08-31 18:53:06 +00001843
1844 assert( pTo!=0 );
1845 if( p==0 || pParse->nErr ) goto fk_end;
1846 if( pFromCol==0 ){
1847 int iCol = p->nCol-1;
1848 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00001849 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00001850 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00001851 " should reference only one column of table %T",
1852 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00001853 goto fk_end;
1854 }
1855 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00001856 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001857 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00001858 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00001859 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00001860 goto fk_end;
1861 }else{
danielk19770202b292004-06-09 09:55:16 +00001862 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00001863 }
1864 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1865 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00001866 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00001867 nByte += strlen(pToCol->a[i].zName) + 1;
1868 }
1869 }
1870 pFKey = sqliteMalloc( nByte );
1871 if( pFKey==0 ) goto fk_end;
1872 pFKey->pFrom = p;
1873 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00001874 z = (char*)&pFKey[1];
1875 pFKey->aCol = (struct sColMap*)z;
1876 z += sizeof(struct sColMap)*nCol;
1877 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00001878 memcpy(z, pTo->z, pTo->n);
1879 z[pTo->n] = 0;
1880 z += pTo->n+1;
1881 pFKey->pNextTo = 0;
1882 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00001883 if( pFromCol==0 ){
1884 pFKey->aCol[0].iFrom = p->nCol-1;
1885 }else{
1886 for(i=0; i<nCol; i++){
1887 int j;
1888 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00001889 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00001890 pFKey->aCol[i].iFrom = j;
1891 break;
1892 }
1893 }
1894 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00001895 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001896 "unknown column \"%s\" in foreign key definition",
1897 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00001898 goto fk_end;
1899 }
1900 }
1901 }
1902 if( pToCol ){
1903 for(i=0; i<nCol; i++){
1904 int n = strlen(pToCol->a[i].zName);
1905 pFKey->aCol[i].zCol = z;
1906 memcpy(z, pToCol->a[i].zName, n);
1907 z[n] = 0;
1908 z += n+1;
1909 }
1910 }
1911 pFKey->isDeferred = 0;
1912 pFKey->deleteConf = flags & 0xff;
1913 pFKey->updateConf = (flags >> 8 ) & 0xff;
1914 pFKey->insertConf = (flags >> 16 ) & 0xff;
1915
1916 /* Link the foreign key to the table as the last step.
1917 */
1918 p->pFKey = pFKey;
1919 pFKey = 0;
1920
1921fk_end:
1922 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00001923#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00001924 sqlite3ExprListDelete(pFromCol);
1925 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00001926}
1927
1928/*
1929** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1930** clause is seen as part of a foreign key definition. The isDeferred
1931** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1932** The behavior of the most recently created foreign key is adjusted
1933** accordingly.
1934*/
danielk19774adee202004-05-08 08:23:19 +00001935void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00001936#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00001937 Table *pTab;
1938 FKey *pFKey;
1939 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1940 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00001941#endif
drhc2eef3b2002-08-31 18:53:06 +00001942}
1943
1944/*
drh063336a2004-11-05 20:58:39 +00001945** Generate code that will erase and refill index *pIdx. This is
1946** used to initialize a newly created index or to recompute the
1947** content of an index in response to a REINDEX command.
1948**
1949** if memRootPage is not negative, it means that the index is newly
1950** created. The memory cell specified by memRootPage contains the
1951** root page number of the index. If memRootPage is negative, then
1952** the index already exists and must be cleared before being refilled and
1953** the root page number of the index is taken from pIndex->tnum.
1954*/
1955static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
1956 Table *pTab = pIndex->pTable; /* The table that is indexed */
1957 int iTab = pParse->nTab; /* Btree cursor used for pTab */
1958 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
1959 int addr1; /* Address of top of loop */
1960 int tnum; /* Root page of index */
1961 Vdbe *v; /* Generate code into this virtual machine */
1962
danielk19771d54df82004-11-23 15:41:16 +00001963#ifndef SQLITE_OMIT_AUTHORIZATION
1964 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
1965 pParse->db->aDb[pIndex->iDb].zName ) ){
1966 return;
1967 }
1968#endif
1969
danielk197733a5edc2005-01-27 00:22:02 +00001970 /* Ensure all the required collation sequences are available. This
1971 ** routine will invoke the collation-needed callback if necessary (and
1972 ** if one has been registered).
1973 */
1974 if( sqlite3CheckIndexCollSeq(pParse, pIndex) ){
1975 return;
1976 }
1977
drh063336a2004-11-05 20:58:39 +00001978 v = sqlite3GetVdbe(pParse);
1979 if( v==0 ) return;
1980 if( memRootPage>=0 ){
1981 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
1982 tnum = 0;
1983 }else{
1984 tnum = pIndex->tnum;
1985 sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb);
1986 }
1987 sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0);
1988 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum,
1989 (char*)&pIndex->keyInfo, P3_KEYINFO);
drh29dda4a2005-07-21 18:23:20 +00001990 sqlite3OpenTableForReading(v, iTab, pTab);
drh063336a2004-11-05 20:58:39 +00001991 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
1992 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00001993 if( pIndex->onError!=OE_None ){
1994 int curaddr = sqlite3VdbeCurrentAddr(v);
1995 int addr2 = curaddr+4;
1996 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
1997 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
1998 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
1999 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2000 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2001 "indexed columns are not unique", P3_STATIC);
2002 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002003 }
drh7f057c92005-06-24 03:53:06 +00002004 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002005 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
2006 sqlite3VdbeChangeP2(v, addr1, sqlite3VdbeCurrentAddr(v));
2007 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2008 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2009}
2010
2011/*
drh23bf66d2004-12-14 03:34:34 +00002012** Create a new index for an SQL table. pName1.pName2 is the name of the index
2013** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002014** be NULL for a primary key or an index that is created to satisfy a
2015** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002016** as the table to be indexed. pParse->pNewTable is a table that is
2017** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002018**
drh382c0242001-10-06 16:33:02 +00002019** pList is a list of columns to be indexed. pList will be NULL if this
2020** is a primary key or unique-constraint on the most recent column added
2021** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002022*/
danielk19774adee202004-05-08 08:23:19 +00002023void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002024 Parse *pParse, /* All information about this parse */
2025 Token *pName1, /* First part of index name. May be NULL */
2026 Token *pName2, /* Second part of index name. May be NULL */
2027 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002028 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002029 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2030 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
2031 Token *pEnd /* The ")" that closes the CREATE INDEX statement */
drh75897232000-05-29 14:26:00 +00002032){
drh23bf66d2004-12-14 03:34:34 +00002033 Table *pTab = 0; /* Table to be indexed */
danielk1977d8123362004-06-12 09:25:12 +00002034 Index *pIndex = 0; /* The index to be created */
drh75897232000-05-29 14:26:00 +00002035 char *zName = 0;
drhbeae3192001-09-22 18:12:08 +00002036 int i, j;
drhf26e09c2003-05-31 16:21:12 +00002037 Token nullId; /* Fake token for an empty ID list */
2038 DbFixer sFix; /* For assigning database names to pTable */
drh9bb575f2004-09-06 17:24:11 +00002039 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002040
danielk1977cbb18d22004-05-28 11:37:27 +00002041 int iDb; /* Index of the database that is being written */
2042 Token *pName = 0; /* Unqualified name of the index to create */
2043
danielk197724b03fd2004-05-10 10:34:34 +00002044 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
drhdaffd0e2001-04-11 14:28:42 +00002045
drh75897232000-05-29 14:26:00 +00002046 /*
2047 ** Find the table that is to be indexed. Return early if not found.
2048 */
danielk1977cbb18d22004-05-28 11:37:27 +00002049 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002050
2051 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002052 ** to search for the table. 'Fix' the table name to this db
2053 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002054 */
2055 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002056 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002057 if( iDb<0 ) goto exit_create_index;
2058
danielk197753c0f742005-03-29 03:10:59 +00002059#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002060 /* If the index name was unqualified, check if the the table
2061 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002062 */
danielk1977ef2cb632004-05-29 02:37:19 +00002063 pTab = sqlite3SrcListLookup(pParse, pTblName);
2064 if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){
2065 iDb = 1;
2066 }
danielk197753c0f742005-03-29 03:10:59 +00002067#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002068
2069 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2070 sqlite3FixSrcList(&sFix, pTblName)
2071 ){
drh85c23c62005-08-20 03:03:04 +00002072 /* Because the parser constructs pTblName from a single identifier,
2073 ** sqlite3FixSrcList can never fail. */
2074 assert(0);
danielk1977cbb18d22004-05-28 11:37:27 +00002075 }
danielk1977ef2cb632004-05-29 02:37:19 +00002076 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2077 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002078 if( !pTab ) goto exit_create_index;
danielk1977ef2cb632004-05-29 02:37:19 +00002079 assert( iDb==pTab->iDb );
drh75897232000-05-29 14:26:00 +00002080 }else{
drhe3c41372001-09-17 20:25:58 +00002081 assert( pName==0 );
drh75897232000-05-29 14:26:00 +00002082 pTab = pParse->pNewTable;
danielk1977cbb18d22004-05-28 11:37:27 +00002083 iDb = pTab->iDb;
drh75897232000-05-29 14:26:00 +00002084 }
danielk1977cbb18d22004-05-28 11:37:27 +00002085
drh75897232000-05-29 14:26:00 +00002086 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002087 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002088 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002089 goto exit_create_index;
2090 }
danielk1977576ec6b2005-01-21 11:55:25 +00002091#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002092 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002093 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002094 goto exit_create_index;
2095 }
danielk1977576ec6b2005-01-21 11:55:25 +00002096#endif
drh75897232000-05-29 14:26:00 +00002097
2098 /*
2099 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002100 ** index or table with the same name.
2101 **
2102 ** Exception: If we are reading the names of permanent indices from the
2103 ** sqlite_master table (because some other process changed the schema) and
2104 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002105 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002106 **
2107 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002108 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2109 ** own name.
drh75897232000-05-29 14:26:00 +00002110 */
danielk1977d8123362004-06-12 09:25:12 +00002111 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002112 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002113 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002114 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002115 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002116 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002117 }
danielk1977d8123362004-06-12 09:25:12 +00002118 if( !db->init.busy ){
2119 Index *pISameName; /* Another index with the same name */
2120 Table *pTSameName; /* A table with same name as the index */
danielk19778a414492004-06-29 08:59:35 +00002121 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002122 if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName))!=0 ){
2123 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2124 goto exit_create_index;
2125 }
2126 if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 ){
2127 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2128 goto exit_create_index;
2129 }
drhe3c41372001-09-17 20:25:58 +00002130 }
danielk1977a21c6b62005-01-24 10:25:59 +00002131 }else{
drhadbca9c2001-09-27 15:11:53 +00002132 char zBuf[30];
2133 int n;
2134 Index *pLoop;
2135 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002136 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002137 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002138 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002139 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002140 }
2141
drhe5f9c642003-01-13 23:27:31 +00002142 /* Check for authorization to create an index.
2143 */
2144#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002145 {
danielk197753c0f742005-03-29 03:10:59 +00002146 const char *zDb = db->aDb[iDb].zName;
2147 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002148 goto exit_create_index;
2149 }
2150 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002151 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002152 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002153 goto exit_create_index;
2154 }
drhe5f9c642003-01-13 23:27:31 +00002155 }
2156#endif
2157
drh75897232000-05-29 14:26:00 +00002158 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002159 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002160 ** So create a fake list to simulate this.
2161 */
2162 if( pList==0 ){
drh7020f652000-06-03 18:06:52 +00002163 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drh75897232000-05-29 14:26:00 +00002164 nullId.n = strlen(nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002165 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002166 if( pList==0 ) goto exit_create_index;
2167 }
2168
2169 /*
2170 ** Allocate the index structure.
2171 */
drh17a18f22005-07-23 14:52:12 +00002172 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) +
drh497e4462005-07-23 03:18:40 +00002173 (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr );
danielk1977e94ddc92005-03-21 03:53:38 +00002174 if( sqlite3_malloc_failed ) goto exit_create_index;
danielk19770202b292004-06-09 09:55:16 +00002175 pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
drh37108e12005-08-31 13:13:31 +00002176 pIndex->aiRowEst = (unsigned*)&pIndex->aiColumn[pList->nExpr];
drh17a18f22005-07-23 14:52:12 +00002177 pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1];
drh75897232000-05-29 14:26:00 +00002178 strcpy(pIndex->zName, zName);
2179 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002180 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002181 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002182 pIndex->autoIndex = pName==0;
danielk1977cbb18d22004-05-28 11:37:27 +00002183 pIndex->iDb = iDb;
drh75897232000-05-29 14:26:00 +00002184
drh1ccde152000-06-17 13:12:39 +00002185 /* Scan the names of the columns of the table to be indexed and
2186 ** load the column indices into the Index structure. Report an error
2187 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002188 */
danielk19770202b292004-06-09 09:55:16 +00002189 for(i=0; i<pList->nExpr; i++){
drh75897232000-05-29 14:26:00 +00002190 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002191 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002192 }
2193 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002194 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhf7a9e1a2004-02-22 18:40:56 +00002195 pTab->zName, pList->a[i].zName);
drh75897232000-05-29 14:26:00 +00002196 goto exit_create_index;
2197 }
drh967e8b72000-06-21 13:59:10 +00002198 pIndex->aiColumn[i] = j;
danielk19770202b292004-06-09 09:55:16 +00002199 if( pList->a[i].pExpr ){
2200 assert( pList->a[i].pExpr->pColl );
2201 pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
2202 }else{
2203 pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
2204 }
2205 assert( pIndex->keyInfo.aColl[i] );
danielk19777cedc8d2004-06-10 10:50:08 +00002206 if( !db->init.busy &&
2207 sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i])
2208 ){
2209 goto exit_create_index;
2210 }
drh75897232000-05-29 14:26:00 +00002211 }
danielk19770202b292004-06-09 09:55:16 +00002212 pIndex->keyInfo.nField = pList->nExpr;
drh51147ba2005-07-23 22:59:55 +00002213 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002214
danielk1977d8123362004-06-12 09:25:12 +00002215 if( pTab==pParse->pNewTable ){
2216 /* This routine has been called to create an automatic index as a
2217 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2218 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2219 ** i.e. one of:
2220 **
2221 ** CREATE TABLE t(x PRIMARY KEY, y);
2222 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2223 **
2224 ** Either way, check to see if the table already has such an index. If
2225 ** so, don't bother creating this one. This only applies to
2226 ** automatically created indices. Users can do as they wish with
2227 ** explicit indices.
2228 */
2229 Index *pIdx;
2230 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2231 int k;
2232 assert( pIdx->onError!=OE_None );
2233 assert( pIdx->autoIndex );
2234 assert( pIndex->onError!=OE_None );
2235
2236 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2237 for(k=0; k<pIdx->nColumn; k++){
2238 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2239 if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break;
2240 }
2241 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002242 if( pIdx->onError!=pIndex->onError ){
2243 /* This constraint creates the same index as a previous
2244 ** constraint specified somewhere in the CREATE TABLE statement.
2245 ** However the ON CONFLICT clauses are different. If both this
2246 ** constraint and the previous equivalent constraint have explicit
2247 ** ON CONFLICT clauses this is an error. Otherwise, use the
2248 ** explicitly specified behaviour for the index.
2249 */
2250 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2251 sqlite3ErrorMsg(pParse,
2252 "conflicting ON CONFLICT clauses specified", 0);
2253 }
2254 if( pIdx->onError==OE_Default ){
2255 pIdx->onError = pIndex->onError;
2256 }
2257 }
danielk1977d8123362004-06-12 09:25:12 +00002258 goto exit_create_index;
2259 }
2260 }
2261 }
2262
drh75897232000-05-29 14:26:00 +00002263 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002264 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002265 */
drh234c39d2004-07-24 03:30:47 +00002266 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002267 Index *p;
danielk19774adee202004-05-08 08:23:19 +00002268 p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash,
drh3c8bf552003-07-01 18:13:14 +00002269 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002270 if( p ){
2271 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002272 goto exit_create_index;
2273 }
drh5e00f6c2001-09-13 13:46:56 +00002274 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002275 if( pTblName!=0 ){
2276 pIndex->tnum = db->init.newTnum;
2277 }
drhd78eeee2001-09-13 16:18:53 +00002278 }
2279
drh1d85d932004-02-14 23:05:52 +00002280 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002281 ** involves writing the index into the master table and filling in the
2282 ** index with the current table contents.
2283 **
drh1d85d932004-02-14 23:05:52 +00002284 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2285 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002286 ** CREATE INDEX statements are read out of the master table. In
2287 ** the latter case the index already exists on disk, which is why
2288 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002289 **
danielk1977cbb18d22004-05-28 11:37:27 +00002290 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002291 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2292 ** has just been created, it contains no data and the index initialization
2293 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002294 */
drh1d85d932004-02-14 23:05:52 +00002295 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002296 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002297 char *zStmt;
2298 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002299
danielk19774adee202004-05-08 08:23:19 +00002300 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002301 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002302
2303 /* Create the rootpage for the index
2304 */
drhaee128d2005-02-14 20:48:18 +00002305 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002306 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002307 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2308
2309 /* Gather the complete text of the CREATE INDEX statement into
2310 ** the zStmt variable
2311 */
drhe0bc4042002-06-25 01:09:11 +00002312 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002313 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002314 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002315 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002316 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002317 pName->z);
2318 }else{
2319 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002320 /* zStmt = sqlite3MPrintf(""); */
2321 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002322 }
drh063336a2004-11-05 20:58:39 +00002323
2324 /* Add an entry in sqlite_master for this index
2325 */
2326 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002327 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002328 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2329 pIndex->zName,
2330 pTab->zName,
2331 zStmt
2332 );
2333 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2334 sqliteFree(zStmt);
2335
danielk1977a21c6b62005-01-24 10:25:59 +00002336 /* Fill the index with data and reparse the schema. Code an OP_Expire
2337 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002338 */
danielk1977cbb18d22004-05-28 11:37:27 +00002339 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002340 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002341 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002342 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2343 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002344 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002345 }
drh75897232000-05-29 14:26:00 +00002346 }
2347
danielk1977d8123362004-06-12 09:25:12 +00002348 /* When adding an index to the list of indices for a table, make
2349 ** sure all indices labeled OE_Replace come after all those labeled
2350 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2351 ** and INSERT.
2352 */
drh234c39d2004-07-24 03:30:47 +00002353 if( db->init.busy || pTblName==0 ){
2354 if( onError!=OE_Replace || pTab->pIndex==0
2355 || pTab->pIndex->onError==OE_Replace){
2356 pIndex->pNext = pTab->pIndex;
2357 pTab->pIndex = pIndex;
2358 }else{
2359 Index *pOther = pTab->pIndex;
2360 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2361 pOther = pOther->pNext;
2362 }
2363 pIndex->pNext = pOther->pNext;
2364 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002365 }
drh234c39d2004-07-24 03:30:47 +00002366 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002367 }
danielk1977d8123362004-06-12 09:25:12 +00002368
drh75897232000-05-29 14:26:00 +00002369 /* Clean up before exiting */
2370exit_create_index:
drh956bc922004-07-24 17:38:29 +00002371 if( pIndex ){
2372 freeIndex(pIndex);
2373 }
danielk19770202b292004-06-09 09:55:16 +00002374 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002375 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002376 sqliteFree(zName);
2377 return;
2378}
2379
2380/*
drh51147ba2005-07-23 22:59:55 +00002381** Fill the Index.aiRowEst[] array with default information - information
drh91124b32005-08-18 18:15:05 +00002382** to be used when we have not run the ANALYZE command.
drh28c4cf42005-07-27 20:41:43 +00002383**
2384** aiRowEst[0] is suppose to contain the number of elements in the index.
2385** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2386** number of rows in the table that match any particular value of the
2387** first column of the index. aiRowEst[2] is an estimate of the number
2388** of rows that match any particular combiniation of the first 2 columns
2389** of the index. And so forth. It must always be the case that
2390*
2391** aiRowEst[N]<=aiRowEst[N-1]
2392** aiRowEst[N]>=1
2393**
2394** Apart from that, we have little to go on besides intuition as to
2395** how aiRowEst[] should be initialized. The numbers generated here
2396** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002397*/
2398void sqlite3DefaultRowEst(Index *pIdx){
drh37108e12005-08-31 13:13:31 +00002399 unsigned *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002400 int i;
drh28c4cf42005-07-27 20:41:43 +00002401 assert( a!=0 );
2402 a[0] = 1000000;
drh3adc9ce2005-07-28 16:51:51 +00002403 for(i=pIdx->nColumn; i>=1; i--){
2404 a[i] = 10;
drh28c4cf42005-07-27 20:41:43 +00002405 }
2406 if( pIdx->onError!=OE_None ){
2407 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002408 }
2409}
2410
2411/*
drh74e24cd2002-01-09 03:19:59 +00002412** This routine will drop an existing named index. This routine
2413** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002414*/
danielk19774adee202004-05-08 08:23:19 +00002415void sqlite3DropIndex(Parse *pParse, SrcList *pName){
drh75897232000-05-29 14:26:00 +00002416 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002417 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002418 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002419
danielk1977d5d56522005-03-16 12:15:20 +00002420 if( pParse->nErr || sqlite3_malloc_failed ){
2421 goto exit_drop_index;
2422 }
drhd24cc422003-03-27 12:51:24 +00002423 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002424 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2425 goto exit_drop_index;
2426 }
danielk19774adee202004-05-08 08:23:19 +00002427 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002428 if( pIndex==0 ){
danielk19774adee202004-05-08 08:23:19 +00002429 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
drha6ecd332004-06-10 00:29:09 +00002430 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002431 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002432 }
drh485b39b2002-07-13 03:11:52 +00002433 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002434 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002435 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002436 goto exit_drop_index;
2437 }
drhe5f9c642003-01-13 23:27:31 +00002438#ifndef SQLITE_OMIT_AUTHORIZATION
2439 {
2440 int code = SQLITE_DROP_INDEX;
2441 Table *pTab = pIndex->pTable;
drhe22a3342003-04-22 20:30:37 +00002442 const char *zDb = db->aDb[pIndex->iDb].zName;
2443 const char *zTab = SCHEMA_TABLE(pIndex->iDb);
danielk19774adee202004-05-08 08:23:19 +00002444 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002445 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002446 }
danielk197753c0f742005-03-29 03:10:59 +00002447 if( !OMIT_TEMPDB && pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002448 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002449 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002450 }
drhed6c8672003-01-12 18:02:16 +00002451 }
drhe5f9c642003-01-13 23:27:31 +00002452#endif
drh75897232000-05-29 14:26:00 +00002453
2454 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002455 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002456 if( v ){
drhb17131a2004-11-05 22:18:49 +00002457 int iDb = pIndex->iDb;
2458 sqlite3NestedParse(pParse,
2459 "DELETE FROM %Q.%s WHERE name=%Q",
2460 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2461 pIndex->zName
2462 );
2463 sqlite3ChangeCookie(db, v, iDb);
2464 destroyRootPage(pParse, pIndex->tnum, iDb);
2465 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002466 }
2467
drhd24cc422003-03-27 12:51:24 +00002468exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002469 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002470}
2471
2472/*
drh13449892005-09-07 21:22:45 +00002473** ppArray points into a structure where there is an array pointer
2474** followed by two integers. The first integer is the
2475** number of elements in the structure array. The second integer
2476** is the number of allocated slots in the array.
2477**
2478** In other words, the structure looks something like this:
2479**
2480** struct Example1 {
2481** struct subElem *aEntry;
2482** int nEntry;
2483** int nAlloc;
2484** }
2485**
2486** The pnEntry parameter points to the equivalent of Example1.nEntry.
2487**
2488** This routine allocates a new slot in the array, zeros it out,
2489** and returns its index. If malloc fails a negative number is returned.
2490**
2491** szEntry is the sizeof of a single array entry. initSize is the
2492** number of array entries allocated on the initial allocation.
2493*/
2494int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
2495 char *p;
2496 int *an = (int*)&ppArray[1];
2497 if( an[0]>=an[1] ){
2498 void *pNew;
drh5360ad32005-09-08 00:13:27 +00002499 int newSize;
2500 newSize = an[1]*2 + initSize;
2501 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
drh13449892005-09-07 21:22:45 +00002502 if( pNew==0 ){
2503 return -1;
2504 }
drh5360ad32005-09-08 00:13:27 +00002505 an[1] = newSize;
drh13449892005-09-07 21:22:45 +00002506 *ppArray = pNew;
2507 }
2508 p = *ppArray;
2509 memset(&p[an[0]*szEntry], 0, szEntry);
2510 return an[0]++;
2511}
2512
2513/*
drh75897232000-05-29 14:26:00 +00002514** Append a new element to the given IdList. Create a new IdList if
2515** need be.
drhdaffd0e2001-04-11 14:28:42 +00002516**
2517** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002518*/
danielk19774adee202004-05-08 08:23:19 +00002519IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh13449892005-09-07 21:22:45 +00002520 int i;
drh75897232000-05-29 14:26:00 +00002521 if( pList==0 ){
2522 pList = sqliteMalloc( sizeof(IdList) );
2523 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002524 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002525 }
drh13449892005-09-07 21:22:45 +00002526 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
2527 if( i<0 ){
2528 sqlite3IdListDelete(pList);
2529 return 0;
drh75897232000-05-29 14:26:00 +00002530 }
drh13449892005-09-07 21:22:45 +00002531 pList->a[i].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002532 return pList;
2533}
2534
2535/*
drhfe05af82005-07-21 03:14:59 +00002536** Delete an IdList.
2537*/
2538void sqlite3IdListDelete(IdList *pList){
2539 int i;
2540 if( pList==0 ) return;
2541 for(i=0; i<pList->nId; i++){
2542 sqliteFree(pList->a[i].zName);
2543 }
2544 sqliteFree(pList->a);
2545 sqliteFree(pList);
2546}
2547
2548/*
2549** Return the index in pList of the identifier named zId. Return -1
2550** if not found.
2551*/
2552int sqlite3IdListIndex(IdList *pList, const char *zName){
2553 int i;
2554 if( pList==0 ) return -1;
2555 for(i=0; i<pList->nId; i++){
2556 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2557 }
2558 return -1;
2559}
2560
2561/*
drhad3cab52002-05-24 02:04:32 +00002562** Append a new table name to the given SrcList. Create a new SrcList if
2563** need be. A new entry is created in the SrcList even if pToken is NULL.
2564**
2565** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002566**
2567** If pDatabase is not null, it means that the table has an optional
2568** database name prefix. Like this: "database.table". The pDatabase
2569** points to the table name and the pTable points to the database name.
2570** The SrcList.a[].zName field is filled with the table name which might
2571** come from pTable (if pDatabase is NULL) or from pDatabase.
2572** SrcList.a[].zDatabase is filled with the database name from pTable,
2573** or with NULL if no database is specified.
2574**
2575** In other words, if call like this:
2576**
danielk19774adee202004-05-08 08:23:19 +00002577** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002578**
2579** Then B is a table name and the database name is unspecified. If called
2580** like this:
2581**
danielk19774adee202004-05-08 08:23:19 +00002582** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002583**
2584** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002585*/
danielk19774adee202004-05-08 08:23:19 +00002586SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002587 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002588 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002589 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002590 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002591 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002592 }
drh4305d102003-07-30 12:34:12 +00002593 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002594 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002595 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002596 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002597 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002598 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002599 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002600 return 0;
2601 }
drh113088e2003-03-20 01:16:58 +00002602 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002603 }
drha99db3b2004-06-19 14:49:12 +00002604 pItem = &pList->a[pList->nSrc];
2605 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002606 if( pDatabase && pDatabase->z==0 ){
2607 pDatabase = 0;
2608 }
2609 if( pDatabase && pTable ){
2610 Token *pTemp = pDatabase;
2611 pDatabase = pTable;
2612 pTable = pTemp;
2613 }
drha99db3b2004-06-19 14:49:12 +00002614 pItem->zName = sqlite3NameFromToken(pTable);
2615 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2616 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002617 pList->nSrc++;
2618 return pList;
2619}
2620
2621/*
drh63eb5f22003-04-29 16:20:44 +00002622** Assign cursors to all tables in a SrcList
2623*/
danielk19774adee202004-05-08 08:23:19 +00002624void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002625 int i;
drh9b3187e2005-01-18 14:45:47 +00002626 struct SrcList_item *pItem;
2627 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2628 if( pItem->iCursor>=0 ) break;
2629 pItem->iCursor = pParse->nTab++;
2630 if( pItem->pSelect ){
2631 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
drh63eb5f22003-04-29 16:20:44 +00002632 }
2633 }
2634}
2635
2636/*
drh75897232000-05-29 14:26:00 +00002637** Add an alias to the last identifier on the given identifier list.
2638*/
danielk19774adee202004-05-08 08:23:19 +00002639void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002640 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002641 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002642 }
2643}
2644
2645/*
drhad3cab52002-05-24 02:04:32 +00002646** Delete an entire SrcList including all its substructure.
2647*/
danielk19774adee202004-05-08 08:23:19 +00002648void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002649 int i;
drhbe5c89a2004-07-26 00:31:09 +00002650 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002651 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002652 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2653 sqliteFree(pItem->zDatabase);
2654 sqliteFree(pItem->zName);
2655 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002656 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002657 sqlite3SelectDelete(pItem->pSelect);
2658 sqlite3ExprDelete(pItem->pOn);
2659 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002660 }
drh75897232000-05-29 14:26:00 +00002661 sqliteFree(pList);
2662}
2663
drh982cef72000-05-30 16:27:03 +00002664/*
drhc4a3c772001-04-04 11:48:57 +00002665** Begin a transaction
2666*/
drh684917c2004-10-05 02:41:42 +00002667void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002668 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002669 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002670 int i;
drh5e00f6c2001-09-13 13:46:56 +00002671
drh001bbcb2003-03-19 03:14:00 +00002672 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002673 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002674 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002675
2676 v = sqlite3GetVdbe(pParse);
2677 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002678 if( type!=TK_DEFERRED ){
2679 for(i=0; i<db->nDb; i++){
2680 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2681 }
2682 }
danielk19771d850a72004-05-31 08:26:49 +00002683 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002684}
2685
2686/*
2687** Commit a transaction
2688*/
danielk19774adee202004-05-08 08:23:19 +00002689void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002690 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002691 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002692
drh001bbcb2003-03-19 03:14:00 +00002693 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002694 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002695 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002696
2697 v = sqlite3GetVdbe(pParse);
2698 if( v ){
2699 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002700 }
drhc4a3c772001-04-04 11:48:57 +00002701}
2702
2703/*
2704** Rollback a transaction
2705*/
danielk19774adee202004-05-08 08:23:19 +00002706void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002707 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002708 Vdbe *v;
2709
drh001bbcb2003-03-19 03:14:00 +00002710 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002711 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002712 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002713
danielk19774adee202004-05-08 08:23:19 +00002714 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002715 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002716 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002717 }
drhc4a3c772001-04-04 11:48:57 +00002718}
drhf57b14a2001-09-14 18:54:08 +00002719
2720/*
drhdc3ff9c2004-08-18 02:10:15 +00002721** Make sure the TEMP database is open and available for use. Return
2722** the number of errors. Leave any error messages in the pParse structure.
2723*/
2724static int sqlite3OpenTempDatabase(Parse *pParse){
2725 sqlite3 *db = pParse->db;
2726 if( db->aDb[1].pBt==0 && !pParse->explain ){
2727 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2728 if( rc!=SQLITE_OK ){
2729 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2730 "file for storing temporary tables");
2731 pParse->rc = rc;
2732 return 1;
2733 }
2734 if( db->flags & !db->autoCommit ){
2735 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2736 if( rc!=SQLITE_OK ){
2737 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2738 "the temporary database file");
2739 pParse->rc = rc;
2740 return 1;
2741 }
2742 }
2743 }
2744 return 0;
2745}
2746
2747/*
drh80242052004-06-09 00:48:12 +00002748** Generate VDBE code that will verify the schema cookie and start
2749** a read-transaction for all named database files.
2750**
2751** It is important that all schema cookies be verified and all
2752** read transactions be started before anything else happens in
2753** the VDBE program. But this routine can be called after much other
2754** code has been generated. So here is what we do:
2755**
drhc275b4e2004-07-19 17:25:24 +00002756** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002757** will jump to a subroutine at the end of the program. Then we
2758** record every database that needs its schema verified in the
2759** pParse->cookieMask field. Later, after all other code has been
2760** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002761** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002762** will be made to point to that subroutine. The generation of the
2763** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002764**
2765** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2766** schema on any databases. This can be used to position the OP_Goto
2767** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00002768*/
danielk19774adee202004-05-08 08:23:19 +00002769void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00002770 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00002771 Vdbe *v;
2772 int mask;
2773
2774 v = sqlite3GetVdbe(pParse);
2775 if( v==0 ) return; /* This only happens if there was a prior error */
2776 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00002777 if( pParse->cookieGoto==0 ){
2778 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00002779 }
drhc275b4e2004-07-19 17:25:24 +00002780 if( iDb>=0 ){
2781 assert( iDb<db->nDb );
2782 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
2783 assert( iDb<32 );
2784 mask = 1<<iDb;
2785 if( (pParse->cookieMask & mask)==0 ){
2786 pParse->cookieMask |= mask;
2787 pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00002788 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00002789 sqlite3OpenTempDatabase(pParse);
2790 }
drhc275b4e2004-07-19 17:25:24 +00002791 }
drh001bbcb2003-03-19 03:14:00 +00002792 }
drh001bbcb2003-03-19 03:14:00 +00002793}
2794
2795/*
drh1c928532002-01-31 15:54:21 +00002796** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00002797** might change the database.
2798**
2799** This routine starts a new transaction if we are not already within
2800** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00002801** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00002802** be set for operations that might fail (due to a constraint) part of
2803** the way through and which will need to undo some writes without having to
2804** rollback the whole transaction. For operations where all constraints
2805** can be checked before any changes are made to the database, it is never
2806** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00002807**
drh8bf8dc92003-05-17 17:35:10 +00002808** Only database iDb and the temp database are made writable by this call.
2809** If iDb==0, then the main and temp databases are made writable. If
2810** iDb==1 then only the temp database is made writable. If iDb>1 then the
2811** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00002812*/
drh7f0f12e2004-05-21 13:39:50 +00002813void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00002814 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00002815 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00002816 sqlite3CodeVerifySchema(pParse, iDb);
2817 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00002818 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00002819 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00002820 }
danielk197753c0f742005-03-29 03:10:59 +00002821 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00002822 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00002823 }
2824}
2825
drh4343fea2004-11-05 23:46:15 +00002826/*
2827** Check to see if pIndex uses the collating sequence pColl. Return
2828** true if it does and false if it does not.
2829*/
2830#ifndef SQLITE_OMIT_REINDEX
2831static int collationMatch(CollSeq *pColl, Index *pIndex){
2832 int n = pIndex->keyInfo.nField;
2833 CollSeq **pp = pIndex->keyInfo.aColl;
2834 while( n-- ){
2835 if( *pp==pColl ) return 1;
2836 pp++;
2837 }
2838 return 0;
2839}
2840#endif
2841
2842/*
2843** Recompute all indices of pTab that use the collating sequence pColl.
2844** If pColl==0 then recompute all indices of pTab.
2845*/
2846#ifndef SQLITE_OMIT_REINDEX
drh9abc9c62005-08-14 01:34:19 +00002847static void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){
drh4343fea2004-11-05 23:46:15 +00002848 Index *pIndex; /* An index associated with pTab */
2849
2850 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
2851 if( pColl==0 || collationMatch(pColl,pIndex) ){
2852 sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
2853 sqlite3RefillIndex(pParse, pIndex, -1);
2854 }
2855 }
2856}
2857#endif
2858
2859/*
2860** Recompute all indices of all tables in all databases where the
2861** indices use the collating sequence pColl. If pColl==0 then recompute
2862** all indices everywhere.
2863*/
2864#ifndef SQLITE_OMIT_REINDEX
drh9abc9c62005-08-14 01:34:19 +00002865static void reindexDatabases(Parse *pParse, CollSeq *pColl){
drh4343fea2004-11-05 23:46:15 +00002866 Db *pDb; /* A single database */
2867 int iDb; /* The database index number */
2868 sqlite3 *db = pParse->db; /* The database connection */
2869 HashElem *k; /* For looping over tables in pDb */
2870 Table *pTab; /* A table in the database */
2871
2872 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
2873 if( pDb==0 ) continue;
drhff2d5ea2005-07-23 00:41:48 +00002874 for(k=sqliteHashFirst(&pDb->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00002875 pTab = (Table*)sqliteHashData(k);
2876 reindexTable(pParse, pTab, pColl);
2877 }
2878 }
2879}
2880#endif
2881
2882/*
drheee46cf2004-11-06 00:02:48 +00002883** Generate code for the REINDEX command.
2884**
2885** REINDEX -- 1
2886** REINDEX <collation> -- 2
2887** REINDEX ?<database>.?<tablename> -- 3
2888** REINDEX ?<database>.?<indexname> -- 4
2889**
2890** Form 1 causes all indices in all attached databases to be rebuilt.
2891** Form 2 rebuilds all indices in all databases that use the named
2892** collating function. Forms 3 and 4 rebuild the named index or all
2893** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00002894*/
2895#ifndef SQLITE_OMIT_REINDEX
2896void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
2897 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
2898 char *z; /* Name of a table or index */
2899 const char *zDb; /* Name of the database */
2900 Table *pTab; /* A table in the database */
2901 Index *pIndex; /* An index associated with pTab */
2902 int iDb; /* The database index number */
2903 sqlite3 *db = pParse->db; /* The database connection */
2904 Token *pObjName; /* Name of the table or index to be reindexed */
2905
danielk197733a5edc2005-01-27 00:22:02 +00002906 /* Read the database schema. If an error occurs, leave an error message
2907 ** and code in pParse and return NULL. */
2908 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00002909 return;
danielk197733a5edc2005-01-27 00:22:02 +00002910 }
2911
drhe497f002004-11-07 13:01:49 +00002912 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002913 reindexDatabases(pParse, 0);
2914 return;
drhe497f002004-11-07 13:01:49 +00002915 }else if( pName2==0 || pName2->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002916 pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0);
2917 if( pColl ){
2918 reindexDatabases(pParse, pColl);
2919 return;
2920 }
2921 }
2922 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
2923 if( iDb<0 ) return;
2924 z = sqlite3NameFromToken(pObjName);
2925 zDb = db->aDb[iDb].zName;
2926 pTab = sqlite3FindTable(db, z, zDb);
2927 if( pTab ){
2928 reindexTable(pParse, pTab, 0);
2929 sqliteFree(z);
2930 return;
2931 }
2932 pIndex = sqlite3FindIndex(db, z, zDb);
2933 sqliteFree(z);
2934 if( pIndex ){
2935 sqlite3BeginWriteOperation(pParse, 0, iDb);
2936 sqlite3RefillIndex(pParse, pIndex, -1);
2937 return;
2938 }
2939 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
2940}
2941#endif