blob: 10d21655ca85a80a601f19026bee689d95f67483 [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**
drh28c4cf42005-07-27 20:41:43 +000025** $Id: build.c,v 1.337 2005/07/27 20:41:44 drh Exp $
drh75897232000-05-29 14:26:00 +000026*/
27#include "sqliteInt.h"
drhf57b14a2001-09-14 18:54:08 +000028#include <ctype.h>
drh75897232000-05-29 14:26:00 +000029
30/*
drhe0bc4042002-06-25 01:09:11 +000031** This routine is called when a new SQL statement is beginning to
drh23bf66d2004-12-14 03:34:34 +000032** be parsed. Initialize the pParse structure as needed.
drhe0bc4042002-06-25 01:09:11 +000033*/
danielk19774adee202004-05-08 08:23:19 +000034void sqlite3BeginParse(Parse *pParse, int explainFlag){
drhe0bc4042002-06-25 01:09:11 +000035 pParse->explain = explainFlag;
drh7c972de2003-09-06 22:18:07 +000036 pParse->nVar = 0;
drhe0bc4042002-06-25 01:09:11 +000037}
38
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
drh71c697e2004-08-08 23:39:19 +000088 /* Add a No-op that contains the complete text of the compiled SQL
89 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +000090 ** of the program.
91 **
drh23bf66d2004-12-14 03:34:34 +000092 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +000093 */
94 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh71c697e2004-08-08 23:39:19 +000095 }
96
drh3f7d4e42004-07-24 14:35:58 +000097
drh80242052004-06-09 00:48:12 +000098 /* Get the VDBE program ready for execution
99 */
drhb86ccfb2003-01-28 23:13:10 +0000100 if( v && pParse->nErr==0 ){
101 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +0000102 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +0000103 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
danielk1977b3bce662005-01-29 08:32:43 +0000104 pParse->nTab+3, pParse->nMaxDepth+1, pParse->explain);
danielk1977441daf62005-02-01 03:46:43 +0000105 pParse->rc = SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000106 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000107 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000108 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000109 }
drha226d052002-09-25 19:04:07 +0000110 pParse->nTab = 0;
111 pParse->nMem = 0;
112 pParse->nSet = 0;
drh7c972de2003-09-06 22:18:07 +0000113 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000114 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000115 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000116}
117
118/*
drh205f48e2004-11-05 00:43:11 +0000119** Run the parser and code generator recursively in order to generate
120** code for the SQL statement given onto the end of the pParse context
121** currently under construction. When the parser is run recursively
122** this way, the final OP_Halt is not appended and other initialization
123** and finalization steps are omitted because those are handling by the
124** outermost parser.
125**
126** Not everything is nestable. This facility is designed to permit
127** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000128** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000129*/
130void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
131 va_list ap;
132 char *zSql;
133 int rc;
drhf1974842004-11-05 03:56:00 +0000134# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
135 char saveBuf[SAVE_SZ];
136
drh205f48e2004-11-05 00:43:11 +0000137 if( pParse->nErr ) return;
138 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
139 va_start(ap, zFormat);
140 zSql = sqlite3VMPrintf(zFormat, ap);
141 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000142 if( zSql==0 ){
143 return; /* A malloc must have failed */
144 }
drh205f48e2004-11-05 00:43:11 +0000145 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000146 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
147 memset(&pParse->nVar, 0, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000148 rc = sqlite3RunParser(pParse, zSql, 0);
149 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000150 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000151 pParse->nested--;
152}
153
154/*
danielk19778a414492004-06-29 08:59:35 +0000155** Locate the in-memory structure that describes a particular database
156** table given the name of that table and (optionally) the name of the
157** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000158**
danielk19778a414492004-06-29 08:59:35 +0000159** If zDatabase is 0, all databases are searched for the table and the
160** first matching table is returned. (No checking for duplicate table
161** names is done.) The search order is TEMP first, then MAIN, then any
162** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000163**
danielk19774adee202004-05-08 08:23:19 +0000164** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000165*/
drh9bb575f2004-09-06 17:24:11 +0000166Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000167 Table *p = 0;
168 int i;
drh645f63e2004-06-22 13:22:40 +0000169 assert( zName!=0 );
danielk19778a414492004-06-29 08:59:35 +0000170 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
danielk197753c0f742005-03-29 03:10:59 +0000171 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000172 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000173 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
174 p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000175 if( p ) break;
176 }
drh74e24cd2002-01-09 03:19:59 +0000177 return p;
drh75897232000-05-29 14:26:00 +0000178}
179
180/*
danielk19778a414492004-06-29 08:59:35 +0000181** Locate the in-memory structure that describes a particular database
182** table given the name of that table and (optionally) the name of the
183** database containing the table. Return NULL if not found. Also leave an
184** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000185**
danielk19778a414492004-06-29 08:59:35 +0000186** The difference between this routine and sqlite3FindTable() is that this
187** routine leaves an error message in pParse->zErrMsg where
188** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000189*/
danielk19774adee202004-05-08 08:23:19 +0000190Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000191 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000192
danielk19778a414492004-06-29 08:59:35 +0000193 /* Read the database schema. If an error occurs, leave an error message
194 ** and code in pParse and return NULL. */
195 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
196 return 0;
197 }
198
danielk19774adee202004-05-08 08:23:19 +0000199 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000200 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000201 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000202 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
203 }else if( sqlite3FindTable(pParse->db, zName, 0)!=0 ){
204 sqlite3ErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
drhf26e09c2003-05-31 16:21:12 +0000205 zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000206 }else{
danielk19774adee202004-05-08 08:23:19 +0000207 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000208 }
drha6ecd332004-06-10 00:29:09 +0000209 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000210 }
211 return p;
212}
213
214/*
215** Locate the in-memory structure that describes
216** a particular index given the name of that index
217** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000218** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000219**
220** If zDatabase is 0, all databases are searched for the
221** table and the first matching index is returned. (No checking
222** for duplicate index names is done.) The search order is
223** TEMP first, then MAIN, then any auxiliary databases added
224** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000225*/
drh9bb575f2004-09-06 17:24:11 +0000226Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000227 Index *p = 0;
228 int i;
danielk19778a414492004-06-29 08:59:35 +0000229 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
danielk197753c0f742005-03-29 03:10:59 +0000230 for(i=OMIT_TEMPDB; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000231 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000232 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
233 p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000234 if( p ) break;
235 }
drh74e24cd2002-01-09 03:19:59 +0000236 return p;
drh75897232000-05-29 14:26:00 +0000237}
238
239/*
drh956bc922004-07-24 17:38:29 +0000240** Reclaim the memory used by an index
241*/
242static void freeIndex(Index *p){
243 sqliteFree(p->zColAff);
244 sqliteFree(p);
245}
246
247/*
drh75897232000-05-29 14:26:00 +0000248** Remove the given index from the index hash table, and free
249** its memory structures.
250**
drhd229ca92002-01-09 13:30:41 +0000251** The index is removed from the database hash tables but
252** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000253** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000254*/
drh9bb575f2004-09-06 17:24:11 +0000255static void sqliteDeleteIndex(sqlite3 *db, Index *p){
drhd229ca92002-01-09 13:30:41 +0000256 Index *pOld;
drhd24cc422003-03-27 12:51:24 +0000257
drhd229ca92002-01-09 13:30:41 +0000258 assert( db!=0 && p->zName!=0 );
danielk19774adee202004-05-08 08:23:19 +0000259 pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
drhd24cc422003-03-27 12:51:24 +0000260 strlen(p->zName)+1, 0);
drhd229ca92002-01-09 13:30:41 +0000261 if( pOld!=0 && pOld!=p ){
danielk19774adee202004-05-08 08:23:19 +0000262 sqlite3HashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
drhd24cc422003-03-27 12:51:24 +0000263 strlen(pOld->zName)+1, pOld);
drh75897232000-05-29 14:26:00 +0000264 }
drh956bc922004-07-24 17:38:29 +0000265 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000266}
267
268/*
drhc96d8532005-05-03 12:30:33 +0000269** For the index called zIdxName which is found in the database iDb,
270** unlike that index from its Table then remove the index from
271** the index hash table and free all memory structures associated
272** with the index.
drh5e00f6c2001-09-13 13:46:56 +0000273*/
drh9bb575f2004-09-06 17:24:11 +0000274void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000275 Index *pIndex;
276 int len;
277
278 len = strlen(zIdxName);
279 pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0);
280 if( pIndex ){
281 if( pIndex->pTable->pIndex==pIndex ){
282 pIndex->pTable->pIndex = pIndex->pNext;
283 }else{
284 Index *p;
285 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
286 if( p && p->pNext==pIndex ){
287 p->pNext = pIndex->pNext;
288 }
drh5e00f6c2001-09-13 13:46:56 +0000289 }
drh956bc922004-07-24 17:38:29 +0000290 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000291 }
drh956bc922004-07-24 17:38:29 +0000292 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000293}
294
295/*
drhe0bc4042002-06-25 01:09:11 +0000296** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000297** a single database. This routine is called to reclaim memory
298** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000299** if there were schema changes during the transaction or if a
300** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000301**
302** If iDb<=0 then reset the internal schema tables for all database
303** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000304** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000305*/
drh9bb575f2004-09-06 17:24:11 +0000306void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drhe0bc4042002-06-25 01:09:11 +0000307 HashElem *pElem;
308 Hash temp1;
309 Hash temp2;
drh1c2d8412003-03-31 00:30:47 +0000310 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000311
drh1c2d8412003-03-31 00:30:47 +0000312 assert( iDb>=0 && iDb<db->nDb );
313 db->flags &= ~SQLITE_Initialized;
314 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000315 Db *pDb = &db->aDb[i];
316 temp1 = pDb->tblHash;
317 temp2 = pDb->trigHash;
danielk19774adee202004-05-08 08:23:19 +0000318 sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
319 sqlite3HashClear(&pDb->aFKey);
320 sqlite3HashClear(&pDb->idxHash);
drhd24cc422003-03-27 12:51:24 +0000321 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
drh40e016e2004-11-04 14:47:11 +0000322 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
drhd24cc422003-03-27 12:51:24 +0000323 }
danielk19774adee202004-05-08 08:23:19 +0000324 sqlite3HashClear(&temp2);
325 sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
drhd24cc422003-03-27 12:51:24 +0000326 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
327 Table *pTab = sqliteHashData(pElem);
danielk19774adee202004-05-08 08:23:19 +0000328 sqlite3DeleteTable(db, pTab);
drhd24cc422003-03-27 12:51:24 +0000329 }
danielk19774adee202004-05-08 08:23:19 +0000330 sqlite3HashClear(&temp1);
drh2958a4e2004-11-12 03:56:15 +0000331 pDb->pSeqTab = 0;
drh8bf8dc92003-05-17 17:35:10 +0000332 DbClearProperty(db, i, DB_SchemaLoaded);
drh1c2d8412003-03-31 00:30:47 +0000333 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000334 }
drh1c2d8412003-03-31 00:30:47 +0000335 assert( iDb==0 );
336 db->flags &= ~SQLITE_InternChanges;
337
338 /* If one or more of the auxiliary database files has been closed,
339 ** then remove then from the auxiliary database list. We take the
340 ** opportunity to do this here since we have just deleted all of the
341 ** schema hash tables and therefore do not have to make any changes
342 ** to any of those tables.
343 */
drh4d189ca2004-02-12 18:46:38 +0000344 for(i=0; i<db->nDb; i++){
345 struct Db *pDb = &db->aDb[i];
346 if( pDb->pBt==0 ){
347 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
348 pDb->pAux = 0;
349 }
350 }
drh1c2d8412003-03-31 00:30:47 +0000351 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000352 struct Db *pDb = &db->aDb[i];
353 if( pDb->pBt==0 ){
354 sqliteFree(pDb->zName);
355 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000356 continue;
357 }
358 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000359 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000360 }
drh8bf8dc92003-05-17 17:35:10 +0000361 j++;
drh1c2d8412003-03-31 00:30:47 +0000362 }
363 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
364 db->nDb = j;
365 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
366 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
367 sqliteFree(db->aDb);
368 db->aDb = db->aDbStatic;
369 }
drhe0bc4042002-06-25 01:09:11 +0000370}
371
372/*
373** This routine is called whenever a rollback occurs. If there were
374** schema changes during the transaction, then we have to reset the
375** internal hash tables and reload them from disk.
376*/
drh9bb575f2004-09-06 17:24:11 +0000377void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000378 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000379 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000380 }
381}
382
383/*
384** This routine is called when a commit occurs.
385*/
drh9bb575f2004-09-06 17:24:11 +0000386void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000387 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000388}
389
390/*
drh956bc922004-07-24 17:38:29 +0000391** Clear the column names from a table or view.
392*/
393static void sqliteResetColumnNames(Table *pTable){
394 int i;
395 Column *pCol;
396 assert( pTable!=0 );
drhdd5b2fa2005-03-28 03:39:55 +0000397 if( (pCol = pTable->aCol)!=0 ){
398 for(i=0; i<pTable->nCol; i++, pCol++){
399 sqliteFree(pCol->zName);
400 sqlite3ExprDelete(pCol->pDflt);
401 sqliteFree(pCol->zType);
402 }
403 sqliteFree(pTable->aCol);
drh956bc922004-07-24 17:38:29 +0000404 }
drh956bc922004-07-24 17:38:29 +0000405 pTable->aCol = 0;
406 pTable->nCol = 0;
407}
408
409/*
drh75897232000-05-29 14:26:00 +0000410** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000411** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000412**
413** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000414** the table data structure from the hash table. Nor does it remove
415** foreign keys from the sqlite.aFKey hash table. But it does destroy
416** memory structures of the indices and foreign keys associated with
417** the table.
drhdaffd0e2001-04-11 14:28:42 +0000418**
419** Indices associated with the table are unlinked from the "db"
420** data structure if db!=NULL. If db==NULL, indices attached to
421** the table are deleted, but it is assumed they have already been
422** unlinked.
drh75897232000-05-29 14:26:00 +0000423*/
drh9bb575f2004-09-06 17:24:11 +0000424void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000425 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000426 FKey *pFKey, *pNextFKey;
427
drh75897232000-05-29 14:26:00 +0000428 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000429
drhed8a3bb2005-06-06 21:19:56 +0000430 /* Do not delete the table until the reference count reaches zero. */
431 pTable->nRef--;
432 if( pTable->nRef>0 ){
433 return;
434 }
435 assert( pTable->nRef==0 );
436
drhc2eef3b2002-08-31 18:53:06 +0000437 /* Delete all indices associated with this table
438 */
439 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
440 pNext = pIndex->pNext;
drhd24cc422003-03-27 12:51:24 +0000441 assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
drhc2eef3b2002-08-31 18:53:06 +0000442 sqliteDeleteIndex(db, pIndex);
443 }
444
danielk1977576ec6b2005-01-21 11:55:25 +0000445#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +0000446 /* Delete all foreign keys associated with this table. The keys
447 ** should have already been unlinked from the db->aFKey hash table
448 */
449 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
450 pNextFKey = pFKey->pNextFrom;
drhd24cc422003-03-27 12:51:24 +0000451 assert( pTable->iDb<db->nDb );
danielk19774adee202004-05-08 08:23:19 +0000452 assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
drhd24cc422003-03-27 12:51:24 +0000453 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000454 sqliteFree(pFKey);
455 }
danielk1977576ec6b2005-01-21 11:55:25 +0000456#endif
drhc2eef3b2002-08-31 18:53:06 +0000457
458 /* Delete the Table structure itself.
459 */
drh956bc922004-07-24 17:38:29 +0000460 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000461 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000462 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000463 sqlite3SelectDelete(pTable->pSelect);
drh75897232000-05-29 14:26:00 +0000464 sqliteFree(pTable);
465}
466
467/*
drh5edc3122001-09-13 21:53:09 +0000468** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000469** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000470*/
drh9bb575f2004-09-06 17:24:11 +0000471void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000472 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000473 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000474 Db *pDb;
475
drhd229ca92002-01-09 13:30:41 +0000476 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000477 assert( iDb>=0 && iDb<db->nDb );
478 assert( zTabName && zTabName[0] );
479 pDb = &db->aDb[iDb];
480 p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0);
481 if( p ){
danielk1977576ec6b2005-01-21 11:55:25 +0000482#ifndef SQLITE_OMIT_FOREIGN_KEY
drh956bc922004-07-24 17:38:29 +0000483 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
484 int nTo = strlen(pF1->zTo) + 1;
485 pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo);
486 if( pF2==pF1 ){
487 sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo);
488 }else{
489 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
490 if( pF2 ){
491 pF2->pNextTo = pF1->pNextTo;
492 }
drhc2eef3b2002-08-31 18:53:06 +0000493 }
494 }
danielk1977576ec6b2005-01-21 11:55:25 +0000495#endif
drh956bc922004-07-24 17:38:29 +0000496 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000497 }
drh956bc922004-07-24 17:38:29 +0000498 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000499}
500
501/*
drha99db3b2004-06-19 14:49:12 +0000502** Given a token, return a string that consists of the text of that
503** token with any quotations removed. Space to hold the returned string
504** is obtained from sqliteMalloc() and must be freed by the calling
505** function.
drh75897232000-05-29 14:26:00 +0000506**
drhc96d8532005-05-03 12:30:33 +0000507** Tokens are often just pointers into the original SQL text and so
drha99db3b2004-06-19 14:49:12 +0000508** are not \000 terminated and are not persistent. The returned string
509** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000510*/
drha99db3b2004-06-19 14:49:12 +0000511char *sqlite3NameFromToken(Token *pName){
512 char *zName;
513 if( pName ){
514 zName = sqliteStrNDup(pName->z, pName->n);
515 sqlite3Dequote(zName);
516 }else{
517 zName = 0;
518 }
drh75897232000-05-29 14:26:00 +0000519 return zName;
520}
521
522/*
danielk1977cbb18d22004-05-28 11:37:27 +0000523** Open the sqlite_master table stored in database number iDb for
524** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000525*/
danielk1977cbb18d22004-05-28 11:37:27 +0000526void sqlite3OpenMasterTable(Vdbe *v, int iDb){
527 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000528 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000529 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000530}
531
532/*
danielk1977cbb18d22004-05-28 11:37:27 +0000533** The token *pName contains the name of a database (either "main" or
534** "temp" or the name of an attached db). This routine returns the
535** index of the named database in db->aDb[], or -1 if the named db
536** does not exist.
537*/
drhff2d5ea2005-07-23 00:41:48 +0000538int sqlite3FindDb(sqlite3 *db, Token *pName){
danielk1977576ec6b2005-01-21 11:55:25 +0000539 int i = -1; /* Database number */
drh73c42a12004-11-20 18:13:10 +0000540 int n; /* Number of characters in the name */
541 Db *pDb; /* A database whose name space is being searched */
542 char *zName; /* Name we are searching for */
543
544 zName = sqlite3NameFromToken(pName);
545 if( zName ){
546 n = strlen(zName);
danielk1977576ec6b2005-01-21 11:55:25 +0000547 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
danielk197753c0f742005-03-29 03:10:59 +0000548 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
549 0==sqlite3StrICmp(pDb->zName, zName) ){
danielk1977576ec6b2005-01-21 11:55:25 +0000550 break;
drh73c42a12004-11-20 18:13:10 +0000551 }
danielk1977cbb18d22004-05-28 11:37:27 +0000552 }
drh73c42a12004-11-20 18:13:10 +0000553 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000554 }
danielk1977576ec6b2005-01-21 11:55:25 +0000555 return i;
danielk1977cbb18d22004-05-28 11:37:27 +0000556}
557
drh0e3d7472004-06-19 17:33:07 +0000558/* The table or view or trigger name is passed to this routine via tokens
559** pName1 and pName2. If the table name was fully qualified, for example:
560**
561** CREATE TABLE xxx.yyy (...);
562**
563** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
564** the table name is not fully qualified, i.e.:
565**
566** CREATE TABLE yyy(...);
567**
568** Then pName1 is set to "yyy" and pName2 is "".
569**
570** This routine sets the *ppUnqual pointer to point at the token (pName1 or
571** pName2) that stores the unqualified table name. The index of the
572** database "xxx" is returned.
573*/
danielk1977ef2cb632004-05-29 02:37:19 +0000574int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000575 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000576 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000577 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
578 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000579){
drh0e3d7472004-06-19 17:33:07 +0000580 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000581 sqlite3 *db = pParse->db;
582
583 if( pName2 && pName2->n>0 ){
584 assert( !db->init.busy );
585 *pUnqual = pName2;
drhff2d5ea2005-07-23 00:41:48 +0000586 iDb = sqlite3FindDb(db, pName1);
danielk1977cbb18d22004-05-28 11:37:27 +0000587 if( iDb<0 ){
588 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
589 pParse->nErr++;
590 return -1;
591 }
592 }else{
593 assert( db->init.iDb==0 || db->init.busy );
594 iDb = db->init.iDb;
595 *pUnqual = pName1;
596 }
597 return iDb;
598}
599
600/*
danielk1977d8123362004-06-12 09:25:12 +0000601** This routine is used to check if the UTF-8 string zName is a legal
602** unqualified name for a new schema object (table, index, view or
603** trigger). All names are legal except those that begin with the string
604** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
605** is reserved for internal use.
606*/
607int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000608 if( !pParse->db->init.busy && pParse->nested==0
danielk19773a3f38e2005-05-22 06:49:56 +0000609 && (pParse->db->flags & SQLITE_WriteSchema)==0
drhf1974842004-11-05 03:56:00 +0000610 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000611 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
612 return SQLITE_ERROR;
613 }
614 return SQLITE_OK;
615}
616
617/*
drh75897232000-05-29 14:26:00 +0000618** Begin constructing a new table representation in memory. This is
619** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000620** to a CREATE TABLE statement. In particular, this routine is called
621** after seeing tokens "CREATE" and "TABLE" and the table name. The
drhf57b3392001-10-08 13:22:32 +0000622** pStart token is the CREATE and pName is the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000623** flag is true if the table should be stored in the auxiliary database
624** file instead of in the main database file. This is normally the case
625** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000626** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000627**
drhf57b3392001-10-08 13:22:32 +0000628** The new table record is initialized and put in pParse->pNewTable.
629** As more of the CREATE TABLE statement is parsed, additional action
630** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000631** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000632** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000633*/
danielk19774adee202004-05-08 08:23:19 +0000634void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000635 Parse *pParse, /* Parser context */
636 Token *pStart, /* The "CREATE" token */
danielk1977cbb18d22004-05-28 11:37:27 +0000637 Token *pName1, /* First part of the name of the table or view */
638 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000639 int isTemp, /* True if this is a TEMP table */
640 int isView /* True if this is a VIEW */
641){
drh75897232000-05-29 14:26:00 +0000642 Table *pTable;
drhf57b3392001-10-08 13:22:32 +0000643 Index *pIdx;
drh23bf66d2004-12-14 03:34:34 +0000644 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000645 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000646 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000647 int iDb; /* Database number to create the table in */
648 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000649
danielk1977cbb18d22004-05-28 11:37:27 +0000650 /* The table or view name to create is passed to this routine via tokens
651 ** pName1 and pName2. If the table name was fully qualified, for example:
652 **
653 ** CREATE TABLE xxx.yyy (...);
654 **
655 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
656 ** the table name is not fully qualified, i.e.:
657 **
658 ** CREATE TABLE yyy(...);
659 **
660 ** Then pName1 is set to "yyy" and pName2 is "".
661 **
662 ** The call below sets the pName pointer to point at the token (pName1 or
663 ** pName2) that stores the unqualified table name. The variable iDb is
664 ** set to the index of the database that the table or view is to be
665 ** created in.
666 */
danielk1977ef2cb632004-05-29 02:37:19 +0000667 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000668 if( iDb<0 ) return;
danielk197753c0f742005-03-29 03:10:59 +0000669 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000670 /* If creating a temp table, the name may not be qualified */
671 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000672 return;
673 }
danielk197753c0f742005-03-29 03:10:59 +0000674 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
danielk1977cbb18d22004-05-28 11:37:27 +0000675
676 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000677 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000678 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000679 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000680 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000681 }
drh1d85d932004-02-14 23:05:52 +0000682 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000683#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000684 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000685 {
686 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000687 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000688 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000689 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000690 }
drhe5f9c642003-01-13 23:27:31 +0000691 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +0000692 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000693 code = SQLITE_CREATE_TEMP_VIEW;
694 }else{
695 code = SQLITE_CREATE_VIEW;
696 }
697 }else{
danielk197753c0f742005-03-29 03:10:59 +0000698 if( !OMIT_TEMPDB && isTemp ){
drhe5f9c642003-01-13 23:27:31 +0000699 code = SQLITE_CREATE_TEMP_TABLE;
700 }else{
701 code = SQLITE_CREATE_TABLE;
702 }
703 }
danielk19774adee202004-05-08 08:23:19 +0000704 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000705 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000706 }
707 }
708#endif
drhf57b3392001-10-08 13:22:32 +0000709
drhf57b3392001-10-08 13:22:32 +0000710 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000711 ** index or table name in the same database. Issue an error message if
712 ** it does.
drhf57b3392001-10-08 13:22:32 +0000713 */
danielk19775558a8a2005-01-17 07:53:44 +0000714 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
715 goto begin_table_error;
716 }
danielk19773df6b252004-05-29 10:23:19 +0000717 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
718 if( pTable ){
danielk19774adee202004-05-08 08:23:19 +0000719 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
drh23bf66d2004-12-14 03:34:34 +0000720 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000721 }
danielk19778a414492004-06-29 08:59:35 +0000722 if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 &&
723 ( iDb==0 || !db->init.busy) ){
danielk19774adee202004-05-08 08:23:19 +0000724 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
drh23bf66d2004-12-14 03:34:34 +0000725 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000726 }
727 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000728 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000729 pParse->rc = SQLITE_NOMEM;
730 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000731 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000732 }
drh75897232000-05-29 14:26:00 +0000733 pTable->zName = zName;
drh75897232000-05-29 14:26:00 +0000734 pTable->nCol = 0;
drh7020f652000-06-03 18:06:52 +0000735 pTable->aCol = 0;
drh4a324312001-12-21 14:30:42 +0000736 pTable->iPKey = -1;
drh75897232000-05-29 14:26:00 +0000737 pTable->pIndex = 0;
drh1c2d8412003-03-31 00:30:47 +0000738 pTable->iDb = iDb;
drhed8a3bb2005-06-06 21:19:56 +0000739 pTable->nRef = 1;
danielk19774adee202004-05-08 08:23:19 +0000740 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000741 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000742
drh4794f732004-11-05 17:17:50 +0000743 /* If this is the magic sqlite_sequence table used by autoincrement,
744 ** then record a pointer to this table in the main database structure
745 ** so that INSERT can find the table easily.
746 */
747#ifndef SQLITE_OMIT_AUTOINCREMENT
drh78776ec2005-06-14 02:12:46 +0000748 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
drh4794f732004-11-05 17:17:50 +0000749 db->aDb[iDb].pSeqTab = pTable;
750 }
751#endif
752
drh17f71932002-02-21 12:01:27 +0000753 /* Begin generating the code that will insert the table record into
754 ** the SQLITE_MASTER table. Note in particular that we must go ahead
755 ** and allocate the record number for the table entry now. Before any
756 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
757 ** indices to be created and the table record must come before the
758 ** indices. Hence, the record number for the table must be allocated
759 ** now.
760 */
danielk19774adee202004-05-08 08:23:19 +0000761 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk197736963fd2005-02-19 08:18:05 +0000762 int lbl;
danielk1977cbb18d22004-05-28 11:37:27 +0000763 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000764
danielk197736963fd2005-02-19 08:18:05 +0000765 /* If the file format and encoding in the database have not been set,
766 ** set them now.
danielk1977d008cfe2004-06-19 02:22:10 +0000767 */
danielk197736963fd2005-02-19 08:18:05 +0000768 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
769 lbl = sqlite3VdbeMakeLabel(v);
770 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000771 sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
772 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
773 sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
774 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
danielk197736963fd2005-02-19 08:18:05 +0000775 sqlite3VdbeResolveLabel(v, lbl);
danielk1977d008cfe2004-06-19 02:22:10 +0000776
drh4794f732004-11-05 17:17:50 +0000777 /* This just creates a place-holder record in the sqlite_master table.
778 ** The record created does not contain anything yet. It will be replaced
779 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000780 **
781 ** The rowid for the new entry is left on the top of the stack.
782 ** The rowid value is needed by the code that sqlite3EndTable will
783 ** generate.
drh4794f732004-11-05 17:17:50 +0000784 */
danielk1977a21c6b62005-01-24 10:25:59 +0000785#ifndef SQLITE_OMIT_VIEW
786 if( isView ){
787 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
788 }else
789#endif
790 {
791 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
792 }
danielk1977cbb18d22004-05-28 11:37:27 +0000793 sqlite3OpenMasterTable(v, iDb);
drhf0863fe2005-06-12 21:35:51 +0000794 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000795 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhf0863fe2005-06-12 21:35:51 +0000796 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
797 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000798 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
danielk1977a21c6b62005-01-24 10:25:59 +0000799 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drh5e00f6c2001-09-13 13:46:56 +0000800 }
drh23bf66d2004-12-14 03:34:34 +0000801
802 /* Normal (non-error) return. */
803 return;
804
805 /* If an error occurs, we jump here */
806begin_table_error:
807 sqliteFree(zName);
808 return;
drh75897232000-05-29 14:26:00 +0000809}
810
811/*
danielk1977c60e9b82005-01-31 12:42:29 +0000812** This macro is used to compare two strings in a case-insensitive manner.
813** It is slightly faster than calling sqlite3StrICmp() directly, but
814** produces larger code.
815**
816** WARNING: This macro is not compatible with the strcmp() family. It
817** returns true if the two strings are equal, otherwise false.
818*/
819#define STRICMP(x, y) (\
820sqlite3UpperToLower[*(unsigned char *)(x)]== \
821sqlite3UpperToLower[*(unsigned char *)(y)] \
822&& sqlite3StrICmp((x)+1,(y)+1)==0 )
823
824/*
drh75897232000-05-29 14:26:00 +0000825** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000826**
827** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000828** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000829** first to get things going. Then this routine is called for each
830** column.
drh75897232000-05-29 14:26:00 +0000831*/
danielk19774adee202004-05-08 08:23:19 +0000832void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000833 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000834 int i;
drha99db3b2004-06-19 14:49:12 +0000835 char *z;
drhc9b84a12002-06-20 11:36:48 +0000836 Column *pCol;
drh75897232000-05-29 14:26:00 +0000837 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000838 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000839 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000840 for(i=0; i<p->nCol; i++){
danielk1977c60e9b82005-01-31 12:42:29 +0000841 if( STRICMP(z, p->aCol[i].zName) ){
danielk19774adee202004-05-08 08:23:19 +0000842 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000843 sqliteFree(z);
844 return;
845 }
846 }
drh75897232000-05-29 14:26:00 +0000847 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000848 Column *aNew;
849 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000850 if( aNew==0 ){
851 sqliteFree(z);
852 return;
853 }
drh6d4abfb2001-10-22 02:58:08 +0000854 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000855 }
drhc9b84a12002-06-20 11:36:48 +0000856 pCol = &p->aCol[p->nCol];
857 memset(pCol, 0, sizeof(p->aCol[0]));
858 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000859
860 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000861 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
862 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000863 */
danielk19774f057f92004-06-08 00:02:33 +0000864 pCol->affinity = SQLITE_AFF_NONE;
drhd3d39e92004-05-20 22:16:29 +0000865 pCol->pColl = pParse->db->pDfltColl;
drhc9b84a12002-06-20 11:36:48 +0000866 p->nCol++;
drh75897232000-05-29 14:26:00 +0000867}
868
869/*
drh382c0242001-10-06 16:33:02 +0000870** This routine is called by the parser while in the middle of
871** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
872** been seen on a column. This routine sets the notNull flag on
873** the column currently under construction.
874*/
danielk19774adee202004-05-08 08:23:19 +0000875void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000876 Table *p;
877 int i;
878 if( (p = pParse->pNewTable)==0 ) return;
879 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000880 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000881}
882
883/*
danielk197752a83fb2005-01-31 12:56:44 +0000884** Scan the column type name zType (length nType) and return the
885** associated affinity type.
danielk1977b3dff962005-02-01 01:21:55 +0000886**
887** This routine does a case-independent search of zType for the
888** substrings in the following table. If one of the substrings is
889** found, the corresponding affinity is returned. If zType contains
890** more than one of the substrings, entries toward the top of
891** the table take priority. For example, if zType is 'BLOBINT',
892** SQLITE_AFF_INTEGER is returned.
893**
894** Substring | Affinity
895** --------------------------------
896** 'INT' | SQLITE_AFF_INTEGER
897** 'CHAR' | SQLITE_AFF_TEXT
898** 'CLOB' | SQLITE_AFF_TEXT
899** 'TEXT' | SQLITE_AFF_TEXT
900** 'BLOB' | SQLITE_AFF_NONE
901**
902** If none of the substrings in the above table are found,
903** SQLITE_AFF_NUMERIC is returned.
danielk197752a83fb2005-01-31 12:56:44 +0000904*/
drh487e2622005-06-25 18:42:14 +0000905char sqlite3AffinityType(const Token *pType){
danielk1977b3dff962005-02-01 01:21:55 +0000906 u32 h = 0;
907 char aff = SQLITE_AFF_NUMERIC;
drh487e2622005-06-25 18:42:14 +0000908 const unsigned char *zIn = pType->z;
909 const unsigned char *zEnd = &pType->z[pType->n];
danielk197752a83fb2005-01-31 12:56:44 +0000910
danielk1977b3dff962005-02-01 01:21:55 +0000911 while( zIn!=zEnd ){
912 h = (h<<8) + sqlite3UpperToLower[*zIn];
913 zIn++;
danielk1977201f7162005-02-01 02:13:29 +0000914 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
915 aff = SQLITE_AFF_TEXT;
916 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
917 aff = SQLITE_AFF_TEXT;
918 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
919 aff = SQLITE_AFF_TEXT;
920 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
921 && aff==SQLITE_AFF_NUMERIC ){
danielk1977b3dff962005-02-01 01:21:55 +0000922 aff = SQLITE_AFF_NONE;
danielk1977201f7162005-02-01 02:13:29 +0000923 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
danielk1977b3dff962005-02-01 01:21:55 +0000924 aff = SQLITE_AFF_INTEGER;
925 break;
danielk197752a83fb2005-01-31 12:56:44 +0000926 }
927 }
danielk1977b3dff962005-02-01 01:21:55 +0000928
929 return aff;
danielk197752a83fb2005-01-31 12:56:44 +0000930}
931
932/*
drh382c0242001-10-06 16:33:02 +0000933** This routine is called by the parser while in the middle of
934** parsing a CREATE TABLE statement. The pFirst token is the first
935** token in the sequence of tokens that describe the type of the
936** column currently under construction. pLast is the last token
937** in the sequence. Use this information to construct a string
938** that contains the typename of the column and store that string
939** in zType.
940*/
drh487e2622005-06-25 18:42:14 +0000941void sqlite3AddColumnType(Parse *pParse, Token *pType){
drh382c0242001-10-06 16:33:02 +0000942 Table *p;
drh487e2622005-06-25 18:42:14 +0000943 int i;
drhc9b84a12002-06-20 11:36:48 +0000944 Column *pCol;
drh487e2622005-06-25 18:42:14 +0000945
drh382c0242001-10-06 16:33:02 +0000946 if( (p = pParse->pNewTable)==0 ) return;
947 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +0000948 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +0000949 pCol = &p->aCol[i];
drhae29ffb2004-09-25 14:39:18 +0000950 assert( pCol->zType==0 );
drh487e2622005-06-25 18:42:14 +0000951#if 0
danielk1977c60e9b82005-01-31 12:42:29 +0000952 z = pCol->zType = sqliteMallocRaw(n+1);
drhf57b3392001-10-08 13:22:32 +0000953 if( z==0 ) return;
danielk1977c60e9b82005-01-31 12:42:29 +0000954 for(i=j=0; i<n; i++){
955 int c = zIn[i];
drh382c0242001-10-06 16:33:02 +0000956 if( isspace(c) ) continue;
957 z[j++] = c;
958 }
959 z[j] = 0;
drh487e2622005-06-25 18:42:14 +0000960#endif
961 pCol->zType = sqlite3NameFromToken(pType);
962 pCol->affinity = sqlite3AffinityType(pType);
drh382c0242001-10-06 16:33:02 +0000963}
964
965/*
danielk19777977a172004-11-09 12:44:37 +0000966** The expression is the default value for the most recently added column
967** of the table currently under construction.
968**
969** Default value expressions must be constant. Raise an exception if this
970** is not the case.
drhd9b02572001-04-15 00:37:09 +0000971**
972** This routine is called by the parser while in the middle of
973** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +0000974*/
danielk19777977a172004-11-09 12:44:37 +0000975void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +0000976 Table *p;
danielk19777977a172004-11-09 12:44:37 +0000977 Column *pCol;
drh7020f652000-06-03 18:06:52 +0000978 if( (p = pParse->pNewTable)==0 ) return;
danielk19777977a172004-11-09 12:44:37 +0000979 pCol = &(p->aCol[p->nCol-1]);
drheb55bd22005-06-30 17:04:21 +0000980 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
danielk19777977a172004-11-09 12:44:37 +0000981 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
982 pCol->zName);
983 }else{
984 sqlite3ExprDelete(pCol->pDflt);
985 pCol->pDflt = sqlite3ExprDup(pExpr);
danielk19777977a172004-11-09 12:44:37 +0000986 }
987 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +0000988}
989
990/*
drh4a324312001-12-21 14:30:42 +0000991** Designate the PRIMARY KEY for the table. pList is a list of names
992** of columns that form the primary key. If pList is NULL, then the
993** most recently added column of the table is the primary key.
994**
995** A table can have at most one primary key. If the table already has
996** a primary key (and this is the second primary key) then create an
997** error.
998**
999** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +00001000** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +00001001** field of the table under construction to be the index of the
1002** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1003** no INTEGER PRIMARY KEY.
1004**
1005** If the key is not an INTEGER PRIMARY KEY, then create a unique
1006** index for the key. No index is created for INTEGER PRIMARY KEYs.
1007*/
drh205f48e2004-11-05 00:43:11 +00001008void sqlite3AddPrimaryKey(
1009 Parse *pParse, /* Parsing context */
1010 ExprList *pList, /* List of field names to be indexed */
1011 int onError, /* What to do with a uniqueness conflict */
1012 int autoInc /* True if the AUTOINCREMENT keyword is present */
1013){
drh4a324312001-12-21 14:30:42 +00001014 Table *pTab = pParse->pNewTable;
1015 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +00001016 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +00001017 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001018 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +00001019 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001020 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +00001021 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +00001022 }
1023 pTab->hasPrimKey = 1;
1024 if( pList==0 ){
1025 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +00001026 pTab->aCol[iCol].isPrimKey = 1;
1027 }else{
danielk19770202b292004-06-09 09:55:16 +00001028 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +00001029 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +00001030 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
1031 break;
1032 }
drh78100cc2003-08-23 22:40:53 +00001033 }
1034 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
drh4a324312001-12-21 14:30:42 +00001035 }
danielk19770202b292004-06-09 09:55:16 +00001036 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +00001037 }
1038 if( iCol>=0 && iCol<pTab->nCol ){
1039 zType = pTab->aCol[iCol].zType;
1040 }
danielk19773d68f032004-05-11 07:11:51 +00001041 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
drh4a324312001-12-21 14:30:42 +00001042 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +00001043 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +00001044 pTab->autoInc = autoInc;
1045 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +00001046#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +00001047 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1048 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +00001049#endif
drh4a324312001-12-21 14:30:42 +00001050 }else{
danielk1977cbb18d22004-05-28 11:37:27 +00001051 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
drhe0194f22003-02-26 13:52:51 +00001052 pList = 0;
drh4a324312001-12-21 14:30:42 +00001053 }
drhe0194f22003-02-26 13:52:51 +00001054
1055primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +00001056 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +00001057 return;
drh4a324312001-12-21 14:30:42 +00001058}
1059
1060/*
drhd3d39e92004-05-20 22:16:29 +00001061** Set the collation function of the most recently parsed table column
1062** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +00001063*/
drhd3d39e92004-05-20 22:16:29 +00001064void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +00001065 Table *p;
danielk19770202b292004-06-09 09:55:16 +00001066 Index *pIdx;
drhd3d39e92004-05-20 22:16:29 +00001067 CollSeq *pColl;
danielk19770202b292004-06-09 09:55:16 +00001068 int i;
danielk1977a37cdde2004-05-16 11:15:36 +00001069
drhd3d39e92004-05-20 22:16:29 +00001070 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +00001071 i = p->nCol-1;
1072
1073 pColl = sqlite3LocateCollSeq(pParse, zType, nType);
1074 p->aCol[i].pColl = pColl;
1075
1076 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
1077 ** then an index may have been created on this column before the
1078 ** collation type was added. Correct this if it is the case.
1079 */
1080 for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){
1081 assert( pIdx->nColumn==1 );
1082 if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl;
drhd3d39e92004-05-20 22:16:29 +00001083 }
1084}
1085
1086/*
drhda71ce12004-06-21 18:14:45 +00001087** Call sqlite3CheckCollSeq() for all collating sequences in an index,
1088** in order to verify that all the necessary collating sequences are
1089** loaded.
1090*/
danielk19777cedc8d2004-06-10 10:50:08 +00001091int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){
1092 if( pIdx ){
1093 int i;
1094 for(i=0; i<pIdx->nColumn; i++){
1095 if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){
1096 return SQLITE_ERROR;
1097 }
1098 }
1099 }
1100 return SQLITE_OK;
1101}
1102
danielk1977466be562004-06-10 02:16:01 +00001103/*
1104** This function returns the collation sequence for database native text
1105** encoding identified by the string zName, length nName.
1106**
1107** If the requested collation sequence is not available, or not available
1108** in the database native encoding, the collation factory is invoked to
1109** request it. If the collation factory does not supply such a sequence,
1110** and the sequence is available in another text encoding, then that is
1111** returned instead.
1112**
1113** If no versions of the requested collations sequence are available, or
1114** another error occurs, NULL is returned and an error message written into
1115** pParse.
1116*/
danielk19770202b292004-06-09 09:55:16 +00001117CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk19774dade032005-05-25 10:45:10 +00001118 sqlite3 *db = pParse->db;
1119 u8 enc = db->enc;
1120 u8 initbusy = db->init.busy;
1121
1122 CollSeq *pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
danielk19777cedc8d2004-06-10 10:50:08 +00001123 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19774dade032005-05-25 10:45:10 +00001124 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
1125 if( !pColl ){
1126 if( nName<0 ){
1127 nName = strlen(zName);
danielk1977466be562004-06-10 02:16:01 +00001128 }
danielk19774dade032005-05-25 10:45:10 +00001129 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
1130 pColl = 0;
danielk1977466be562004-06-10 02:16:01 +00001131 }
1132 }
1133
danielk19770202b292004-06-09 09:55:16 +00001134 return pColl;
1135}
1136
1137
drh8e2ca022002-06-17 17:07:19 +00001138/*
drh3f7d4e42004-07-24 14:35:58 +00001139** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001140**
1141** The schema cookie is used to determine when the schema for the
1142** database changes. After each schema change, the cookie value
1143** changes. When a process first reads the schema it records the
1144** cookie. Thereafter, whenever it goes to access the database,
1145** it checks the cookie to make sure the schema has not changed
1146** since it was last read.
1147**
1148** This plan is not completely bullet-proof. It is possible for
1149** the schema to change multiple times and for the cookie to be
1150** set back to prior value. But schema changes are infrequent
1151** and the probability of hitting the same cookie value is only
1152** 1 chance in 2^32. So we're safe enough.
1153*/
drh9bb575f2004-09-06 17:24:11 +00001154void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
drh3f7d4e42004-07-24 14:35:58 +00001155 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001156 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001157}
1158
1159/*
drh969fa7c2002-02-18 18:30:32 +00001160** Measure the number of characters needed to output the given
1161** identifier. The number returned includes any quotes used
1162** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001163**
1164** The estimate is conservative. It might be larger that what is
1165** really needed.
drh969fa7c2002-02-18 18:30:32 +00001166*/
1167static int identLength(const char *z){
1168 int n;
drh17f71932002-02-21 12:01:27 +00001169 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001170 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001171 }
drh234c39d2004-07-24 03:30:47 +00001172 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001173}
1174
1175/*
1176** Write an identifier onto the end of the given string. Add
1177** quote characters as needed.
1178*/
drh4c755c02004-08-08 20:22:17 +00001179static void identPut(char *z, int *pIdx, char *zSignedIdent){
1180 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001181 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001182 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001183 for(j=0; zIdent[j]; j++){
1184 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1185 }
1186 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001187 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001188 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001189 for(j=0; zIdent[j]; j++){
1190 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001191 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001192 }
drh234c39d2004-07-24 03:30:47 +00001193 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001194 z[i] = 0;
1195 *pIdx = i;
1196}
1197
1198/*
1199** Generate a CREATE TABLE statement appropriate for the given
1200** table. Memory to hold the text of the statement is obtained
1201** from sqliteMalloc() and must be freed by the calling function.
1202*/
1203static char *createTableStmt(Table *p){
1204 int i, k, n;
1205 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001206 char *zSep, *zSep2, *zEnd, *z;
1207 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001208 n = 0;
drh234c39d2004-07-24 03:30:47 +00001209 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1210 n += identLength(pCol->zName);
1211 z = pCol->zType;
1212 if( z ){
1213 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001214 }
drh969fa7c2002-02-18 18:30:32 +00001215 }
1216 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001217 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001218 zSep = "";
1219 zSep2 = ",";
1220 zEnd = ")";
1221 }else{
1222 zSep = "\n ";
1223 zSep2 = ",\n ";
1224 zEnd = "\n)";
1225 }
drhe0bc4042002-06-25 01:09:11 +00001226 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001227 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001228 if( zStmt==0 ) return 0;
danielk197753c0f742005-03-29 03:10:59 +00001229 strcpy(zStmt, !OMIT_TEMPDB&&p->iDb==1 ? "CREATE TEMP TABLE ":"CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001230 k = strlen(zStmt);
1231 identPut(zStmt, &k, p->zName);
1232 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001233 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001234 strcpy(&zStmt[k], zSep);
1235 k += strlen(&zStmt[k]);
1236 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001237 identPut(zStmt, &k, pCol->zName);
1238 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001239 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001240 strcpy(&zStmt[k], z);
1241 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001242 }
drh969fa7c2002-02-18 18:30:32 +00001243 }
1244 strcpy(&zStmt[k], zEnd);
1245 return zStmt;
1246}
1247
1248/*
drh75897232000-05-29 14:26:00 +00001249** This routine is called to report the final ")" that terminates
1250** a CREATE TABLE statement.
1251**
drhf57b3392001-10-08 13:22:32 +00001252** The table structure that other action routines have been building
1253** is added to the internal hash tables, assuming no errors have
1254** occurred.
drh75897232000-05-29 14:26:00 +00001255**
drh1d85d932004-02-14 23:05:52 +00001256** An entry for the table is made in the master table on disk, unless
1257** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001258** it means we are reading the sqlite_master table because we just
1259** connected to the database or because the sqlite_master table has
drhddba9e52005-03-19 01:41:21 +00001260** recently changed, so the entry for this table already exists in
drhf57b3392001-10-08 13:22:32 +00001261** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001262**
1263** If the pSelect argument is not NULL, it means that this routine
1264** was called to create a table generated from a
1265** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1266** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001267*/
danielk197719a8e7e2005-03-17 05:03:38 +00001268void sqlite3EndTable(
1269 Parse *pParse, /* Parse context */
1270 Token *pCons, /* The ',' token after the last column defn. */
1271 Token *pEnd, /* The final ')' token in the CREATE TABLE */
1272 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
1273){
drh75897232000-05-29 14:26:00 +00001274 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001275 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001276
danielk197724b03fd2004-05-10 10:34:34 +00001277 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
drh28037572000-08-02 13:47:41 +00001278 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001279 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001280
danielk1977517eb642004-06-07 10:00:31 +00001281 assert( !db->init.busy || !pSelect );
1282
drh1d85d932004-02-14 23:05:52 +00001283 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001284 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1285 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001286 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001287 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001288 */
drh1d85d932004-02-14 23:05:52 +00001289 if( db->init.busy ){
1290 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001291 }
1292
drhe3c41372001-09-17 20:25:58 +00001293 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001294 ** in the SQLITE_MASTER table of the database. The record number
1295 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001296 **
drhe0bc4042002-06-25 01:09:11 +00001297 ** If this is a TEMPORARY table, write the entry into the auxiliary
1298 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001299 */
drh1d85d932004-02-14 23:05:52 +00001300 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001301 int n;
drhd8bc7082000-06-07 23:51:50 +00001302 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001303 char *zType; /* "view" or "table" */
1304 char *zType2; /* "VIEW" or "TABLE" */
1305 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001306
danielk19774adee202004-05-08 08:23:19 +00001307 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001308 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001309
danielk1977e6efa742004-11-10 11:55:10 +00001310 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1311
drh4794f732004-11-05 17:17:50 +00001312 /* Create the rootpage for the new table and push it onto the stack.
1313 ** A view has no rootpage, so just push a zero onto the stack for
1314 ** views. Initialize zType at the same time.
1315 */
drh4ff6dfa2002-03-03 23:06:00 +00001316 if( p->pSelect==0 ){
1317 /* A regular table */
danielk1977a21c6b62005-01-24 10:25:59 +00001318 /* sqlite3VdbeAddOp(v, OP_CreateTable, p->iDb, 0); */
drh4794f732004-11-05 17:17:50 +00001319 zType = "table";
1320 zType2 = "TABLE";
danielk1977576ec6b2005-01-21 11:55:25 +00001321#ifndef SQLITE_OMIT_VIEW
drh4ff6dfa2002-03-03 23:06:00 +00001322 }else{
1323 /* A view */
danielk1977a21c6b62005-01-24 10:25:59 +00001324 /* sqlite3VdbeAddOp(v, OP_Integer, 0, 0); */
drh4794f732004-11-05 17:17:50 +00001325 zType = "view";
1326 zType2 = "VIEW";
danielk1977576ec6b2005-01-21 11:55:25 +00001327#endif
drh4ff6dfa2002-03-03 23:06:00 +00001328 }
danielk1977517eb642004-06-07 10:00:31 +00001329
danielk1977517eb642004-06-07 10:00:31 +00001330 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1331 ** statement to populate the new table. The root-page number for the
1332 ** new table is on the top of the vdbe stack.
1333 **
1334 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1335 ** suitable state to query for the column names and types to be used
1336 ** by the new table.
1337 */
1338 if( pSelect ){
1339 Table *pSelTab;
1340 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1341 sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
1342 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1343 pParse->nTab = 2;
danielk1977b3bce662005-01-29 08:32:43 +00001344 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
danielk1977517eb642004-06-07 10:00:31 +00001345 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1346 if( pParse->nErr==0 ){
1347 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1348 if( pSelTab==0 ) return;
1349 assert( p->aCol==0 );
1350 p->nCol = pSelTab->nCol;
1351 p->aCol = pSelTab->aCol;
1352 pSelTab->nCol = 0;
1353 pSelTab->aCol = 0;
1354 sqlite3DeleteTable(0, pSelTab);
1355 }
1356 }
drh4794f732004-11-05 17:17:50 +00001357
drh4794f732004-11-05 17:17:50 +00001358 /* Compute the complete text of the CREATE statement */
1359 if( pSelect ){
1360 zStmt = createTableStmt(p);
1361 }else{
drh97903fe2005-05-24 20:19:57 +00001362 n = pEnd->z - pParse->sNameToken.z + 1;
drh4794f732004-11-05 17:17:50 +00001363 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1364 }
1365
1366 /* A slot for the record has already been allocated in the
1367 ** SQLITE_MASTER table. We just need to update that slot with all
1368 ** the information we've collected. The rowid for the preallocated
1369 ** slot is the 2nd item on the stack. The top of the stack is the
1370 ** root page for the new table (or a 0 if this is a view).
1371 */
1372 sqlite3NestedParse(pParse,
1373 "UPDATE %Q.%s "
1374 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1375 "WHERE rowid=#1",
1376 db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb),
1377 zType,
1378 p->zName,
1379 p->zName,
1380 zStmt
1381 );
1382 sqliteFree(zStmt);
drh2958a4e2004-11-12 03:56:15 +00001383 sqlite3ChangeCookie(db, v, p->iDb);
1384
1385#ifndef SQLITE_OMIT_AUTOINCREMENT
1386 /* Check to see if we need to create an sqlite_sequence table for
1387 ** keeping track of autoincrement keys.
1388 */
1389 if( p->autoInc ){
1390 Db *pDb = &db->aDb[p->iDb];
1391 if( pDb->pSeqTab==0 ){
1392 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001393 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1394 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001395 );
1396 }
1397 }
1398#endif
drh4794f732004-11-05 17:17:50 +00001399
1400 /* Reparse everything to update our internal data structures */
drh234c39d2004-07-24 03:30:47 +00001401 sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0,
1402 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001403 }
drh17e9e292003-02-01 13:53:28 +00001404
drh2958a4e2004-11-12 03:56:15 +00001405
drh17e9e292003-02-01 13:53:28 +00001406 /* Add the table to the in-memory representation of the database.
1407 */
drh234c39d2004-07-24 03:30:47 +00001408 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001409 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001410 FKey *pFKey;
1411 Db *pDb = &db->aDb[p->iDb];
1412 pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p);
drh17e9e292003-02-01 13:53:28 +00001413 if( pOld ){
1414 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1415 return;
1416 }
danielk1977576ec6b2005-01-21 11:55:25 +00001417#ifndef SQLITE_OMIT_FOREIGN_KEY
drh17e9e292003-02-01 13:53:28 +00001418 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1419 int nTo = strlen(pFKey->zTo) + 1;
drhbe5c89a2004-07-26 00:31:09 +00001420 pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo);
1421 sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001422 }
danielk1977576ec6b2005-01-21 11:55:25 +00001423#endif
drh17e9e292003-02-01 13:53:28 +00001424 pParse->pNewTable = 0;
1425 db->nTable++;
1426 db->flags |= SQLITE_InternChanges;
danielk197719a8e7e2005-03-17 05:03:38 +00001427
1428#ifndef SQLITE_OMIT_ALTERTABLE
1429 if( !p->pSelect ){
1430 assert( !pSelect && pCons && pEnd );
1431 if( pCons->z==0 ) pCons = pEnd;
1432 p->addColOffset = 13 + (pCons->z - pParse->sNameToken.z);
1433 }
1434#endif
drh17e9e292003-02-01 13:53:28 +00001435 }
drh75897232000-05-29 14:26:00 +00001436}
1437
drhb7f91642004-10-31 02:22:47 +00001438#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001439/*
drha76b5df2002-02-23 02:32:10 +00001440** The parser calls this routine in order to create a new VIEW
1441*/
danielk19774adee202004-05-08 08:23:19 +00001442void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001443 Parse *pParse, /* The parsing context */
1444 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001445 Token *pName1, /* The token that holds the name of the view */
1446 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001447 Select *pSelect, /* A SELECT statement that will become the new view */
1448 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001449){
drha76b5df2002-02-23 02:32:10 +00001450 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001451 int n;
drh4c755c02004-08-08 20:22:17 +00001452 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001453 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001454 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001455 Token *pName;
drha76b5df2002-02-23 02:32:10 +00001456
drh7c3d64f2005-06-06 15:32:08 +00001457 if( pParse->nVar>0 ){
1458 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
1459 sqlite3SelectDelete(pSelect);
1460 return;
1461 }
danielk197748dec7e2004-05-28 12:33:30 +00001462 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
drha76b5df2002-02-23 02:32:10 +00001463 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001464 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001465 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001466 return;
1467 }
danielk1977ef2cb632004-05-29 02:37:19 +00001468 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk19774adee202004-05-08 08:23:19 +00001469 if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
1470 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001471 ){
danielk19774adee202004-05-08 08:23:19 +00001472 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001473 return;
1474 }
drh174b6192002-12-03 02:22:52 +00001475
drh4b59ab52002-08-24 18:24:51 +00001476 /* Make a copy of the entire SELECT statement that defines the view.
1477 ** This will force all the Expr.token.z values to be dynamically
1478 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001479 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001480 */
danielk19774adee202004-05-08 08:23:19 +00001481 p->pSelect = sqlite3SelectDup(pSelect);
1482 sqlite3SelectDelete(pSelect);
drh1d85d932004-02-14 23:05:52 +00001483 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001484 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001485 }
drh4b59ab52002-08-24 18:24:51 +00001486
1487 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1488 ** the end.
1489 */
drha76b5df2002-02-23 02:32:10 +00001490 sEnd = pParse->sLastToken;
1491 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1492 sEnd.z += sEnd.n;
1493 }
1494 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001495 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001496 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001497 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1498 sEnd.z = &z[n-1];
1499 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001500
danielk19774adee202004-05-08 08:23:19 +00001501 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
danielk197719a8e7e2005-03-17 05:03:38 +00001502 sqlite3EndTable(pParse, 0, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001503 return;
drh417be792002-03-03 18:59:40 +00001504}
drhb7f91642004-10-31 02:22:47 +00001505#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001506
drhb7f91642004-10-31 02:22:47 +00001507#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001508/*
1509** The Table structure pTable is really a VIEW. Fill in the names of
1510** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001511** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001512*/
danielk19774adee202004-05-08 08:23:19 +00001513int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh9b3187e2005-01-18 14:45:47 +00001514 Table *pSelTab; /* A fake table from which we get the result set */
1515 Select *pSel; /* Copy of the SELECT that implements the view */
1516 int nErr = 0; /* Number of errors encountered */
1517 int n; /* Temporarily holds the number of cursors assigned */
drh417be792002-03-03 18:59:40 +00001518
1519 assert( pTable );
1520
1521 /* A positive nCol means the columns names for this view are
1522 ** already known.
1523 */
1524 if( pTable->nCol>0 ) return 0;
1525
1526 /* A negative nCol is a special marker meaning that we are currently
1527 ** trying to compute the column names. If we enter this routine with
1528 ** a negative nCol, it means two or more views form a loop, like this:
1529 **
1530 ** CREATE VIEW one AS SELECT * FROM two;
1531 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001532 **
1533 ** Actually, this error is caught previously and so the following test
1534 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001535 */
1536 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001537 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001538 return 1;
1539 }
1540
1541 /* If we get this far, it means we need to compute the table names.
drh9b3187e2005-01-18 14:45:47 +00001542 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
1543 ** "*" elements in the results set of the view and will assign cursors
1544 ** to the elements of the FROM clause. But we do not want these changes
1545 ** to be permanent. So the computation is done on a copy of the SELECT
1546 ** statement that defines the view.
drh417be792002-03-03 18:59:40 +00001547 */
drh9b3187e2005-01-18 14:45:47 +00001548 assert( pTable->pSelect );
1549 pSel = sqlite3SelectDup(pTable->pSelect);
1550 n = pParse->nTab;
1551 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
drh417be792002-03-03 18:59:40 +00001552 pTable->nCol = -1;
danielk19774adee202004-05-08 08:23:19 +00001553 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
drh9b3187e2005-01-18 14:45:47 +00001554 pParse->nTab = n;
drh417be792002-03-03 18:59:40 +00001555 if( pSelTab ){
1556 assert( pTable->aCol==0 );
1557 pTable->nCol = pSelTab->nCol;
1558 pTable->aCol = pSelTab->aCol;
1559 pSelTab->nCol = 0;
1560 pSelTab->aCol = 0;
danielk19774adee202004-05-08 08:23:19 +00001561 sqlite3DeleteTable(0, pSelTab);
drh8bf8dc92003-05-17 17:35:10 +00001562 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
drh417be792002-03-03 18:59:40 +00001563 }else{
1564 pTable->nCol = 0;
1565 nErr++;
1566 }
drh9b3187e2005-01-18 14:45:47 +00001567 sqlite3SelectDelete(pSel);
drh417be792002-03-03 18:59:40 +00001568 return nErr;
1569}
drhb7f91642004-10-31 02:22:47 +00001570#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001571
drhb7f91642004-10-31 02:22:47 +00001572#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001573/*
drh8bf8dc92003-05-17 17:35:10 +00001574** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001575*/
drh9bb575f2004-09-06 17:24:11 +00001576static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001577 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001578 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
drhd24cc422003-03-27 12:51:24 +00001579 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001580 Table *pTab = sqliteHashData(i);
1581 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001582 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001583 }
1584 }
drh8bf8dc92003-05-17 17:35:10 +00001585 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001586}
drhb7f91642004-10-31 02:22:47 +00001587#else
1588# define sqliteViewResetAll(A,B)
1589#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001590
drh75897232000-05-29 14:26:00 +00001591/*
danielk1977a0bf2652004-11-04 14:30:04 +00001592** This function is called by the VDBE to adjust the internal schema
1593** used by SQLite when the btree layer moves a table root page. The
1594** root-page of a table or index in database iDb has changed from iFrom
1595** to iTo.
1596*/
1597#ifndef SQLITE_OMIT_AUTOVACUUM
1598void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1599 HashElem *pElem;
1600
1601 for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){
1602 Table *pTab = sqliteHashData(pElem);
1603 if( pTab->tnum==iFrom ){
1604 pTab->tnum = iTo;
1605 return;
1606 }
1607 }
1608 for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){
1609 Index *pIdx = sqliteHashData(pElem);
1610 if( pIdx->tnum==iFrom ){
1611 pIdx->tnum = iTo;
1612 return;
1613 }
1614 }
1615 assert(0);
1616}
1617#endif
1618
1619/*
1620** Write code to erase the table with root-page iTable from database iDb.
1621** Also write code to modify the sqlite_master table and internal schema
1622** if a root-page of another table is moved by the btree-layer whilst
1623** erasing iTable (this can happen with an auto-vacuum database).
1624*/
drh4e0cff62004-11-05 05:10:28 +00001625static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1626 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001627 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1628#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001629 /* OP_Destroy pushes an integer onto the stack. If this integer
1630 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001631 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001632 ** reflect this.
1633 **
1634 ** The "#0" in the SQL is a special constant that means whatever value
1635 ** is on the top of the stack. See sqlite3RegisterExpr().
1636 */
danielk197763e3e9f2004-11-05 09:19:27 +00001637 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001638 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001639 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001640#endif
1641}
1642
1643/*
1644** Write VDBE code to erase table pTab and all associated indices on disk.
1645** Code to update the sqlite_master tables and internal schema definitions
1646** in case a root-page belonging to another table is moved by the btree layer
1647** is also added (this can happen with an auto-vacuum database).
1648*/
drh4e0cff62004-11-05 05:10:28 +00001649static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001650#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001651 Index *pIdx;
drh4e0cff62004-11-05 05:10:28 +00001652 destroyRootPage(pParse, pTab->tnum, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001653 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh7a638582004-11-05 05:23:59 +00001654 destroyRootPage(pParse, pIdx->tnum, pIdx->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001655 }
1656#else
1657 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1658 ** is not defined), then it is important to call OP_Destroy on the
1659 ** table and index root-pages in order, starting with the numerically
1660 ** largest root-page number. This guarantees that none of the root-pages
1661 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1662 ** following were coded:
1663 **
1664 ** OP_Destroy 4 0
1665 ** ...
1666 ** OP_Destroy 5 0
1667 **
1668 ** and root page 5 happened to be the largest root-page number in the
1669 ** database, then root page 5 would be moved to page 4 by the
1670 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1671 ** a free-list page.
1672 */
1673 int iTab = pTab->tnum;
1674 int iDestroyed = 0;
1675
1676 while( 1 ){
1677 Index *pIdx;
1678 int iLargest = 0;
1679
1680 if( iDestroyed==0 || iTab<iDestroyed ){
1681 iLargest = iTab;
1682 }
1683 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1684 int iIdx = pIdx->tnum;
1685 assert( pIdx->iDb==pTab->iDb );
1686 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1687 iLargest = iIdx;
1688 }
1689 }
1690 if( iLargest==0 ) return;
drh4e0cff62004-11-05 05:10:28 +00001691 destroyRootPage(pParse, iLargest, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001692 iDestroyed = iLargest;
1693 }
1694#endif
1695}
1696
1697/*
drh75897232000-05-29 14:26:00 +00001698** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001699** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001700*/
danielk1977a8858102004-05-28 12:11:21 +00001701void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
1702 Table *pTab;
drh75897232000-05-29 14:26:00 +00001703 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001704 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001705 int iDb;
drh75897232000-05-29 14:26:00 +00001706
danielk1977a8858102004-05-28 12:11:21 +00001707 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
1708 assert( pName->nSrc==1 );
1709 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1710
1711 if( pTab==0 ) goto exit_drop_table;
1712 iDb = pTab->iDb;
drhe22a3342003-04-22 20:30:37 +00001713 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001714#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001715 {
1716 int code;
danielk1977a8858102004-05-28 12:11:21 +00001717 const char *zTab = SCHEMA_TABLE(pTab->iDb);
1718 const char *zDb = db->aDb[pTab->iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001719 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001720 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001721 }
drhe5f9c642003-01-13 23:27:31 +00001722 if( isView ){
danielk197753c0f742005-03-29 03:10:59 +00001723 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001724 code = SQLITE_DROP_TEMP_VIEW;
1725 }else{
1726 code = SQLITE_DROP_VIEW;
1727 }
1728 }else{
danielk197753c0f742005-03-29 03:10:59 +00001729 if( !OMIT_TEMPDB && iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001730 code = SQLITE_DROP_TEMP_TABLE;
1731 }else{
1732 code = SQLITE_DROP_TABLE;
1733 }
1734 }
danielk1977a8858102004-05-28 12:11:21 +00001735 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1736 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001737 }
danielk1977a8858102004-05-28 12:11:21 +00001738 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1739 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001740 }
drhe5f9c642003-01-13 23:27:31 +00001741 }
1742#endif
drhf3388142004-11-13 03:48:06 +00001743 if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001744 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001745 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001746 }
danielk1977576ec6b2005-01-21 11:55:25 +00001747
1748#ifndef SQLITE_OMIT_VIEW
1749 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
1750 ** on a table.
1751 */
danielk1977a8858102004-05-28 12:11:21 +00001752 if( isView && pTab->pSelect==0 ){
1753 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1754 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001755 }
danielk1977a8858102004-05-28 12:11:21 +00001756 if( !isView && pTab->pSelect ){
1757 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1758 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001759 }
danielk1977576ec6b2005-01-21 11:55:25 +00001760#endif
drh75897232000-05-29 14:26:00 +00001761
drh1ccde152000-06-17 13:12:39 +00001762 /* Generate code to remove the table from the master table
1763 ** on disk.
1764 */
danielk19774adee202004-05-08 08:23:19 +00001765 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001766 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001767 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001768 int iDb = pTab->iDb;
1769 Db *pDb = &db->aDb[iDb];
1770 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001771
danielk19778e227872004-06-07 07:52:17 +00001772 /* Drop all triggers associated with the table being dropped. Code
1773 ** is generated to remove entries from sqlite_master and/or
1774 ** sqlite_temp_master if required.
1775 */
danielk1977a8858102004-05-28 12:11:21 +00001776 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001777 while( pTrigger ){
drh2958a4e2004-11-12 03:56:15 +00001778 assert( pTrigger->iDb==iDb || pTrigger->iDb==1 );
danielk19774adee202004-05-08 08:23:19 +00001779 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001780 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001781 }
drh8bf8dc92003-05-17 17:35:10 +00001782
danielk19774d36b812004-11-19 07:07:30 +00001783#ifndef SQLITE_OMIT_AUTOINCREMENT
1784 /* Remove any entries of the sqlite_sequence table associated with
1785 ** the table being dropped. This is done before the table is dropped
1786 ** at the btree level, in case the sqlite_sequence table needs to
1787 ** move as a result of the drop (can happen in auto-vacuum mode).
1788 */
1789 if( pTab->autoInc ){
1790 sqlite3NestedParse(pParse,
1791 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1792 pDb->zName, pTab->zName
1793 );
1794 }
1795#endif
1796
danielk19778e227872004-06-07 07:52:17 +00001797 /* Drop all SQLITE_MASTER table and index entries that refer to the
1798 ** table. The program name loops through the master table and deletes
1799 ** every row that refers to a table of the same name as the one being
1800 ** dropped. Triggers are handled seperately because a trigger can be
1801 ** created in the temp database that refers to a table in another
1802 ** database.
1803 */
drhf1974842004-11-05 03:56:00 +00001804 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001805 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001806 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001807 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001808 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001809 }
drh2958a4e2004-11-12 03:56:15 +00001810
danielk1977a21c6b62005-01-24 10:25:59 +00001811 /* Remove the table entry from SQLite's internal schema and modify
1812 ** the schema cookie.
drh2958a4e2004-11-12 03:56:15 +00001813 */
1814 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
danielk1977a21c6b62005-01-24 10:25:59 +00001815 sqlite3ChangeCookie(db, v, iDb);
drh75897232000-05-29 14:26:00 +00001816 }
drhd24cc422003-03-27 12:51:24 +00001817 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001818
1819exit_drop_table:
1820 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001821}
1822
1823/*
drhc2eef3b2002-08-31 18:53:06 +00001824** This routine is called to create a new foreign key on the table
1825** currently under construction. pFromCol determines which columns
1826** in the current table point to the foreign key. If pFromCol==0 then
1827** connect the key to the last column inserted. pTo is the name of
1828** the table referred to. pToCol is a list of tables in the other
1829** pTo table that the foreign key points to. flags contains all
1830** information about the conflict resolution algorithms specified
1831** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1832**
1833** An FKey structure is created and added to the table currently
1834** under construction in the pParse->pNewTable field. The new FKey
1835** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001836** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001837**
1838** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001839** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001840*/
danielk19774adee202004-05-08 08:23:19 +00001841void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001842 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001843 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001844 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001845 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001846 int flags /* Conflict resolution algorithms. */
1847){
drhb7f91642004-10-31 02:22:47 +00001848#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001849 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001850 Table *p = pParse->pNewTable;
1851 int nByte;
1852 int i;
1853 int nCol;
1854 char *z;
drhc2eef3b2002-08-31 18:53:06 +00001855
1856 assert( pTo!=0 );
1857 if( p==0 || pParse->nErr ) goto fk_end;
1858 if( pFromCol==0 ){
1859 int iCol = p->nCol-1;
1860 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00001861 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00001862 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00001863 " should reference only one column of table %T",
1864 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00001865 goto fk_end;
1866 }
1867 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00001868 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001869 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00001870 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00001871 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00001872 goto fk_end;
1873 }else{
danielk19770202b292004-06-09 09:55:16 +00001874 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00001875 }
1876 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1877 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00001878 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00001879 nByte += strlen(pToCol->a[i].zName) + 1;
1880 }
1881 }
1882 pFKey = sqliteMalloc( nByte );
1883 if( pFKey==0 ) goto fk_end;
1884 pFKey->pFrom = p;
1885 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00001886 z = (char*)&pFKey[1];
1887 pFKey->aCol = (struct sColMap*)z;
1888 z += sizeof(struct sColMap)*nCol;
1889 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00001890 memcpy(z, pTo->z, pTo->n);
1891 z[pTo->n] = 0;
1892 z += pTo->n+1;
1893 pFKey->pNextTo = 0;
1894 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00001895 if( pFromCol==0 ){
1896 pFKey->aCol[0].iFrom = p->nCol-1;
1897 }else{
1898 for(i=0; i<nCol; i++){
1899 int j;
1900 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00001901 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00001902 pFKey->aCol[i].iFrom = j;
1903 break;
1904 }
1905 }
1906 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00001907 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001908 "unknown column \"%s\" in foreign key definition",
1909 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00001910 goto fk_end;
1911 }
1912 }
1913 }
1914 if( pToCol ){
1915 for(i=0; i<nCol; i++){
1916 int n = strlen(pToCol->a[i].zName);
1917 pFKey->aCol[i].zCol = z;
1918 memcpy(z, pToCol->a[i].zName, n);
1919 z[n] = 0;
1920 z += n+1;
1921 }
1922 }
1923 pFKey->isDeferred = 0;
1924 pFKey->deleteConf = flags & 0xff;
1925 pFKey->updateConf = (flags >> 8 ) & 0xff;
1926 pFKey->insertConf = (flags >> 16 ) & 0xff;
1927
1928 /* Link the foreign key to the table as the last step.
1929 */
1930 p->pFKey = pFKey;
1931 pFKey = 0;
1932
1933fk_end:
1934 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00001935#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00001936 sqlite3ExprListDelete(pFromCol);
1937 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00001938}
1939
1940/*
1941** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
1942** clause is seen as part of a foreign key definition. The isDeferred
1943** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
1944** The behavior of the most recently created foreign key is adjusted
1945** accordingly.
1946*/
danielk19774adee202004-05-08 08:23:19 +00001947void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00001948#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00001949 Table *pTab;
1950 FKey *pFKey;
1951 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
1952 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00001953#endif
drhc2eef3b2002-08-31 18:53:06 +00001954}
1955
1956/*
drh063336a2004-11-05 20:58:39 +00001957** Generate code that will erase and refill index *pIdx. This is
1958** used to initialize a newly created index or to recompute the
1959** content of an index in response to a REINDEX command.
1960**
1961** if memRootPage is not negative, it means that the index is newly
1962** created. The memory cell specified by memRootPage contains the
1963** root page number of the index. If memRootPage is negative, then
1964** the index already exists and must be cleared before being refilled and
1965** the root page number of the index is taken from pIndex->tnum.
1966*/
1967static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
1968 Table *pTab = pIndex->pTable; /* The table that is indexed */
1969 int iTab = pParse->nTab; /* Btree cursor used for pTab */
1970 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
1971 int addr1; /* Address of top of loop */
1972 int tnum; /* Root page of index */
1973 Vdbe *v; /* Generate code into this virtual machine */
1974
danielk19771d54df82004-11-23 15:41:16 +00001975#ifndef SQLITE_OMIT_AUTHORIZATION
1976 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
1977 pParse->db->aDb[pIndex->iDb].zName ) ){
1978 return;
1979 }
1980#endif
1981
danielk197733a5edc2005-01-27 00:22:02 +00001982 /* Ensure all the required collation sequences are available. This
1983 ** routine will invoke the collation-needed callback if necessary (and
1984 ** if one has been registered).
1985 */
1986 if( sqlite3CheckIndexCollSeq(pParse, pIndex) ){
1987 return;
1988 }
1989
drh063336a2004-11-05 20:58:39 +00001990 v = sqlite3GetVdbe(pParse);
1991 if( v==0 ) return;
1992 if( memRootPage>=0 ){
1993 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
1994 tnum = 0;
1995 }else{
1996 tnum = pIndex->tnum;
1997 sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb);
1998 }
1999 sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0);
2000 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum,
2001 (char*)&pIndex->keyInfo, P3_KEYINFO);
drh29dda4a2005-07-21 18:23:20 +00002002 sqlite3OpenTableForReading(v, iTab, pTab);
drh063336a2004-11-05 20:58:39 +00002003 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2004 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh7f057c92005-06-24 03:53:06 +00002005 if( pIndex->onError!=OE_None ){
2006 int curaddr = sqlite3VdbeCurrentAddr(v);
2007 int addr2 = curaddr+4;
2008 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
2009 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
2010 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
2011 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
2012 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
2013 "indexed columns are not unique", P3_STATIC);
2014 assert( addr2==sqlite3VdbeCurrentAddr(v) );
drh4343fea2004-11-05 23:46:15 +00002015 }
drh7f057c92005-06-24 03:53:06 +00002016 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
drh063336a2004-11-05 20:58:39 +00002017 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
2018 sqlite3VdbeChangeP2(v, addr1, sqlite3VdbeCurrentAddr(v));
2019 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2020 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2021}
2022
2023/*
drh23bf66d2004-12-14 03:34:34 +00002024** Create a new index for an SQL table. pName1.pName2 is the name of the index
2025** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002026** be NULL for a primary key or an index that is created to satisfy a
2027** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002028** as the table to be indexed. pParse->pNewTable is a table that is
2029** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002030**
drh382c0242001-10-06 16:33:02 +00002031** pList is a list of columns to be indexed. pList will be NULL if this
2032** is a primary key or unique-constraint on the most recent column added
2033** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002034*/
danielk19774adee202004-05-08 08:23:19 +00002035void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002036 Parse *pParse, /* All information about this parse */
2037 Token *pName1, /* First part of index name. May be NULL */
2038 Token *pName2, /* Second part of index name. May be NULL */
2039 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002040 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002041 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2042 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
2043 Token *pEnd /* The ")" that closes the CREATE INDEX statement */
drh75897232000-05-29 14:26:00 +00002044){
drh23bf66d2004-12-14 03:34:34 +00002045 Table *pTab = 0; /* Table to be indexed */
danielk1977d8123362004-06-12 09:25:12 +00002046 Index *pIndex = 0; /* The index to be created */
drh75897232000-05-29 14:26:00 +00002047 char *zName = 0;
drhbeae3192001-09-22 18:12:08 +00002048 int i, j;
drhf26e09c2003-05-31 16:21:12 +00002049 Token nullId; /* Fake token for an empty ID list */
2050 DbFixer sFix; /* For assigning database names to pTable */
drh9bb575f2004-09-06 17:24:11 +00002051 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002052
danielk1977cbb18d22004-05-28 11:37:27 +00002053 int iDb; /* Index of the database that is being written */
2054 Token *pName = 0; /* Unqualified name of the index to create */
2055
danielk197724b03fd2004-05-10 10:34:34 +00002056 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
drhdaffd0e2001-04-11 14:28:42 +00002057
drh75897232000-05-29 14:26:00 +00002058 /*
2059 ** Find the table that is to be indexed. Return early if not found.
2060 */
danielk1977cbb18d22004-05-28 11:37:27 +00002061 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002062
2063 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002064 ** to search for the table. 'Fix' the table name to this db
2065 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002066 */
2067 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002068 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002069 if( iDb<0 ) goto exit_create_index;
2070
danielk197753c0f742005-03-29 03:10:59 +00002071#ifndef SQLITE_OMIT_TEMPDB
danielk1977ef2cb632004-05-29 02:37:19 +00002072 /* If the index name was unqualified, check if the the table
2073 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002074 */
danielk1977ef2cb632004-05-29 02:37:19 +00002075 pTab = sqlite3SrcListLookup(pParse, pTblName);
2076 if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){
2077 iDb = 1;
2078 }
danielk197753c0f742005-03-29 03:10:59 +00002079#endif
danielk1977ef2cb632004-05-29 02:37:19 +00002080
2081 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2082 sqlite3FixSrcList(&sFix, pTblName)
2083 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002084 goto exit_create_index;
2085 }
danielk1977ef2cb632004-05-29 02:37:19 +00002086 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2087 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002088 if( !pTab ) goto exit_create_index;
danielk1977ef2cb632004-05-29 02:37:19 +00002089 assert( iDb==pTab->iDb );
drh75897232000-05-29 14:26:00 +00002090 }else{
drhe3c41372001-09-17 20:25:58 +00002091 assert( pName==0 );
drh75897232000-05-29 14:26:00 +00002092 pTab = pParse->pNewTable;
danielk1977cbb18d22004-05-28 11:37:27 +00002093 iDb = pTab->iDb;
drh75897232000-05-29 14:26:00 +00002094 }
danielk1977cbb18d22004-05-28 11:37:27 +00002095
drh75897232000-05-29 14:26:00 +00002096 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002097 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002098 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002099 goto exit_create_index;
2100 }
danielk1977576ec6b2005-01-21 11:55:25 +00002101#ifndef SQLITE_OMIT_VIEW
drha76b5df2002-02-23 02:32:10 +00002102 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002103 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002104 goto exit_create_index;
2105 }
danielk1977576ec6b2005-01-21 11:55:25 +00002106#endif
drh75897232000-05-29 14:26:00 +00002107
2108 /*
2109 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002110 ** index or table with the same name.
2111 **
2112 ** Exception: If we are reading the names of permanent indices from the
2113 ** sqlite_master table (because some other process changed the schema) and
2114 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002115 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002116 **
2117 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002118 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2119 ** own name.
drh75897232000-05-29 14:26:00 +00002120 */
danielk1977d8123362004-06-12 09:25:12 +00002121 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002122 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002123 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002124 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002125 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002126 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002127 }
danielk1977d8123362004-06-12 09:25:12 +00002128 if( !db->init.busy ){
2129 Index *pISameName; /* Another index with the same name */
2130 Table *pTSameName; /* A table with same name as the index */
danielk19778a414492004-06-29 08:59:35 +00002131 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002132 if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName))!=0 ){
2133 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2134 goto exit_create_index;
2135 }
2136 if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 ){
2137 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2138 goto exit_create_index;
2139 }
drhe3c41372001-09-17 20:25:58 +00002140 }
danielk1977a21c6b62005-01-24 10:25:59 +00002141 }else{
drhadbca9c2001-09-27 15:11:53 +00002142 char zBuf[30];
2143 int n;
2144 Index *pLoop;
2145 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002146 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002147 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002148 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002149 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002150 }
2151
drhe5f9c642003-01-13 23:27:31 +00002152 /* Check for authorization to create an index.
2153 */
2154#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002155 {
danielk197753c0f742005-03-29 03:10:59 +00002156 const char *zDb = db->aDb[iDb].zName;
2157 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002158 goto exit_create_index;
2159 }
2160 i = SQLITE_CREATE_INDEX;
danielk197753c0f742005-03-29 03:10:59 +00002161 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002162 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002163 goto exit_create_index;
2164 }
drhe5f9c642003-01-13 23:27:31 +00002165 }
2166#endif
2167
drh75897232000-05-29 14:26:00 +00002168 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002169 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002170 ** So create a fake list to simulate this.
2171 */
2172 if( pList==0 ){
drh7020f652000-06-03 18:06:52 +00002173 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drh75897232000-05-29 14:26:00 +00002174 nullId.n = strlen(nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002175 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002176 if( pList==0 ) goto exit_create_index;
2177 }
2178
2179 /*
2180 ** Allocate the index structure.
2181 */
drh17a18f22005-07-23 14:52:12 +00002182 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 + sizeof(int) +
drh497e4462005-07-23 03:18:40 +00002183 (sizeof(int)*2 + sizeof(CollSeq*))*pList->nExpr );
danielk1977e94ddc92005-03-21 03:53:38 +00002184 if( sqlite3_malloc_failed ) goto exit_create_index;
danielk19770202b292004-06-09 09:55:16 +00002185 pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
drh497e4462005-07-23 03:18:40 +00002186 pIndex->aiRowEst = &pIndex->aiColumn[pList->nExpr];
drh17a18f22005-07-23 14:52:12 +00002187 pIndex->zName = (char*)&pIndex->aiRowEst[pList->nExpr+1];
drh75897232000-05-29 14:26:00 +00002188 strcpy(pIndex->zName, zName);
2189 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002190 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002191 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002192 pIndex->autoIndex = pName==0;
danielk1977cbb18d22004-05-28 11:37:27 +00002193 pIndex->iDb = iDb;
drh75897232000-05-29 14:26:00 +00002194
drh1ccde152000-06-17 13:12:39 +00002195 /* Scan the names of the columns of the table to be indexed and
2196 ** load the column indices into the Index structure. Report an error
2197 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002198 */
danielk19770202b292004-06-09 09:55:16 +00002199 for(i=0; i<pList->nExpr; i++){
drh75897232000-05-29 14:26:00 +00002200 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002201 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002202 }
2203 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002204 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhf7a9e1a2004-02-22 18:40:56 +00002205 pTab->zName, pList->a[i].zName);
drh75897232000-05-29 14:26:00 +00002206 goto exit_create_index;
2207 }
drh967e8b72000-06-21 13:59:10 +00002208 pIndex->aiColumn[i] = j;
danielk19770202b292004-06-09 09:55:16 +00002209 if( pList->a[i].pExpr ){
2210 assert( pList->a[i].pExpr->pColl );
2211 pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
2212 }else{
2213 pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
2214 }
2215 assert( pIndex->keyInfo.aColl[i] );
danielk19777cedc8d2004-06-10 10:50:08 +00002216 if( !db->init.busy &&
2217 sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i])
2218 ){
2219 goto exit_create_index;
2220 }
drh75897232000-05-29 14:26:00 +00002221 }
danielk19770202b292004-06-09 09:55:16 +00002222 pIndex->keyInfo.nField = pList->nExpr;
drh51147ba2005-07-23 22:59:55 +00002223 sqlite3DefaultRowEst(pIndex);
drh75897232000-05-29 14:26:00 +00002224
danielk1977d8123362004-06-12 09:25:12 +00002225 if( pTab==pParse->pNewTable ){
2226 /* This routine has been called to create an automatic index as a
2227 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2228 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2229 ** i.e. one of:
2230 **
2231 ** CREATE TABLE t(x PRIMARY KEY, y);
2232 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2233 **
2234 ** Either way, check to see if the table already has such an index. If
2235 ** so, don't bother creating this one. This only applies to
2236 ** automatically created indices. Users can do as they wish with
2237 ** explicit indices.
2238 */
2239 Index *pIdx;
2240 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2241 int k;
2242 assert( pIdx->onError!=OE_None );
2243 assert( pIdx->autoIndex );
2244 assert( pIndex->onError!=OE_None );
2245
2246 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2247 for(k=0; k<pIdx->nColumn; k++){
2248 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2249 if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break;
2250 }
2251 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002252 if( pIdx->onError!=pIndex->onError ){
2253 /* This constraint creates the same index as a previous
2254 ** constraint specified somewhere in the CREATE TABLE statement.
2255 ** However the ON CONFLICT clauses are different. If both this
2256 ** constraint and the previous equivalent constraint have explicit
2257 ** ON CONFLICT clauses this is an error. Otherwise, use the
2258 ** explicitly specified behaviour for the index.
2259 */
2260 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2261 sqlite3ErrorMsg(pParse,
2262 "conflicting ON CONFLICT clauses specified", 0);
2263 }
2264 if( pIdx->onError==OE_Default ){
2265 pIdx->onError = pIndex->onError;
2266 }
2267 }
danielk1977d8123362004-06-12 09:25:12 +00002268 goto exit_create_index;
2269 }
2270 }
2271 }
2272
drh75897232000-05-29 14:26:00 +00002273 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002274 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002275 */
drh234c39d2004-07-24 03:30:47 +00002276 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002277 Index *p;
danielk19774adee202004-05-08 08:23:19 +00002278 p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash,
drh3c8bf552003-07-01 18:13:14 +00002279 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002280 if( p ){
2281 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002282 goto exit_create_index;
2283 }
drh5e00f6c2001-09-13 13:46:56 +00002284 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002285 if( pTblName!=0 ){
2286 pIndex->tnum = db->init.newTnum;
2287 }
drhd78eeee2001-09-13 16:18:53 +00002288 }
2289
drh1d85d932004-02-14 23:05:52 +00002290 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002291 ** involves writing the index into the master table and filling in the
2292 ** index with the current table contents.
2293 **
drh1d85d932004-02-14 23:05:52 +00002294 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2295 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002296 ** CREATE INDEX statements are read out of the master table. In
2297 ** the latter case the index already exists on disk, which is why
2298 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002299 **
danielk1977cbb18d22004-05-28 11:37:27 +00002300 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002301 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2302 ** has just been created, it contains no data and the index initialization
2303 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002304 */
drh1d85d932004-02-14 23:05:52 +00002305 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002306 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002307 char *zStmt;
2308 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002309
danielk19774adee202004-05-08 08:23:19 +00002310 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002311 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002312
2313 /* Create the rootpage for the index
2314 */
drhaee128d2005-02-14 20:48:18 +00002315 sqlite3BeginWriteOperation(pParse, 1, iDb);
drh234c39d2004-07-24 03:30:47 +00002316 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002317 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2318
2319 /* Gather the complete text of the CREATE INDEX statement into
2320 ** the zStmt variable
2321 */
drhe0bc4042002-06-25 01:09:11 +00002322 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002323 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002324 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002325 onError==OE_None ? "" : " UNIQUE",
drh97903fe2005-05-24 20:19:57 +00002326 pEnd->z - pName->z + 1,
drh063336a2004-11-05 20:58:39 +00002327 pName->z);
2328 }else{
2329 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002330 /* zStmt = sqlite3MPrintf(""); */
2331 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002332 }
drh063336a2004-11-05 20:58:39 +00002333
2334 /* Add an entry in sqlite_master for this index
2335 */
2336 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002337 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002338 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2339 pIndex->zName,
2340 pTab->zName,
2341 zStmt
2342 );
2343 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2344 sqliteFree(zStmt);
2345
danielk1977a21c6b62005-01-24 10:25:59 +00002346 /* Fill the index with data and reparse the schema. Code an OP_Expire
2347 ** to invalidate all pre-compiled statements.
drh063336a2004-11-05 20:58:39 +00002348 */
danielk1977cbb18d22004-05-28 11:37:27 +00002349 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002350 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002351 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002352 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2353 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
danielk1977a21c6b62005-01-24 10:25:59 +00002354 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +00002355 }
drh75897232000-05-29 14:26:00 +00002356 }
2357
danielk1977d8123362004-06-12 09:25:12 +00002358 /* When adding an index to the list of indices for a table, make
2359 ** sure all indices labeled OE_Replace come after all those labeled
2360 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2361 ** and INSERT.
2362 */
drh234c39d2004-07-24 03:30:47 +00002363 if( db->init.busy || pTblName==0 ){
2364 if( onError!=OE_Replace || pTab->pIndex==0
2365 || pTab->pIndex->onError==OE_Replace){
2366 pIndex->pNext = pTab->pIndex;
2367 pTab->pIndex = pIndex;
2368 }else{
2369 Index *pOther = pTab->pIndex;
2370 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2371 pOther = pOther->pNext;
2372 }
2373 pIndex->pNext = pOther->pNext;
2374 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002375 }
drh234c39d2004-07-24 03:30:47 +00002376 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002377 }
danielk1977d8123362004-06-12 09:25:12 +00002378
drh75897232000-05-29 14:26:00 +00002379 /* Clean up before exiting */
2380exit_create_index:
drh956bc922004-07-24 17:38:29 +00002381 if( pIndex ){
2382 freeIndex(pIndex);
2383 }
danielk19770202b292004-06-09 09:55:16 +00002384 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002385 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002386 sqliteFree(zName);
2387 return;
2388}
2389
2390/*
drh51147ba2005-07-23 22:59:55 +00002391** Fill the Index.aiRowEst[] array with default information - information
2392** to be used when we have no ANALYZE command to run.
drh28c4cf42005-07-27 20:41:43 +00002393**
2394** aiRowEst[0] is suppose to contain the number of elements in the index.
2395** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
2396** number of rows in the table that match any particular value of the
2397** first column of the index. aiRowEst[2] is an estimate of the number
2398** of rows that match any particular combiniation of the first 2 columns
2399** of the index. And so forth. It must always be the case that
2400*
2401** aiRowEst[N]<=aiRowEst[N-1]
2402** aiRowEst[N]>=1
2403**
2404** Apart from that, we have little to go on besides intuition as to
2405** how aiRowEst[] should be initialized. The numbers generated here
2406** are based on typical values found in actual indices.
drh51147ba2005-07-23 22:59:55 +00002407*/
2408void sqlite3DefaultRowEst(Index *pIdx){
drh28c4cf42005-07-27 20:41:43 +00002409 int *a = pIdx->aiRowEst;
drh51147ba2005-07-23 22:59:55 +00002410 int i;
drh28c4cf42005-07-27 20:41:43 +00002411 assert( a!=0 );
2412 a[0] = 1000000;
2413 switch( pIdx->nColumn ){
2414 case 1: {
2415 a[1] = 20;
2416 break;
2417 }
2418 case 2: {
2419 a[1] = 350;
2420 a[2] = 20;
2421 break;
2422 }
2423 default: {
2424 a[1] = 1250;
2425 a[2] = 350;
2426 a[3] = 20;
2427 for(i=pIdx->nColumn; i>=4; i--){
2428 a[i] = 10;
2429 }
2430 }
2431 }
2432 if( pIdx->onError!=OE_None ){
2433 a[pIdx->nColumn] = 1;
drh51147ba2005-07-23 22:59:55 +00002434 }
2435}
2436
2437/*
drh74e24cd2002-01-09 03:19:59 +00002438** This routine will drop an existing named index. This routine
2439** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002440*/
danielk19774adee202004-05-08 08:23:19 +00002441void sqlite3DropIndex(Parse *pParse, SrcList *pName){
drh75897232000-05-29 14:26:00 +00002442 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002443 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002444 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002445
danielk1977d5d56522005-03-16 12:15:20 +00002446 if( pParse->nErr || sqlite3_malloc_failed ){
2447 goto exit_drop_index;
2448 }
drhd24cc422003-03-27 12:51:24 +00002449 assert( pName->nSrc==1 );
danielk1977d5d56522005-03-16 12:15:20 +00002450 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
2451 goto exit_drop_index;
2452 }
danielk19774adee202004-05-08 08:23:19 +00002453 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002454 if( pIndex==0 ){
danielk19774adee202004-05-08 08:23:19 +00002455 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
drha6ecd332004-06-10 00:29:09 +00002456 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002457 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002458 }
drh485b39b2002-07-13 03:11:52 +00002459 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002460 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002461 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002462 goto exit_drop_index;
2463 }
drhe5f9c642003-01-13 23:27:31 +00002464#ifndef SQLITE_OMIT_AUTHORIZATION
2465 {
2466 int code = SQLITE_DROP_INDEX;
2467 Table *pTab = pIndex->pTable;
drhe22a3342003-04-22 20:30:37 +00002468 const char *zDb = db->aDb[pIndex->iDb].zName;
2469 const char *zTab = SCHEMA_TABLE(pIndex->iDb);
danielk19774adee202004-05-08 08:23:19 +00002470 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002471 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002472 }
danielk197753c0f742005-03-29 03:10:59 +00002473 if( !OMIT_TEMPDB && pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002474 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002475 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002476 }
drhed6c8672003-01-12 18:02:16 +00002477 }
drhe5f9c642003-01-13 23:27:31 +00002478#endif
drh75897232000-05-29 14:26:00 +00002479
2480 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002481 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002482 if( v ){
drhb17131a2004-11-05 22:18:49 +00002483 int iDb = pIndex->iDb;
2484 sqlite3NestedParse(pParse,
2485 "DELETE FROM %Q.%s WHERE name=%Q",
2486 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2487 pIndex->zName
2488 );
2489 sqlite3ChangeCookie(db, v, iDb);
2490 destroyRootPage(pParse, pIndex->tnum, iDb);
2491 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002492 }
2493
drhd24cc422003-03-27 12:51:24 +00002494exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002495 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002496}
2497
2498/*
drh75897232000-05-29 14:26:00 +00002499** Append a new element to the given IdList. Create a new IdList if
2500** need be.
drhdaffd0e2001-04-11 14:28:42 +00002501**
2502** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002503*/
danielk19774adee202004-05-08 08:23:19 +00002504IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh75897232000-05-29 14:26:00 +00002505 if( pList==0 ){
2506 pList = sqliteMalloc( sizeof(IdList) );
2507 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002508 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002509 }
drh4305d102003-07-30 12:34:12 +00002510 if( pList->nId>=pList->nAlloc ){
drh6d4abfb2001-10-22 02:58:08 +00002511 struct IdList_item *a;
drh4305d102003-07-30 12:34:12 +00002512 pList->nAlloc = pList->nAlloc*2 + 5;
2513 a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
drh6d4abfb2001-10-22 02:58:08 +00002514 if( a==0 ){
danielk19774adee202004-05-08 08:23:19 +00002515 sqlite3IdListDelete(pList);
drhdaffd0e2001-04-11 14:28:42 +00002516 return 0;
drh75897232000-05-29 14:26:00 +00002517 }
drh6d4abfb2001-10-22 02:58:08 +00002518 pList->a = a;
drh75897232000-05-29 14:26:00 +00002519 }
2520 memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
drha99db3b2004-06-19 14:49:12 +00002521 pList->a[pList->nId].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002522 pList->nId++;
2523 return pList;
2524}
2525
2526/*
drhfe05af82005-07-21 03:14:59 +00002527** Delete an IdList.
2528*/
2529void sqlite3IdListDelete(IdList *pList){
2530 int i;
2531 if( pList==0 ) return;
2532 for(i=0; i<pList->nId; i++){
2533 sqliteFree(pList->a[i].zName);
2534 }
2535 sqliteFree(pList->a);
2536 sqliteFree(pList);
2537}
2538
2539/*
2540** Return the index in pList of the identifier named zId. Return -1
2541** if not found.
2542*/
2543int sqlite3IdListIndex(IdList *pList, const char *zName){
2544 int i;
2545 if( pList==0 ) return -1;
2546 for(i=0; i<pList->nId; i++){
2547 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
2548 }
2549 return -1;
2550}
2551
2552/*
drhad3cab52002-05-24 02:04:32 +00002553** Append a new table name to the given SrcList. Create a new SrcList if
2554** need be. A new entry is created in the SrcList even if pToken is NULL.
2555**
2556** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002557**
2558** If pDatabase is not null, it means that the table has an optional
2559** database name prefix. Like this: "database.table". The pDatabase
2560** points to the table name and the pTable points to the database name.
2561** The SrcList.a[].zName field is filled with the table name which might
2562** come from pTable (if pDatabase is NULL) or from pDatabase.
2563** SrcList.a[].zDatabase is filled with the database name from pTable,
2564** or with NULL if no database is specified.
2565**
2566** In other words, if call like this:
2567**
danielk19774adee202004-05-08 08:23:19 +00002568** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002569**
2570** Then B is a table name and the database name is unspecified. If called
2571** like this:
2572**
danielk19774adee202004-05-08 08:23:19 +00002573** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002574**
2575** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002576*/
danielk19774adee202004-05-08 08:23:19 +00002577SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002578 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002579 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002580 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002581 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002582 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002583 }
drh4305d102003-07-30 12:34:12 +00002584 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002585 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002586 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002587 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002588 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002589 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002590 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002591 return 0;
2592 }
drh113088e2003-03-20 01:16:58 +00002593 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002594 }
drha99db3b2004-06-19 14:49:12 +00002595 pItem = &pList->a[pList->nSrc];
2596 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002597 if( pDatabase && pDatabase->z==0 ){
2598 pDatabase = 0;
2599 }
2600 if( pDatabase && pTable ){
2601 Token *pTemp = pDatabase;
2602 pDatabase = pTable;
2603 pTable = pTemp;
2604 }
drha99db3b2004-06-19 14:49:12 +00002605 pItem->zName = sqlite3NameFromToken(pTable);
2606 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2607 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002608 pList->nSrc++;
2609 return pList;
2610}
2611
2612/*
drh63eb5f22003-04-29 16:20:44 +00002613** Assign cursors to all tables in a SrcList
2614*/
danielk19774adee202004-05-08 08:23:19 +00002615void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002616 int i;
drh9b3187e2005-01-18 14:45:47 +00002617 struct SrcList_item *pItem;
2618 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
2619 if( pItem->iCursor>=0 ) break;
2620 pItem->iCursor = pParse->nTab++;
2621 if( pItem->pSelect ){
2622 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
drh63eb5f22003-04-29 16:20:44 +00002623 }
2624 }
2625}
2626
2627/*
drh75897232000-05-29 14:26:00 +00002628** Add an alias to the last identifier on the given identifier list.
2629*/
danielk19774adee202004-05-08 08:23:19 +00002630void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002631 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002632 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002633 }
2634}
2635
2636/*
drhad3cab52002-05-24 02:04:32 +00002637** Delete an entire SrcList including all its substructure.
2638*/
danielk19774adee202004-05-08 08:23:19 +00002639void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002640 int i;
drhbe5c89a2004-07-26 00:31:09 +00002641 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002642 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002643 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2644 sqliteFree(pItem->zDatabase);
2645 sqliteFree(pItem->zName);
2646 sqliteFree(pItem->zAlias);
drhed8a3bb2005-06-06 21:19:56 +00002647 sqlite3DeleteTable(0, pItem->pTab);
drhbe5c89a2004-07-26 00:31:09 +00002648 sqlite3SelectDelete(pItem->pSelect);
2649 sqlite3ExprDelete(pItem->pOn);
2650 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002651 }
drh75897232000-05-29 14:26:00 +00002652 sqliteFree(pList);
2653}
2654
drh982cef72000-05-30 16:27:03 +00002655/*
drhc4a3c772001-04-04 11:48:57 +00002656** Begin a transaction
2657*/
drh684917c2004-10-05 02:41:42 +00002658void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002659 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002660 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002661 int i;
drh5e00f6c2001-09-13 13:46:56 +00002662
drh001bbcb2003-03-19 03:14:00 +00002663 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002664 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002665 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002666
2667 v = sqlite3GetVdbe(pParse);
2668 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002669 if( type!=TK_DEFERRED ){
2670 for(i=0; i<db->nDb; i++){
2671 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2672 }
2673 }
danielk19771d850a72004-05-31 08:26:49 +00002674 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002675}
2676
2677/*
2678** Commit a transaction
2679*/
danielk19774adee202004-05-08 08:23:19 +00002680void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002681 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002682 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002683
drh001bbcb2003-03-19 03:14:00 +00002684 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002685 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002686 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002687
2688 v = sqlite3GetVdbe(pParse);
2689 if( v ){
2690 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002691 }
drhc4a3c772001-04-04 11:48:57 +00002692}
2693
2694/*
2695** Rollback a transaction
2696*/
danielk19774adee202004-05-08 08:23:19 +00002697void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002698 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002699 Vdbe *v;
2700
drh001bbcb2003-03-19 03:14:00 +00002701 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002702 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002703 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002704
danielk19774adee202004-05-08 08:23:19 +00002705 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002706 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002707 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002708 }
drhc4a3c772001-04-04 11:48:57 +00002709}
drhf57b14a2001-09-14 18:54:08 +00002710
2711/*
drhdc3ff9c2004-08-18 02:10:15 +00002712** Make sure the TEMP database is open and available for use. Return
2713** the number of errors. Leave any error messages in the pParse structure.
2714*/
2715static int sqlite3OpenTempDatabase(Parse *pParse){
2716 sqlite3 *db = pParse->db;
2717 if( db->aDb[1].pBt==0 && !pParse->explain ){
2718 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2719 if( rc!=SQLITE_OK ){
2720 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2721 "file for storing temporary tables");
2722 pParse->rc = rc;
2723 return 1;
2724 }
2725 if( db->flags & !db->autoCommit ){
2726 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2727 if( rc!=SQLITE_OK ){
2728 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2729 "the temporary database file");
2730 pParse->rc = rc;
2731 return 1;
2732 }
2733 }
2734 }
2735 return 0;
2736}
2737
2738/*
drh80242052004-06-09 00:48:12 +00002739** Generate VDBE code that will verify the schema cookie and start
2740** a read-transaction for all named database files.
2741**
2742** It is important that all schema cookies be verified and all
2743** read transactions be started before anything else happens in
2744** the VDBE program. But this routine can be called after much other
2745** code has been generated. So here is what we do:
2746**
drhc275b4e2004-07-19 17:25:24 +00002747** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002748** will jump to a subroutine at the end of the program. Then we
2749** record every database that needs its schema verified in the
2750** pParse->cookieMask field. Later, after all other code has been
2751** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002752** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002753** will be made to point to that subroutine. The generation of the
2754** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002755**
2756** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2757** schema on any databases. This can be used to position the OP_Goto
2758** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00002759*/
danielk19774adee202004-05-08 08:23:19 +00002760void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00002761 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00002762 Vdbe *v;
2763 int mask;
2764
2765 v = sqlite3GetVdbe(pParse);
2766 if( v==0 ) return; /* This only happens if there was a prior error */
2767 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00002768 if( pParse->cookieGoto==0 ){
2769 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00002770 }
drhc275b4e2004-07-19 17:25:24 +00002771 if( iDb>=0 ){
2772 assert( iDb<db->nDb );
2773 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
2774 assert( iDb<32 );
2775 mask = 1<<iDb;
2776 if( (pParse->cookieMask & mask)==0 ){
2777 pParse->cookieMask |= mask;
2778 pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
danielk197753c0f742005-03-29 03:10:59 +00002779 if( !OMIT_TEMPDB && iDb==1 ){
drhdc3ff9c2004-08-18 02:10:15 +00002780 sqlite3OpenTempDatabase(pParse);
2781 }
drhc275b4e2004-07-19 17:25:24 +00002782 }
drh001bbcb2003-03-19 03:14:00 +00002783 }
drh001bbcb2003-03-19 03:14:00 +00002784}
2785
2786/*
drh1c928532002-01-31 15:54:21 +00002787** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00002788** might change the database.
2789**
2790** This routine starts a new transaction if we are not already within
2791** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00002792** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00002793** be set for operations that might fail (due to a constraint) part of
2794** the way through and which will need to undo some writes without having to
2795** rollback the whole transaction. For operations where all constraints
2796** can be checked before any changes are made to the database, it is never
2797** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00002798**
drh8bf8dc92003-05-17 17:35:10 +00002799** Only database iDb and the temp database are made writable by this call.
2800** If iDb==0, then the main and temp databases are made writable. If
2801** iDb==1 then only the temp database is made writable. If iDb>1 then the
2802** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00002803*/
drh7f0f12e2004-05-21 13:39:50 +00002804void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00002805 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00002806 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00002807 sqlite3CodeVerifySchema(pParse, iDb);
2808 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00002809 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00002810 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00002811 }
danielk197753c0f742005-03-29 03:10:59 +00002812 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00002813 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00002814 }
2815}
2816
drh4343fea2004-11-05 23:46:15 +00002817/*
2818** Check to see if pIndex uses the collating sequence pColl. Return
2819** true if it does and false if it does not.
2820*/
2821#ifndef SQLITE_OMIT_REINDEX
2822static int collationMatch(CollSeq *pColl, Index *pIndex){
2823 int n = pIndex->keyInfo.nField;
2824 CollSeq **pp = pIndex->keyInfo.aColl;
2825 while( n-- ){
2826 if( *pp==pColl ) return 1;
2827 pp++;
2828 }
2829 return 0;
2830}
2831#endif
2832
2833/*
2834** Recompute all indices of pTab that use the collating sequence pColl.
2835** If pColl==0 then recompute all indices of pTab.
2836*/
2837#ifndef SQLITE_OMIT_REINDEX
2838void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){
2839 Index *pIndex; /* An index associated with pTab */
2840
2841 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
2842 if( pColl==0 || collationMatch(pColl,pIndex) ){
2843 sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
2844 sqlite3RefillIndex(pParse, pIndex, -1);
2845 }
2846 }
2847}
2848#endif
2849
2850/*
2851** Recompute all indices of all tables in all databases where the
2852** indices use the collating sequence pColl. If pColl==0 then recompute
2853** all indices everywhere.
2854*/
2855#ifndef SQLITE_OMIT_REINDEX
2856void reindexDatabases(Parse *pParse, CollSeq *pColl){
2857 Db *pDb; /* A single database */
2858 int iDb; /* The database index number */
2859 sqlite3 *db = pParse->db; /* The database connection */
2860 HashElem *k; /* For looping over tables in pDb */
2861 Table *pTab; /* A table in the database */
2862
2863 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
2864 if( pDb==0 ) continue;
drhff2d5ea2005-07-23 00:41:48 +00002865 for(k=sqliteHashFirst(&pDb->tblHash); k; k=sqliteHashNext(k)){
drh4343fea2004-11-05 23:46:15 +00002866 pTab = (Table*)sqliteHashData(k);
2867 reindexTable(pParse, pTab, pColl);
2868 }
2869 }
2870}
2871#endif
2872
2873/*
drheee46cf2004-11-06 00:02:48 +00002874** Generate code for the REINDEX command.
2875**
2876** REINDEX -- 1
2877** REINDEX <collation> -- 2
2878** REINDEX ?<database>.?<tablename> -- 3
2879** REINDEX ?<database>.?<indexname> -- 4
2880**
2881** Form 1 causes all indices in all attached databases to be rebuilt.
2882** Form 2 rebuilds all indices in all databases that use the named
2883** collating function. Forms 3 and 4 rebuild the named index or all
2884** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00002885*/
2886#ifndef SQLITE_OMIT_REINDEX
2887void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
2888 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
2889 char *z; /* Name of a table or index */
2890 const char *zDb; /* Name of the database */
2891 Table *pTab; /* A table in the database */
2892 Index *pIndex; /* An index associated with pTab */
2893 int iDb; /* The database index number */
2894 sqlite3 *db = pParse->db; /* The database connection */
2895 Token *pObjName; /* Name of the table or index to be reindexed */
2896
danielk197733a5edc2005-01-27 00:22:02 +00002897 /* Read the database schema. If an error occurs, leave an error message
2898 ** and code in pParse and return NULL. */
2899 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
danielk1977e63739a2005-01-27 00:33:37 +00002900 return;
danielk197733a5edc2005-01-27 00:22:02 +00002901 }
2902
drhe497f002004-11-07 13:01:49 +00002903 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002904 reindexDatabases(pParse, 0);
2905 return;
drhe497f002004-11-07 13:01:49 +00002906 }else if( pName2==0 || pName2->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002907 pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0);
2908 if( pColl ){
2909 reindexDatabases(pParse, pColl);
2910 return;
2911 }
2912 }
2913 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
2914 if( iDb<0 ) return;
2915 z = sqlite3NameFromToken(pObjName);
2916 zDb = db->aDb[iDb].zName;
2917 pTab = sqlite3FindTable(db, z, zDb);
2918 if( pTab ){
2919 reindexTable(pParse, pTab, 0);
2920 sqliteFree(z);
2921 return;
2922 }
2923 pIndex = sqlite3FindIndex(db, z, zDb);
2924 sqliteFree(z);
2925 if( pIndex ){
2926 sqlite3BeginWriteOperation(pParse, 0, iDb);
2927 sqlite3RefillIndex(pParse, pIndex, -1);
2928 return;
2929 }
2930 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
2931}
2932#endif