blob: 6bfa9294927e2371af8255e46f5fdd12db2f8886 [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**
drh23bf66d2004-12-14 03:34:34 +000025** $Id: build.c,v 1.290 2004/12/14 03:34:34 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;
drh80242052004-06-09 00:48:12 +000055
56 /* Begin by generating some termination code at the end of the
57 ** vdbe program
58 */
59 db = pParse->db;
60 v = sqlite3GetVdbe(pParse);
61 if( v ){
62 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
drh0e3d7472004-06-19 17:33:07 +000063
64 /* The cookie mask contains one bit for each database file open.
65 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
66 ** set for each database that is used. Generate code to start a
67 ** transaction on each used database and to verify the schema cookie
68 ** on each used database.
69 */
drhc275b4e2004-07-19 17:25:24 +000070 if( pParse->cookieGoto>0 ){
drh80242052004-06-09 00:48:12 +000071 u32 mask;
72 int iDb;
drhc275b4e2004-07-19 17:25:24 +000073 sqlite3VdbeChangeP2(v, pParse->cookieGoto-1, sqlite3VdbeCurrentAddr(v));
drh80242052004-06-09 00:48:12 +000074 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
75 if( (mask & pParse->cookieMask)==0 ) continue;
76 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
drhc275b4e2004-07-19 17:25:24 +000077 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
drh80242052004-06-09 00:48:12 +000078 }
drhc275b4e2004-07-19 17:25:24 +000079 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
drh80242052004-06-09 00:48:12 +000080 }
drh80242052004-06-09 00:48:12 +000081
drh71c697e2004-08-08 23:39:19 +000082 /* Add a No-op that contains the complete text of the compiled SQL
83 ** statement as its P3 argument. This does not change the functionality
drhc16a03b2004-09-15 13:38:10 +000084 ** of the program.
85 **
drh23bf66d2004-12-14 03:34:34 +000086 ** This is used to implement sqlite3_trace().
drh71c697e2004-08-08 23:39:19 +000087 */
88 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
drh71c697e2004-08-08 23:39:19 +000089 }
90
drh3f7d4e42004-07-24 14:35:58 +000091
drh80242052004-06-09 00:48:12 +000092 /* Get the VDBE program ready for execution
93 */
drhb86ccfb2003-01-28 23:13:10 +000094 if( v && pParse->nErr==0 ){
95 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
danielk19774adee202004-05-08 08:23:19 +000096 sqlite3VdbeTrace(v, trace);
drh290c1942004-08-21 17:54:45 +000097 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
98 pParse->nTab+3, pParse->explain);
drh826fb5a2004-02-14 23:59:57 +000099 pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
drhd8bc7082000-06-07 23:51:50 +0000100 pParse->colNamesSet = 0;
drh826fb5a2004-02-14 23:59:57 +0000101 }else if( pParse->rc==SQLITE_OK ){
drh483750b2003-01-29 18:46:51 +0000102 pParse->rc = SQLITE_ERROR;
drh75897232000-05-29 14:26:00 +0000103 }
drha226d052002-09-25 19:04:07 +0000104 pParse->nTab = 0;
105 pParse->nMem = 0;
106 pParse->nSet = 0;
107 pParse->nAgg = 0;
drh7c972de2003-09-06 22:18:07 +0000108 pParse->nVar = 0;
drh80242052004-06-09 00:48:12 +0000109 pParse->cookieMask = 0;
drhc275b4e2004-07-19 17:25:24 +0000110 pParse->cookieGoto = 0;
drh75897232000-05-29 14:26:00 +0000111}
112
113/*
drh205f48e2004-11-05 00:43:11 +0000114** Run the parser and code generator recursively in order to generate
115** code for the SQL statement given onto the end of the pParse context
116** currently under construction. When the parser is run recursively
117** this way, the final OP_Halt is not appended and other initialization
118** and finalization steps are omitted because those are handling by the
119** outermost parser.
120**
121** Not everything is nestable. This facility is designed to permit
122** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
drhf1974842004-11-05 03:56:00 +0000123** care if you decide to try to use this routine for some other purposes.
drh205f48e2004-11-05 00:43:11 +0000124*/
125void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
126 va_list ap;
127 char *zSql;
128 int rc;
drhf1974842004-11-05 03:56:00 +0000129# define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
130 char saveBuf[SAVE_SZ];
131
drh205f48e2004-11-05 00:43:11 +0000132 if( pParse->nErr ) return;
133 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
134 va_start(ap, zFormat);
135 zSql = sqlite3VMPrintf(zFormat, ap);
136 va_end(ap);
drh73c42a12004-11-20 18:13:10 +0000137 if( zSql==0 ){
138 return; /* A malloc must have failed */
139 }
drh205f48e2004-11-05 00:43:11 +0000140 pParse->nested++;
drhf1974842004-11-05 03:56:00 +0000141 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
142 memset(&pParse->nVar, 0, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000143 rc = sqlite3RunParser(pParse, zSql, 0);
144 sqliteFree(zSql);
drhf1974842004-11-05 03:56:00 +0000145 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
drh205f48e2004-11-05 00:43:11 +0000146 pParse->nested--;
147}
148
149/*
danielk19778a414492004-06-29 08:59:35 +0000150** Locate the in-memory structure that describes a particular database
151** table given the name of that table and (optionally) the name of the
152** database containing the table. Return NULL if not found.
drha69d9162003-04-17 22:57:53 +0000153**
danielk19778a414492004-06-29 08:59:35 +0000154** If zDatabase is 0, all databases are searched for the table and the
155** first matching table is returned. (No checking for duplicate table
156** names is done.) The search order is TEMP first, then MAIN, then any
157** auxiliary databases added using the ATTACH command.
drhf26e09c2003-05-31 16:21:12 +0000158**
danielk19774adee202004-05-08 08:23:19 +0000159** See also sqlite3LocateTable().
drh75897232000-05-29 14:26:00 +0000160*/
drh9bb575f2004-09-06 17:24:11 +0000161Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
drhd24cc422003-03-27 12:51:24 +0000162 Table *p = 0;
163 int i;
drh645f63e2004-06-22 13:22:40 +0000164 assert( zName!=0 );
danielk19778a414492004-06-29 08:59:35 +0000165 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
166 for(i=0; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000167 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000168 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
169 p = sqlite3HashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000170 if( p ) break;
171 }
drh74e24cd2002-01-09 03:19:59 +0000172 return p;
drh75897232000-05-29 14:26:00 +0000173}
174
175/*
danielk19778a414492004-06-29 08:59:35 +0000176** Locate the in-memory structure that describes a particular database
177** table given the name of that table and (optionally) the name of the
178** database containing the table. Return NULL if not found. Also leave an
179** error message in pParse->zErrMsg.
drha69d9162003-04-17 22:57:53 +0000180**
danielk19778a414492004-06-29 08:59:35 +0000181** The difference between this routine and sqlite3FindTable() is that this
182** routine leaves an error message in pParse->zErrMsg where
183** sqlite3FindTable() does not.
drha69d9162003-04-17 22:57:53 +0000184*/
danielk19774adee202004-05-08 08:23:19 +0000185Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
drha69d9162003-04-17 22:57:53 +0000186 Table *p;
drhf26e09c2003-05-31 16:21:12 +0000187
danielk19778a414492004-06-29 08:59:35 +0000188 /* Read the database schema. If an error occurs, leave an error message
189 ** and code in pParse and return NULL. */
190 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
191 return 0;
192 }
193
danielk19774adee202004-05-08 08:23:19 +0000194 p = sqlite3FindTable(pParse->db, zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000195 if( p==0 ){
danielk19778a414492004-06-29 08:59:35 +0000196 if( zDbase ){
danielk19774adee202004-05-08 08:23:19 +0000197 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
198 }else if( sqlite3FindTable(pParse->db, zName, 0)!=0 ){
199 sqlite3ErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
drhf26e09c2003-05-31 16:21:12 +0000200 zName, zDbase);
drha69d9162003-04-17 22:57:53 +0000201 }else{
danielk19774adee202004-05-08 08:23:19 +0000202 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
drha69d9162003-04-17 22:57:53 +0000203 }
drha6ecd332004-06-10 00:29:09 +0000204 pParse->checkSchema = 1;
drha69d9162003-04-17 22:57:53 +0000205 }
206 return p;
207}
208
209/*
210** Locate the in-memory structure that describes
211** a particular index given the name of that index
212** and the name of the database that contains the index.
drhf57b3392001-10-08 13:22:32 +0000213** Return NULL if not found.
drhf26e09c2003-05-31 16:21:12 +0000214**
215** If zDatabase is 0, all databases are searched for the
216** table and the first matching index is returned. (No checking
217** for duplicate index names is done.) The search order is
218** TEMP first, then MAIN, then any auxiliary databases added
219** using the ATTACH command.
drh75897232000-05-29 14:26:00 +0000220*/
drh9bb575f2004-09-06 17:24:11 +0000221Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
drhd24cc422003-03-27 12:51:24 +0000222 Index *p = 0;
223 int i;
danielk19778a414492004-06-29 08:59:35 +0000224 assert( (db->flags & SQLITE_Initialized) || db->init.busy );
225 for(i=0; i<db->nDb; i++){
drh812d7a22003-03-27 13:50:00 +0000226 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
danielk19774adee202004-05-08 08:23:19 +0000227 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
228 p = sqlite3HashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
drhd24cc422003-03-27 12:51:24 +0000229 if( p ) break;
230 }
drh74e24cd2002-01-09 03:19:59 +0000231 return p;
drh75897232000-05-29 14:26:00 +0000232}
233
234/*
drh956bc922004-07-24 17:38:29 +0000235** Reclaim the memory used by an index
236*/
237static void freeIndex(Index *p){
238 sqliteFree(p->zColAff);
239 sqliteFree(p);
240}
241
242/*
drh75897232000-05-29 14:26:00 +0000243** Remove the given index from the index hash table, and free
244** its memory structures.
245**
drhd229ca92002-01-09 13:30:41 +0000246** The index is removed from the database hash tables but
247** it is not unlinked from the Table that it indexes.
drhdaffd0e2001-04-11 14:28:42 +0000248** Unlinking from the Table must be done by the calling function.
drh75897232000-05-29 14:26:00 +0000249*/
drh9bb575f2004-09-06 17:24:11 +0000250static void sqliteDeleteIndex(sqlite3 *db, Index *p){
drhd229ca92002-01-09 13:30:41 +0000251 Index *pOld;
drhd24cc422003-03-27 12:51:24 +0000252
drhd229ca92002-01-09 13:30:41 +0000253 assert( db!=0 && p->zName!=0 );
danielk19774adee202004-05-08 08:23:19 +0000254 pOld = sqlite3HashInsert(&db->aDb[p->iDb].idxHash, p->zName,
drhd24cc422003-03-27 12:51:24 +0000255 strlen(p->zName)+1, 0);
drhd229ca92002-01-09 13:30:41 +0000256 if( pOld!=0 && pOld!=p ){
danielk19774adee202004-05-08 08:23:19 +0000257 sqlite3HashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
drhd24cc422003-03-27 12:51:24 +0000258 strlen(pOld->zName)+1, pOld);
drh75897232000-05-29 14:26:00 +0000259 }
drh956bc922004-07-24 17:38:29 +0000260 freeIndex(p);
drh75897232000-05-29 14:26:00 +0000261}
262
263/*
drhbeae3192001-09-22 18:12:08 +0000264** Unlink the given index from its table, then remove
drhf57b3392001-10-08 13:22:32 +0000265** the index from the index hash table and free its memory
drh5e00f6c2001-09-13 13:46:56 +0000266** structures.
267*/
drh9bb575f2004-09-06 17:24:11 +0000268void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
drh956bc922004-07-24 17:38:29 +0000269 Index *pIndex;
270 int len;
271
272 len = strlen(zIdxName);
273 pIndex = sqlite3HashInsert(&db->aDb[iDb].idxHash, zIdxName, len+1, 0);
274 if( pIndex ){
275 if( pIndex->pTable->pIndex==pIndex ){
276 pIndex->pTable->pIndex = pIndex->pNext;
277 }else{
278 Index *p;
279 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
280 if( p && p->pNext==pIndex ){
281 p->pNext = pIndex->pNext;
282 }
drh5e00f6c2001-09-13 13:46:56 +0000283 }
drh956bc922004-07-24 17:38:29 +0000284 freeIndex(pIndex);
drh5e00f6c2001-09-13 13:46:56 +0000285 }
drh956bc922004-07-24 17:38:29 +0000286 db->flags |= SQLITE_InternChanges;
drh5e00f6c2001-09-13 13:46:56 +0000287}
288
289/*
drhe0bc4042002-06-25 01:09:11 +0000290** Erase all schema information from the in-memory hash tables of
drh234c39d2004-07-24 03:30:47 +0000291** a single database. This routine is called to reclaim memory
292** before the database closes. It is also called during a rollback
danielk1977e0d4b062004-06-28 01:11:46 +0000293** if there were schema changes during the transaction or if a
294** schema-cookie mismatch occurs.
drh1c2d8412003-03-31 00:30:47 +0000295**
296** If iDb<=0 then reset the internal schema tables for all database
297** files. If iDb>=2 then reset the internal schema for only the
jplyoncfa56842004-01-19 04:55:56 +0000298** single file indicated.
drh74e24cd2002-01-09 03:19:59 +0000299*/
drh9bb575f2004-09-06 17:24:11 +0000300void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
drhe0bc4042002-06-25 01:09:11 +0000301 HashElem *pElem;
302 Hash temp1;
303 Hash temp2;
drh1c2d8412003-03-31 00:30:47 +0000304 int i, j;
drhe0bc4042002-06-25 01:09:11 +0000305
drh1c2d8412003-03-31 00:30:47 +0000306 assert( iDb>=0 && iDb<db->nDb );
307 db->flags &= ~SQLITE_Initialized;
308 for(i=iDb; i<db->nDb; i++){
drhd24cc422003-03-27 12:51:24 +0000309 Db *pDb = &db->aDb[i];
310 temp1 = pDb->tblHash;
311 temp2 = pDb->trigHash;
danielk19774adee202004-05-08 08:23:19 +0000312 sqlite3HashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
313 sqlite3HashClear(&pDb->aFKey);
314 sqlite3HashClear(&pDb->idxHash);
drhd24cc422003-03-27 12:51:24 +0000315 for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
drh40e016e2004-11-04 14:47:11 +0000316 sqlite3DeleteTrigger((Trigger*)sqliteHashData(pElem));
drhd24cc422003-03-27 12:51:24 +0000317 }
danielk19774adee202004-05-08 08:23:19 +0000318 sqlite3HashClear(&temp2);
319 sqlite3HashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
drhd24cc422003-03-27 12:51:24 +0000320 for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
321 Table *pTab = sqliteHashData(pElem);
danielk19774adee202004-05-08 08:23:19 +0000322 sqlite3DeleteTable(db, pTab);
drhd24cc422003-03-27 12:51:24 +0000323 }
danielk19774adee202004-05-08 08:23:19 +0000324 sqlite3HashClear(&temp1);
drh2958a4e2004-11-12 03:56:15 +0000325 pDb->pSeqTab = 0;
drh8bf8dc92003-05-17 17:35:10 +0000326 DbClearProperty(db, i, DB_SchemaLoaded);
drh1c2d8412003-03-31 00:30:47 +0000327 if( iDb>0 ) return;
drh74e24cd2002-01-09 03:19:59 +0000328 }
drh1c2d8412003-03-31 00:30:47 +0000329 assert( iDb==0 );
330 db->flags &= ~SQLITE_InternChanges;
331
332 /* If one or more of the auxiliary database files has been closed,
333 ** then remove then from the auxiliary database list. We take the
334 ** opportunity to do this here since we have just deleted all of the
335 ** schema hash tables and therefore do not have to make any changes
336 ** to any of those tables.
337 */
drh4d189ca2004-02-12 18:46:38 +0000338 for(i=0; i<db->nDb; i++){
339 struct Db *pDb = &db->aDb[i];
340 if( pDb->pBt==0 ){
341 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
342 pDb->pAux = 0;
343 }
344 }
drh1c2d8412003-03-31 00:30:47 +0000345 for(i=j=2; i<db->nDb; i++){
drh4d189ca2004-02-12 18:46:38 +0000346 struct Db *pDb = &db->aDb[i];
347 if( pDb->pBt==0 ){
348 sqliteFree(pDb->zName);
349 pDb->zName = 0;
drh1c2d8412003-03-31 00:30:47 +0000350 continue;
351 }
352 if( j<i ){
drh8bf8dc92003-05-17 17:35:10 +0000353 db->aDb[j] = db->aDb[i];
drh1c2d8412003-03-31 00:30:47 +0000354 }
drh8bf8dc92003-05-17 17:35:10 +0000355 j++;
drh1c2d8412003-03-31 00:30:47 +0000356 }
357 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
358 db->nDb = j;
359 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
360 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
361 sqliteFree(db->aDb);
362 db->aDb = db->aDbStatic;
363 }
drhe0bc4042002-06-25 01:09:11 +0000364}
365
366/*
367** This routine is called whenever a rollback occurs. If there were
368** schema changes during the transaction, then we have to reset the
369** internal hash tables and reload them from disk.
370*/
drh9bb575f2004-09-06 17:24:11 +0000371void sqlite3RollbackInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000372 if( db->flags & SQLITE_InternChanges ){
danielk19774adee202004-05-08 08:23:19 +0000373 sqlite3ResetInternalSchema(db, 0);
drhe0bc4042002-06-25 01:09:11 +0000374 }
375}
376
377/*
378** This routine is called when a commit occurs.
379*/
drh9bb575f2004-09-06 17:24:11 +0000380void sqlite3CommitInternalChanges(sqlite3 *db){
drhe0bc4042002-06-25 01:09:11 +0000381 db->flags &= ~SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000382}
383
384/*
drh956bc922004-07-24 17:38:29 +0000385** Clear the column names from a table or view.
386*/
387static void sqliteResetColumnNames(Table *pTable){
388 int i;
389 Column *pCol;
390 assert( pTable!=0 );
391 for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
392 sqliteFree(pCol->zName);
danielk19777977a172004-11-09 12:44:37 +0000393 sqlite3ExprDelete(pCol->pDflt);
drh956bc922004-07-24 17:38:29 +0000394 sqliteFree(pCol->zType);
395 }
396 sqliteFree(pTable->aCol);
397 pTable->aCol = 0;
398 pTable->nCol = 0;
399}
400
401/*
drh75897232000-05-29 14:26:00 +0000402** Remove the memory data structures associated with the given
drh967e8b72000-06-21 13:59:10 +0000403** Table. No changes are made to disk by this routine.
drh75897232000-05-29 14:26:00 +0000404**
405** This routine just deletes the data structure. It does not unlink
drhc2eef3b2002-08-31 18:53:06 +0000406** the table data structure from the hash table. Nor does it remove
407** foreign keys from the sqlite.aFKey hash table. But it does destroy
408** memory structures of the indices and foreign keys associated with
409** the table.
drhdaffd0e2001-04-11 14:28:42 +0000410**
411** Indices associated with the table are unlinked from the "db"
412** data structure if db!=NULL. If db==NULL, indices attached to
413** the table are deleted, but it is assumed they have already been
414** unlinked.
drh75897232000-05-29 14:26:00 +0000415*/
drh9bb575f2004-09-06 17:24:11 +0000416void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
drh75897232000-05-29 14:26:00 +0000417 Index *pIndex, *pNext;
drhc2eef3b2002-08-31 18:53:06 +0000418 FKey *pFKey, *pNextFKey;
419
drh75897232000-05-29 14:26:00 +0000420 if( pTable==0 ) return;
drhc2eef3b2002-08-31 18:53:06 +0000421
422 /* Delete all indices associated with this table
423 */
424 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
425 pNext = pIndex->pNext;
drhd24cc422003-03-27 12:51:24 +0000426 assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
drhc2eef3b2002-08-31 18:53:06 +0000427 sqliteDeleteIndex(db, pIndex);
428 }
429
430 /* Delete all foreign keys associated with this table. The keys
431 ** should have already been unlinked from the db->aFKey hash table
432 */
433 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
434 pNextFKey = pFKey->pNextFrom;
drhd24cc422003-03-27 12:51:24 +0000435 assert( pTable->iDb<db->nDb );
danielk19774adee202004-05-08 08:23:19 +0000436 assert( sqlite3HashFind(&db->aDb[pTable->iDb].aFKey,
drhd24cc422003-03-27 12:51:24 +0000437 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
drhc2eef3b2002-08-31 18:53:06 +0000438 sqliteFree(pFKey);
439 }
440
441 /* Delete the Table structure itself.
442 */
drh956bc922004-07-24 17:38:29 +0000443 sqliteResetColumnNames(pTable);
drh6e142f52000-06-08 13:36:40 +0000444 sqliteFree(pTable->zName);
drh956bc922004-07-24 17:38:29 +0000445 sqliteFree(pTable->zColAff);
danielk19774adee202004-05-08 08:23:19 +0000446 sqlite3SelectDelete(pTable->pSelect);
drh75897232000-05-29 14:26:00 +0000447 sqliteFree(pTable);
448}
449
450/*
drh5edc3122001-09-13 21:53:09 +0000451** Unlink the given table from the hash tables and the delete the
drhc2eef3b2002-08-31 18:53:06 +0000452** table structure with all its indices and foreign keys.
drh5edc3122001-09-13 21:53:09 +0000453*/
drh9bb575f2004-09-06 17:24:11 +0000454void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
drh956bc922004-07-24 17:38:29 +0000455 Table *p;
drhc2eef3b2002-08-31 18:53:06 +0000456 FKey *pF1, *pF2;
drh956bc922004-07-24 17:38:29 +0000457 Db *pDb;
458
drhd229ca92002-01-09 13:30:41 +0000459 assert( db!=0 );
drh956bc922004-07-24 17:38:29 +0000460 assert( iDb>=0 && iDb<db->nDb );
461 assert( zTabName && zTabName[0] );
462 pDb = &db->aDb[iDb];
463 p = sqlite3HashInsert(&pDb->tblHash, zTabName, strlen(zTabName)+1, 0);
464 if( p ){
465 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
466 int nTo = strlen(pF1->zTo) + 1;
467 pF2 = sqlite3HashFind(&pDb->aFKey, pF1->zTo, nTo);
468 if( pF2==pF1 ){
469 sqlite3HashInsert(&pDb->aFKey, pF1->zTo, nTo, pF1->pNextTo);
470 }else{
471 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
472 if( pF2 ){
473 pF2->pNextTo = pF1->pNextTo;
474 }
drhc2eef3b2002-08-31 18:53:06 +0000475 }
476 }
drh956bc922004-07-24 17:38:29 +0000477 sqlite3DeleteTable(db, p);
drhc2eef3b2002-08-31 18:53:06 +0000478 }
drh956bc922004-07-24 17:38:29 +0000479 db->flags |= SQLITE_InternChanges;
drh74e24cd2002-01-09 03:19:59 +0000480}
481
482/*
drha99db3b2004-06-19 14:49:12 +0000483** Given a token, return a string that consists of the text of that
484** token with any quotations removed. Space to hold the returned string
485** is obtained from sqliteMalloc() and must be freed by the calling
486** function.
drh75897232000-05-29 14:26:00 +0000487**
drha99db3b2004-06-19 14:49:12 +0000488** Tokens are really just pointers into the original SQL text and so
489** are not \000 terminated and are not persistent. The returned string
490** is \000 terminated and is persistent.
drh75897232000-05-29 14:26:00 +0000491*/
drha99db3b2004-06-19 14:49:12 +0000492char *sqlite3NameFromToken(Token *pName){
493 char *zName;
494 if( pName ){
495 zName = sqliteStrNDup(pName->z, pName->n);
496 sqlite3Dequote(zName);
497 }else{
498 zName = 0;
499 }
drh75897232000-05-29 14:26:00 +0000500 return zName;
501}
502
503/*
danielk1977cbb18d22004-05-28 11:37:27 +0000504** Open the sqlite_master table stored in database number iDb for
505** writing. The table is opened using cursor 0.
drhe0bc4042002-06-25 01:09:11 +0000506*/
danielk1977cbb18d22004-05-28 11:37:27 +0000507void sqlite3OpenMasterTable(Vdbe *v, int iDb){
508 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
danielk19778e150812004-05-10 01:17:37 +0000509 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
danielk1977b4964b72004-05-18 01:23:38 +0000510 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
drhe0bc4042002-06-25 01:09:11 +0000511}
512
513/*
danielk1977cbb18d22004-05-28 11:37:27 +0000514** The token *pName contains the name of a database (either "main" or
515** "temp" or the name of an attached db). This routine returns the
516** index of the named database in db->aDb[], or -1 if the named db
517** does not exist.
518*/
drh23bf66d2004-12-14 03:34:34 +0000519static int findDb(sqlite3 *db, Token *pName){
drh73c42a12004-11-20 18:13:10 +0000520 int i; /* Database number */
521 int n; /* Number of characters in the name */
522 Db *pDb; /* A database whose name space is being searched */
523 char *zName; /* Name we are searching for */
524
525 zName = sqlite3NameFromToken(pName);
526 if( zName ){
527 n = strlen(zName);
528 for(pDb=db->aDb, i=0; i<db->nDb; i++, pDb++){
529 if( n==strlen(pDb->zName) && 0==sqlite3StrICmp(pDb->zName, zName) ){
530 sqliteFree(zName);
531 return i;
532 }
danielk1977cbb18d22004-05-28 11:37:27 +0000533 }
drh73c42a12004-11-20 18:13:10 +0000534 sqliteFree(zName);
danielk1977cbb18d22004-05-28 11:37:27 +0000535 }
536 return -1;
537}
538
drh0e3d7472004-06-19 17:33:07 +0000539/* The table or view or trigger name is passed to this routine via tokens
540** pName1 and pName2. If the table name was fully qualified, for example:
541**
542** CREATE TABLE xxx.yyy (...);
543**
544** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
545** the table name is not fully qualified, i.e.:
546**
547** CREATE TABLE yyy(...);
548**
549** Then pName1 is set to "yyy" and pName2 is "".
550**
551** This routine sets the *ppUnqual pointer to point at the token (pName1 or
552** pName2) that stores the unqualified table name. The index of the
553** database "xxx" is returned.
554*/
danielk1977ef2cb632004-05-29 02:37:19 +0000555int sqlite3TwoPartName(
drh0e3d7472004-06-19 17:33:07 +0000556 Parse *pParse, /* Parsing and code generating context */
drh90f5ecb2004-07-22 01:19:35 +0000557 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
drh0e3d7472004-06-19 17:33:07 +0000558 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
559 Token **pUnqual /* Write the unqualified object name here */
danielk1977cbb18d22004-05-28 11:37:27 +0000560){
drh0e3d7472004-06-19 17:33:07 +0000561 int iDb; /* Database holding the object */
danielk1977cbb18d22004-05-28 11:37:27 +0000562 sqlite3 *db = pParse->db;
563
564 if( pName2 && pName2->n>0 ){
565 assert( !db->init.busy );
566 *pUnqual = pName2;
567 iDb = findDb(db, pName1);
568 if( iDb<0 ){
569 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
570 pParse->nErr++;
571 return -1;
572 }
573 }else{
574 assert( db->init.iDb==0 || db->init.busy );
575 iDb = db->init.iDb;
576 *pUnqual = pName1;
577 }
578 return iDb;
579}
580
581/*
danielk1977d8123362004-06-12 09:25:12 +0000582** This routine is used to check if the UTF-8 string zName is a legal
583** unqualified name for a new schema object (table, index, view or
584** trigger). All names are legal except those that begin with the string
585** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
586** is reserved for internal use.
587*/
588int sqlite3CheckObjectName(Parse *pParse, const char *zName){
drhf1974842004-11-05 03:56:00 +0000589 if( !pParse->db->init.busy && pParse->nested==0
590 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danielk1977d8123362004-06-12 09:25:12 +0000591 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
592 return SQLITE_ERROR;
593 }
594 return SQLITE_OK;
595}
596
597/*
drh75897232000-05-29 14:26:00 +0000598** Begin constructing a new table representation in memory. This is
599** the first of several action routines that get called in response
drhd9b02572001-04-15 00:37:09 +0000600** to a CREATE TABLE statement. In particular, this routine is called
601** after seeing tokens "CREATE" and "TABLE" and the table name. The
drhf57b3392001-10-08 13:22:32 +0000602** pStart token is the CREATE and pName is the table name. The isTemp
drhe0bc4042002-06-25 01:09:11 +0000603** flag is true if the table should be stored in the auxiliary database
604** file instead of in the main database file. This is normally the case
605** when the "TEMP" or "TEMPORARY" keyword occurs in between
drhf57b3392001-10-08 13:22:32 +0000606** CREATE and TABLE.
drhd9b02572001-04-15 00:37:09 +0000607**
drhf57b3392001-10-08 13:22:32 +0000608** The new table record is initialized and put in pParse->pNewTable.
609** As more of the CREATE TABLE statement is parsed, additional action
610** routines will be called to add more information to this record.
danielk19774adee202004-05-08 08:23:19 +0000611** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
drhf57b3392001-10-08 13:22:32 +0000612** is called to complete the construction of the new table record.
drh75897232000-05-29 14:26:00 +0000613*/
danielk19774adee202004-05-08 08:23:19 +0000614void sqlite3StartTable(
drhe5f9c642003-01-13 23:27:31 +0000615 Parse *pParse, /* Parser context */
616 Token *pStart, /* The "CREATE" token */
danielk1977cbb18d22004-05-28 11:37:27 +0000617 Token *pName1, /* First part of the name of the table or view */
618 Token *pName2, /* Second part of the name of the table or view */
drhe5f9c642003-01-13 23:27:31 +0000619 int isTemp, /* True if this is a TEMP table */
620 int isView /* True if this is a VIEW */
621){
drh75897232000-05-29 14:26:00 +0000622 Table *pTable;
drhf57b3392001-10-08 13:22:32 +0000623 Index *pIdx;
drh23bf66d2004-12-14 03:34:34 +0000624 char *zName = 0; /* The name of the new table */
drh9bb575f2004-09-06 17:24:11 +0000625 sqlite3 *db = pParse->db;
drhadbca9c2001-09-27 15:11:53 +0000626 Vdbe *v;
danielk1977cbb18d22004-05-28 11:37:27 +0000627 int iDb; /* Database number to create the table in */
628 Token *pName; /* Unqualified name of the table to create */
drh75897232000-05-29 14:26:00 +0000629
danielk1977cbb18d22004-05-28 11:37:27 +0000630 /* The table or view name to create is passed to this routine via tokens
631 ** pName1 and pName2. If the table name was fully qualified, for example:
632 **
633 ** CREATE TABLE xxx.yyy (...);
634 **
635 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
636 ** the table name is not fully qualified, i.e.:
637 **
638 ** CREATE TABLE yyy(...);
639 **
640 ** Then pName1 is set to "yyy" and pName2 is "".
641 **
642 ** The call below sets the pName pointer to point at the token (pName1 or
643 ** pName2) that stores the unqualified table name. The variable iDb is
644 ** set to the index of the database that the table or view is to be
645 ** created in.
646 */
danielk1977ef2cb632004-05-29 02:37:19 +0000647 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +0000648 if( iDb<0 ) return;
649 if( isTemp && iDb>1 ){
650 /* If creating a temp table, the name may not be qualified */
651 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
danielk1977cbb18d22004-05-28 11:37:27 +0000652 return;
653 }
654 if( isTemp ) iDb = 1;
655
656 pParse->sNameToken = *pName;
drha99db3b2004-06-19 14:49:12 +0000657 zName = sqlite3NameFromToken(pName);
danielk1977e0048402004-06-15 16:51:01 +0000658 if( zName==0 ) return;
danielk1977d8123362004-06-12 09:25:12 +0000659 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drh23bf66d2004-12-14 03:34:34 +0000660 goto begin_table_error;
danielk1977d8123362004-06-12 09:25:12 +0000661 }
drh1d85d932004-02-14 23:05:52 +0000662 if( db->init.iDb==1 ) isTemp = 1;
drhe5f9c642003-01-13 23:27:31 +0000663#ifndef SQLITE_OMIT_AUTHORIZATION
drhd24cc422003-03-27 12:51:24 +0000664 assert( (isTemp & 1)==isTemp );
drhe5f9c642003-01-13 23:27:31 +0000665 {
666 int code;
danielk1977cbb18d22004-05-28 11:37:27 +0000667 char *zDb = db->aDb[iDb].zName;
danielk19774adee202004-05-08 08:23:19 +0000668 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000669 goto begin_table_error;
drhe22a3342003-04-22 20:30:37 +0000670 }
drhe5f9c642003-01-13 23:27:31 +0000671 if( isView ){
672 if( isTemp ){
673 code = SQLITE_CREATE_TEMP_VIEW;
674 }else{
675 code = SQLITE_CREATE_VIEW;
676 }
677 }else{
678 if( isTemp ){
679 code = SQLITE_CREATE_TEMP_TABLE;
680 }else{
681 code = SQLITE_CREATE_TABLE;
682 }
683 }
danielk19774adee202004-05-08 08:23:19 +0000684 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
drh23bf66d2004-12-14 03:34:34 +0000685 goto begin_table_error;
drhe5f9c642003-01-13 23:27:31 +0000686 }
687 }
688#endif
drhf57b3392001-10-08 13:22:32 +0000689
drhf57b3392001-10-08 13:22:32 +0000690 /* Make sure the new table name does not collide with an existing
danielk19773df6b252004-05-29 10:23:19 +0000691 ** index or table name in the same database. Issue an error message if
692 ** it does.
drhf57b3392001-10-08 13:22:32 +0000693 */
danielk19778a414492004-06-29 08:59:35 +0000694 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) return;
danielk19773df6b252004-05-29 10:23:19 +0000695 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
696 if( pTable ){
danielk19774adee202004-05-08 08:23:19 +0000697 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
drh23bf66d2004-12-14 03:34:34 +0000698 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000699 }
danielk19778a414492004-06-29 08:59:35 +0000700 if( (pIdx = sqlite3FindIndex(db, zName, 0))!=0 &&
701 ( iDb==0 || !db->init.busy) ){
danielk19774adee202004-05-08 08:23:19 +0000702 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
drh23bf66d2004-12-14 03:34:34 +0000703 goto begin_table_error;
drh75897232000-05-29 14:26:00 +0000704 }
705 pTable = sqliteMalloc( sizeof(Table) );
drh6d4abfb2001-10-22 02:58:08 +0000706 if( pTable==0 ){
danielk1977e0048402004-06-15 16:51:01 +0000707 pParse->rc = SQLITE_NOMEM;
708 pParse->nErr++;
drh23bf66d2004-12-14 03:34:34 +0000709 goto begin_table_error;
drh6d4abfb2001-10-22 02:58:08 +0000710 }
drh75897232000-05-29 14:26:00 +0000711 pTable->zName = zName;
drh75897232000-05-29 14:26:00 +0000712 pTable->nCol = 0;
drh7020f652000-06-03 18:06:52 +0000713 pTable->aCol = 0;
drh4a324312001-12-21 14:30:42 +0000714 pTable->iPKey = -1;
drh75897232000-05-29 14:26:00 +0000715 pTable->pIndex = 0;
drh1c2d8412003-03-31 00:30:47 +0000716 pTable->iDb = iDb;
danielk19774adee202004-05-08 08:23:19 +0000717 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
drh75897232000-05-29 14:26:00 +0000718 pParse->pNewTable = pTable;
drh17f71932002-02-21 12:01:27 +0000719
drh4794f732004-11-05 17:17:50 +0000720 /* If this is the magic sqlite_sequence table used by autoincrement,
721 ** then record a pointer to this table in the main database structure
722 ** so that INSERT can find the table easily.
723 */
724#ifndef SQLITE_OMIT_AUTOINCREMENT
725 if( strcmp(zName, "sqlite_sequence")==0 ){
drh4794f732004-11-05 17:17:50 +0000726 db->aDb[iDb].pSeqTab = pTable;
727 }
728#endif
729
drh17f71932002-02-21 12:01:27 +0000730 /* Begin generating the code that will insert the table record into
731 ** the SQLITE_MASTER table. Note in particular that we must go ahead
732 ** and allocate the record number for the table entry now. Before any
733 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
734 ** indices to be created and the table record must come before the
735 ** indices. Hence, the record number for the table must be allocated
736 ** now.
737 */
danielk19774adee202004-05-08 08:23:19 +0000738 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +0000739 sqlite3BeginWriteOperation(pParse, 0, iDb);
drhb17131a2004-11-05 22:18:49 +0000740
danielk1977d008cfe2004-06-19 02:22:10 +0000741 /* Every time a new table is created the file-format
742 ** and encoding meta-values are set in the database, in
743 ** case this is the first table created.
744 */
745 sqlite3VdbeAddOp(v, OP_Integer, db->file_format, 0);
746 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
747 sqlite3VdbeAddOp(v, OP_Integer, db->enc, 0);
748 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
749
drh4794f732004-11-05 17:17:50 +0000750 /* This just creates a place-holder record in the sqlite_master table.
751 ** The record created does not contain anything yet. It will be replaced
752 ** by the real entry in code generated at sqlite3EndTable().
drhb17131a2004-11-05 22:18:49 +0000753 **
754 ** The rowid for the new entry is left on the top of the stack.
755 ** The rowid value is needed by the code that sqlite3EndTable will
756 ** generate.
drh4794f732004-11-05 17:17:50 +0000757 */
danielk1977cbb18d22004-05-28 11:37:27 +0000758 sqlite3OpenMasterTable(v, iDb);
danielk19774adee202004-05-08 08:23:19 +0000759 sqlite3VdbeAddOp(v, OP_NewRecno, 0, 0);
760 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
danielk19770f69c1e2004-05-29 11:24:50 +0000761 sqlite3VdbeAddOp(v, OP_String8, 0, 0);
danielk19774adee202004-05-08 08:23:19 +0000762 sqlite3VdbeAddOp(v, OP_PutIntKey, 0, 0);
danielk1977e6efa742004-11-10 11:55:10 +0000763 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
drh5e00f6c2001-09-13 13:46:56 +0000764 }
drh23bf66d2004-12-14 03:34:34 +0000765
766 /* Normal (non-error) return. */
767 return;
768
769 /* If an error occurs, we jump here */
770begin_table_error:
771 sqliteFree(zName);
772 return;
drh75897232000-05-29 14:26:00 +0000773}
774
775/*
776** Add a new column to the table currently being constructed.
drhd9b02572001-04-15 00:37:09 +0000777**
778** The parser calls this routine once for each column declaration
danielk19774adee202004-05-08 08:23:19 +0000779** in a CREATE TABLE statement. sqlite3StartTable() gets called
drhd9b02572001-04-15 00:37:09 +0000780** first to get things going. Then this routine is called for each
781** column.
drh75897232000-05-29 14:26:00 +0000782*/
danielk19774adee202004-05-08 08:23:19 +0000783void sqlite3AddColumn(Parse *pParse, Token *pName){
drh75897232000-05-29 14:26:00 +0000784 Table *p;
drh97fc3d02002-05-22 21:27:03 +0000785 int i;
drha99db3b2004-06-19 14:49:12 +0000786 char *z;
drhc9b84a12002-06-20 11:36:48 +0000787 Column *pCol;
drh75897232000-05-29 14:26:00 +0000788 if( (p = pParse->pNewTable)==0 ) return;
drha99db3b2004-06-19 14:49:12 +0000789 z = sqlite3NameFromToken(pName);
drh97fc3d02002-05-22 21:27:03 +0000790 if( z==0 ) return;
drh97fc3d02002-05-22 21:27:03 +0000791 for(i=0; i<p->nCol; i++){
danielk19774adee202004-05-08 08:23:19 +0000792 if( sqlite3StrICmp(z, p->aCol[i].zName)==0 ){
793 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
drh97fc3d02002-05-22 21:27:03 +0000794 sqliteFree(z);
795 return;
796 }
797 }
drh75897232000-05-29 14:26:00 +0000798 if( (p->nCol & 0x7)==0 ){
drh6d4abfb2001-10-22 02:58:08 +0000799 Column *aNew;
800 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
801 if( aNew==0 ) return;
802 p->aCol = aNew;
drh75897232000-05-29 14:26:00 +0000803 }
drhc9b84a12002-06-20 11:36:48 +0000804 pCol = &p->aCol[p->nCol];
805 memset(pCol, 0, sizeof(p->aCol[0]));
806 pCol->zName = z;
danielk1977a37cdde2004-05-16 11:15:36 +0000807
808 /* If there is no type specified, columns have the default affinity
danielk19774f057f92004-06-08 00:02:33 +0000809 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
810 ** be called next to set pCol->affinity correctly.
danielk1977a37cdde2004-05-16 11:15:36 +0000811 */
danielk19774f057f92004-06-08 00:02:33 +0000812 pCol->affinity = SQLITE_AFF_NONE;
drhd3d39e92004-05-20 22:16:29 +0000813 pCol->pColl = pParse->db->pDfltColl;
drhc9b84a12002-06-20 11:36:48 +0000814 p->nCol++;
drh75897232000-05-29 14:26:00 +0000815}
816
817/*
drh382c0242001-10-06 16:33:02 +0000818** This routine is called by the parser while in the middle of
819** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
820** been seen on a column. This routine sets the notNull flag on
821** the column currently under construction.
822*/
danielk19774adee202004-05-08 08:23:19 +0000823void sqlite3AddNotNull(Parse *pParse, int onError){
drh382c0242001-10-06 16:33:02 +0000824 Table *p;
825 int i;
826 if( (p = pParse->pNewTable)==0 ) return;
827 i = p->nCol-1;
drh9cfcf5d2002-01-29 18:41:24 +0000828 if( i>=0 ) p->aCol[i].notNull = onError;
drh382c0242001-10-06 16:33:02 +0000829}
830
831/*
832** This routine is called by the parser while in the middle of
833** parsing a CREATE TABLE statement. The pFirst token is the first
834** token in the sequence of tokens that describe the type of the
835** column currently under construction. pLast is the last token
836** in the sequence. Use this information to construct a string
837** that contains the typename of the column and store that string
838** in zType.
839*/
danielk19774adee202004-05-08 08:23:19 +0000840void sqlite3AddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
drh382c0242001-10-06 16:33:02 +0000841 Table *p;
842 int i, j;
843 int n;
844 char *z, **pz;
drhc9b84a12002-06-20 11:36:48 +0000845 Column *pCol;
drh382c0242001-10-06 16:33:02 +0000846 if( (p = pParse->pNewTable)==0 ) return;
847 i = p->nCol-1;
drhf57b3392001-10-08 13:22:32 +0000848 if( i<0 ) return;
drhc9b84a12002-06-20 11:36:48 +0000849 pCol = &p->aCol[i];
850 pz = &pCol->zType;
drh596bd232004-09-30 14:22:47 +0000851 n = pLast->n + (pLast->z - pFirst->z);
drhae29ffb2004-09-25 14:39:18 +0000852 assert( pCol->zType==0 );
853 z = pCol->zType = sqlite3MPrintf("%.*s", n, pFirst->z);
drhf57b3392001-10-08 13:22:32 +0000854 if( z==0 ) return;
drh382c0242001-10-06 16:33:02 +0000855 for(i=j=0; z[i]; i++){
856 int c = z[i];
857 if( isspace(c) ) continue;
858 z[j++] = c;
859 }
860 z[j] = 0;
danielk1977a37cdde2004-05-16 11:15:36 +0000861 pCol->affinity = sqlite3AffinityType(z, n);
drh382c0242001-10-06 16:33:02 +0000862}
863
864/*
danielk19777977a172004-11-09 12:44:37 +0000865** The expression is the default value for the most recently added column
866** of the table currently under construction.
867**
868** Default value expressions must be constant. Raise an exception if this
869** is not the case.
drhd9b02572001-04-15 00:37:09 +0000870**
871** This routine is called by the parser while in the middle of
872** parsing a CREATE TABLE statement.
drh7020f652000-06-03 18:06:52 +0000873*/
danielk19777977a172004-11-09 12:44:37 +0000874void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
drh7020f652000-06-03 18:06:52 +0000875 Table *p;
danielk19777977a172004-11-09 12:44:37 +0000876 Column *pCol;
drh7020f652000-06-03 18:06:52 +0000877 if( (p = pParse->pNewTable)==0 ) return;
danielk19777977a172004-11-09 12:44:37 +0000878 pCol = &(p->aCol[p->nCol-1]);
879 if( !sqlite3ExprIsConstant(pExpr) ){
880 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
881 pCol->zName);
882 }else{
883 sqlite3ExprDelete(pCol->pDflt);
884 pCol->pDflt = sqlite3ExprDup(pExpr);
885 sqlite3ExprCheck(pParse, pExpr, 0, 0);
886 }
887 sqlite3ExprDelete(pExpr);
drh7020f652000-06-03 18:06:52 +0000888}
889
890/*
drh4a324312001-12-21 14:30:42 +0000891** Designate the PRIMARY KEY for the table. pList is a list of names
892** of columns that form the primary key. If pList is NULL, then the
893** most recently added column of the table is the primary key.
894**
895** A table can have at most one primary key. If the table already has
896** a primary key (and this is the second primary key) then create an
897** error.
898**
899** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
drh23bf66d2004-12-14 03:34:34 +0000900** then we will try to use that column as the rowid. Set the Table.iPKey
drh4a324312001-12-21 14:30:42 +0000901** field of the table under construction to be the index of the
902** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
903** no INTEGER PRIMARY KEY.
904**
905** If the key is not an INTEGER PRIMARY KEY, then create a unique
906** index for the key. No index is created for INTEGER PRIMARY KEYs.
907*/
drh205f48e2004-11-05 00:43:11 +0000908void sqlite3AddPrimaryKey(
909 Parse *pParse, /* Parsing context */
910 ExprList *pList, /* List of field names to be indexed */
911 int onError, /* What to do with a uniqueness conflict */
912 int autoInc /* True if the AUTOINCREMENT keyword is present */
913){
drh4a324312001-12-21 14:30:42 +0000914 Table *pTab = pParse->pNewTable;
915 char *zType = 0;
drh78100cc2003-08-23 22:40:53 +0000916 int iCol = -1, i;
drhe0194f22003-02-26 13:52:51 +0000917 if( pTab==0 ) goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +0000918 if( pTab->hasPrimKey ){
danielk19774adee202004-05-08 08:23:19 +0000919 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +0000920 "table \"%s\" has more than one primary key", pTab->zName);
drhe0194f22003-02-26 13:52:51 +0000921 goto primary_key_exit;
drh4a324312001-12-21 14:30:42 +0000922 }
923 pTab->hasPrimKey = 1;
924 if( pList==0 ){
925 iCol = pTab->nCol - 1;
drh78100cc2003-08-23 22:40:53 +0000926 pTab->aCol[iCol].isPrimKey = 1;
927 }else{
danielk19770202b292004-06-09 09:55:16 +0000928 for(i=0; i<pList->nExpr; i++){
drh78100cc2003-08-23 22:40:53 +0000929 for(iCol=0; iCol<pTab->nCol; iCol++){
drhd3d39e92004-05-20 22:16:29 +0000930 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
931 break;
932 }
drh78100cc2003-08-23 22:40:53 +0000933 }
934 if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
drh4a324312001-12-21 14:30:42 +0000935 }
danielk19770202b292004-06-09 09:55:16 +0000936 if( pList->nExpr>1 ) iCol = -1;
drh4a324312001-12-21 14:30:42 +0000937 }
938 if( iCol>=0 && iCol<pTab->nCol ){
939 zType = pTab->aCol[iCol].zType;
940 }
danielk19773d68f032004-05-11 07:11:51 +0000941 if( zType && sqlite3StrICmp(zType, "INTEGER")==0 ){
drh4a324312001-12-21 14:30:42 +0000942 pTab->iPKey = iCol;
drh9cfcf5d2002-01-29 18:41:24 +0000943 pTab->keyConf = onError;
drh205f48e2004-11-05 00:43:11 +0000944 pTab->autoInc = autoInc;
945 }else if( autoInc ){
drh4794f732004-11-05 17:17:50 +0000946#ifndef SQLITE_OMIT_AUTOINCREMENT
drh205f48e2004-11-05 00:43:11 +0000947 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
948 "INTEGER PRIMARY KEY");
drh4794f732004-11-05 17:17:50 +0000949#endif
drh4a324312001-12-21 14:30:42 +0000950 }else{
danielk1977cbb18d22004-05-28 11:37:27 +0000951 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0);
drhe0194f22003-02-26 13:52:51 +0000952 pList = 0;
drh4a324312001-12-21 14:30:42 +0000953 }
drhe0194f22003-02-26 13:52:51 +0000954
955primary_key_exit:
danielk19770202b292004-06-09 09:55:16 +0000956 sqlite3ExprListDelete(pList);
drhe0194f22003-02-26 13:52:51 +0000957 return;
drh4a324312001-12-21 14:30:42 +0000958}
959
960/*
drhd3d39e92004-05-20 22:16:29 +0000961** Set the collation function of the most recently parsed table column
962** to the CollSeq given.
drh8e2ca022002-06-17 17:07:19 +0000963*/
drhd3d39e92004-05-20 22:16:29 +0000964void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
drh8e2ca022002-06-17 17:07:19 +0000965 Table *p;
danielk19770202b292004-06-09 09:55:16 +0000966 Index *pIdx;
drhd3d39e92004-05-20 22:16:29 +0000967 CollSeq *pColl;
danielk19770202b292004-06-09 09:55:16 +0000968 int i;
danielk1977a37cdde2004-05-16 11:15:36 +0000969
drhd3d39e92004-05-20 22:16:29 +0000970 if( (p = pParse->pNewTable)==0 ) return;
danielk19770202b292004-06-09 09:55:16 +0000971 i = p->nCol-1;
972
973 pColl = sqlite3LocateCollSeq(pParse, zType, nType);
974 p->aCol[i].pColl = pColl;
975
976 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
977 ** then an index may have been created on this column before the
978 ** collation type was added. Correct this if it is the case.
979 */
980 for(pIdx = p->pIndex; pIdx; pIdx=pIdx->pNext){
981 assert( pIdx->nColumn==1 );
982 if( pIdx->aiColumn[0]==i ) pIdx->keyInfo.aColl[0] = pColl;
drhd3d39e92004-05-20 22:16:29 +0000983 }
984}
985
986/*
danielk19770202b292004-06-09 09:55:16 +0000987** Locate and return an entry from the db.aCollSeq hash table. If the entry
988** specified by zName and nName is not found and parameter 'create' is
danielk1977466be562004-06-10 02:16:01 +0000989** true, then create a new entry. Otherwise return NULL.
drhd3d39e92004-05-20 22:16:29 +0000990**
danielk1977466be562004-06-10 02:16:01 +0000991** Each pointer stored in the sqlite3.aCollSeq hash table contains an
992** array of three CollSeq structures. The first is the collation sequence
993** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
drhd3d39e92004-05-20 22:16:29 +0000994**
danielk1977466be562004-06-10 02:16:01 +0000995** Stored immediately after the three collation sequences is a copy of
996** the collation sequence name. A pointer to this string is stored in
997** each collation sequence structure.
drhd3d39e92004-05-20 22:16:29 +0000998*/
danielk1977466be562004-06-10 02:16:01 +0000999static CollSeq * findCollSeqEntry(
drh9bb575f2004-09-06 17:24:11 +00001000 sqlite3 *db,
danielk1977466be562004-06-10 02:16:01 +00001001 const char *zName,
danielk19770202b292004-06-09 09:55:16 +00001002 int nName,
1003 int create
drhd3d39e92004-05-20 22:16:29 +00001004){
1005 CollSeq *pColl;
danielk19770202b292004-06-09 09:55:16 +00001006 if( nName<0 ) nName = strlen(zName);
drhd3d39e92004-05-20 22:16:29 +00001007 pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
danielk1977466be562004-06-10 02:16:01 +00001008
danielk19770202b292004-06-09 09:55:16 +00001009 if( 0==pColl && create ){
danielk1977466be562004-06-10 02:16:01 +00001010 pColl = sqliteMalloc( 3*sizeof(*pColl) + nName + 1 );
danielk19770202b292004-06-09 09:55:16 +00001011 if( pColl ){
danielk1977466be562004-06-10 02:16:01 +00001012 pColl[0].zName = (char*)&pColl[3];
danielk1977dc8453f2004-06-12 00:42:34 +00001013 pColl[0].enc = SQLITE_UTF8;
danielk1977466be562004-06-10 02:16:01 +00001014 pColl[1].zName = (char*)&pColl[3];
danielk1977dc8453f2004-06-12 00:42:34 +00001015 pColl[1].enc = SQLITE_UTF16LE;
danielk1977466be562004-06-10 02:16:01 +00001016 pColl[2].zName = (char*)&pColl[3];
danielk1977dc8453f2004-06-12 00:42:34 +00001017 pColl[2].enc = SQLITE_UTF16BE;
danielk19777cedc8d2004-06-10 10:50:08 +00001018 memcpy(pColl[0].zName, zName, nName);
1019 pColl[0].zName[nName] = 0;
danielk1977466be562004-06-10 02:16:01 +00001020 sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
drhd3d39e92004-05-20 22:16:29 +00001021 }
drhd3d39e92004-05-20 22:16:29 +00001022 }
drhd3d39e92004-05-20 22:16:29 +00001023 return pColl;
danielk1977a37cdde2004-05-16 11:15:36 +00001024}
1025
danielk1977466be562004-06-10 02:16:01 +00001026/*
1027** Parameter zName points to a UTF-8 encoded string nName bytes long.
1028** Return the CollSeq* pointer for the collation sequence named zName
1029** for the encoding 'enc' from the database 'db'.
1030**
1031** If the entry specified is not found and 'create' is true, then create a
1032** new entry. Otherwise return NULL.
1033*/
1034CollSeq *sqlite3FindCollSeq(
drh9bb575f2004-09-06 17:24:11 +00001035 sqlite3 *db,
danielk1977466be562004-06-10 02:16:01 +00001036 u8 enc,
1037 const char *zName,
1038 int nName,
1039 int create
1040){
1041 CollSeq *pColl = findCollSeqEntry(db, zName, nName, create);
drh6d08b4d2004-07-20 12:45:22 +00001042 assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
1043 assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
1044 if( pColl ) pColl += enc-1;
danielk1977466be562004-06-10 02:16:01 +00001045 return pColl;
1046}
1047
danielk1977e159fdf2004-06-21 10:45:06 +00001048/*
1049** Invoke the 'collation needed' callback to request a collation sequence
1050** in the database text encoding of name zName, length nName.
1051** If the collation sequence
1052*/
drh9bb575f2004-09-06 17:24:11 +00001053static void callCollNeeded(sqlite3 *db, const char *zName, int nName){
danielk19777cedc8d2004-06-10 10:50:08 +00001054 assert( !db->xCollNeeded || !db->xCollNeeded16 );
1055 if( nName<0 ) nName = strlen(zName);
1056 if( db->xCollNeeded ){
danielk19778a6c5502004-06-22 12:18:32 +00001057 char *zExternal = sqliteStrNDup(zName, nName);
danielk19777cedc8d2004-06-10 10:50:08 +00001058 if( !zExternal ) return;
danielk1977e159fdf2004-06-21 10:45:06 +00001059 db->xCollNeeded(db->pCollNeededArg, db, (int)db->enc, zExternal);
1060 sqliteFree(zExternal);
danielk19777cedc8d2004-06-10 10:50:08 +00001061 }
1062 if( db->xCollNeeded16 ){
danielk19778a6c5502004-06-22 12:18:32 +00001063 char const *zExternal;
danielk1977bfd6cce2004-06-18 04:24:54 +00001064 sqlite3_value *pTmp = sqlite3GetTransientValue(db);
1065 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
1066 zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
danielk19777cedc8d2004-06-10 10:50:08 +00001067 if( !zExternal ) return;
1068 db->xCollNeeded16(db->pCollNeededArg, db, (int)db->enc, zExternal);
1069 }
danielk19777cedc8d2004-06-10 10:50:08 +00001070}
1071
danielk1977e159fdf2004-06-21 10:45:06 +00001072/*
1073** This routine is called if the collation factory fails to deliver a
1074** collation function in the best encoding but there may be other versions
1075** of this collation function (for other text encodings) available. Use one
1076** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
1077** possible.
1078*/
danielk19777cedc8d2004-06-10 10:50:08 +00001079static int synthCollSeq(Parse *pParse, CollSeq *pColl){
drhda71ce12004-06-21 18:14:45 +00001080 CollSeq *pColl2;
danielk19777cedc8d2004-06-10 10:50:08 +00001081 char *z = pColl->zName;
1082 int n = strlen(z);
drh9bb575f2004-09-06 17:24:11 +00001083 sqlite3 *db = pParse->db;
drhda71ce12004-06-21 18:14:45 +00001084 int i;
1085 static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
1086 for(i=0; i<3; i++){
1087 pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, n, 0);
1088 if( pColl2->xCmp!=0 ){
1089 memcpy(pColl, pColl2, sizeof(CollSeq));
1090 return SQLITE_OK;
danielk19777cedc8d2004-06-10 10:50:08 +00001091 }
danielk19777cedc8d2004-06-10 10:50:08 +00001092 }
drhda71ce12004-06-21 18:14:45 +00001093 if( pParse->nErr==0 ){
drhae29ffb2004-09-25 14:39:18 +00001094 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", n, z);
drhda71ce12004-06-21 18:14:45 +00001095 }
1096 pParse->nErr++;
1097 return SQLITE_ERROR;
danielk19777cedc8d2004-06-10 10:50:08 +00001098}
1099
1100/*
1101** This routine is called on a collation sequence before it is used to
1102** check that it is defined. An undefined collation sequence exists when
1103** a database is loaded that contains references to collation sequences
1104** that have not been defined by sqlite3_create_collation() etc.
1105**
1106** If required, this routine calls the 'collation needed' callback to
1107** request a definition of the collating sequence. If this doesn't work,
1108** an equivalent collating sequence that uses a text encoding different
1109** from the main database is substituted, if one is available.
1110*/
1111int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
1112 if( pColl && !pColl->xCmp ){
danielk1977e159fdf2004-06-21 10:45:06 +00001113 /* No collation sequence of this type for this encoding is registered.
1114 ** Call the collation factory to see if it can supply us with one.
1115 */
danielk19777cedc8d2004-06-10 10:50:08 +00001116 callCollNeeded(pParse->db, pColl->zName, strlen(pColl->zName));
1117 if( !pColl->xCmp && synthCollSeq(pParse, pColl) ){
1118 return SQLITE_ERROR;
1119 }
1120 }
1121 return SQLITE_OK;
1122}
1123
drhda71ce12004-06-21 18:14:45 +00001124/*
1125** Call sqlite3CheckCollSeq() for all collating sequences in an index,
1126** in order to verify that all the necessary collating sequences are
1127** loaded.
1128*/
danielk19777cedc8d2004-06-10 10:50:08 +00001129int sqlite3CheckIndexCollSeq(Parse *pParse, Index *pIdx){
1130 if( pIdx ){
1131 int i;
1132 for(i=0; i<pIdx->nColumn; i++){
1133 if( sqlite3CheckCollSeq(pParse, pIdx->keyInfo.aColl[i]) ){
1134 return SQLITE_ERROR;
1135 }
1136 }
1137 }
1138 return SQLITE_OK;
1139}
1140
danielk1977466be562004-06-10 02:16:01 +00001141/*
1142** This function returns the collation sequence for database native text
1143** encoding identified by the string zName, length nName.
1144**
1145** If the requested collation sequence is not available, or not available
1146** in the database native encoding, the collation factory is invoked to
1147** request it. If the collation factory does not supply such a sequence,
1148** and the sequence is available in another text encoding, then that is
1149** returned instead.
1150**
1151** If no versions of the requested collations sequence are available, or
1152** another error occurs, NULL is returned and an error message written into
1153** pParse.
1154*/
danielk19770202b292004-06-09 09:55:16 +00001155CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
danielk1977466be562004-06-10 02:16:01 +00001156 u8 enc = pParse->db->enc;
danielk19777cedc8d2004-06-10 10:50:08 +00001157 u8 initbusy = pParse->db->init.busy;
1158 CollSeq *pColl = sqlite3FindCollSeq(pParse->db, enc, zName, nName, initbusy);
drhae29ffb2004-09-25 14:39:18 +00001159 if( nName<0 ) nName = strlen(zName);
danielk19777cedc8d2004-06-10 10:50:08 +00001160 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk1977466be562004-06-10 02:16:01 +00001161 /* No collation sequence of this type for this encoding is registered.
1162 ** Call the collation factory to see if it can supply us with one.
1163 */
danielk19777cedc8d2004-06-10 10:50:08 +00001164 callCollNeeded(pParse->db, zName, nName);
danielk1977466be562004-06-10 02:16:01 +00001165 pColl = sqlite3FindCollSeq(pParse->db, enc, zName, nName, 0);
danielk1977466be562004-06-10 02:16:01 +00001166 if( pColl && !pColl->xCmp ){
danielk19777cedc8d2004-06-10 10:50:08 +00001167 /* There may be a version of the collation sequence that requires
1168 ** translation between encodings. Search for it with synthCollSeq().
danielk1977466be562004-06-10 02:16:01 +00001169 */
danielk19777cedc8d2004-06-10 10:50:08 +00001170 if( synthCollSeq(pParse, pColl) ){
1171 return 0;
danielk1977466be562004-06-10 02:16:01 +00001172 }
1173 }
1174 }
1175
1176 /* If nothing has been found, write the error message into pParse */
danielk19777cedc8d2004-06-10 10:50:08 +00001177 if( !initbusy && (!pColl || !pColl->xCmp) ){
danielk19770202b292004-06-09 09:55:16 +00001178 if( pParse->nErr==0 ){
drhae29ffb2004-09-25 14:39:18 +00001179 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
danielk19770202b292004-06-09 09:55:16 +00001180 }
danielk19777cedc8d2004-06-10 10:50:08 +00001181 pColl = 0;
danielk19770202b292004-06-09 09:55:16 +00001182 }
1183 return pColl;
1184}
1185
1186
1187
danielk1977a37cdde2004-05-16 11:15:36 +00001188/*
drh1ad3b9e2004-05-20 12:10:20 +00001189** Scan the column type name zType (length nType) and return the
danielk1977a37cdde2004-05-16 11:15:36 +00001190** associated affinity type.
1191*/
1192char sqlite3AffinityType(const char *zType, int nType){
danielk1977a37cdde2004-05-16 11:15:36 +00001193 int n, i;
drh57196282004-10-06 15:41:16 +00001194 static const struct {
drh1ad3b9e2004-05-20 12:10:20 +00001195 const char *zSub; /* Keywords substring to search for */
drhda71ce12004-06-21 18:14:45 +00001196 char nSub; /* length of zSub */
drh1ad3b9e2004-05-20 12:10:20 +00001197 char affinity; /* Affinity to return if it matches */
danielk1977a37cdde2004-05-16 11:15:36 +00001198 } substrings[] = {
drh1ad3b9e2004-05-20 12:10:20 +00001199 {"INT", 3, SQLITE_AFF_INTEGER},
danielk1977a37cdde2004-05-16 11:15:36 +00001200 {"CHAR", 4, SQLITE_AFF_TEXT},
1201 {"CLOB", 4, SQLITE_AFF_TEXT},
drh1ad3b9e2004-05-20 12:10:20 +00001202 {"TEXT", 4, SQLITE_AFF_TEXT},
1203 {"BLOB", 4, SQLITE_AFF_NONE},
danielk1977a37cdde2004-05-16 11:15:36 +00001204 };
1205
drh9c054832004-05-31 18:51:57 +00001206 if( nType==0 ){
1207 return SQLITE_AFF_NONE;
1208 }
drh1ad3b9e2004-05-20 12:10:20 +00001209 for(i=0; i<sizeof(substrings)/sizeof(substrings[0]); i++){
1210 int c1 = substrings[i].zSub[0];
1211 int c2 = tolower(c1);
1212 int limit = nType - substrings[i].nSub;
1213 const char *z = substrings[i].zSub;
1214 for(n=0; n<=limit; n++){
1215 int c = zType[n];
1216 if( (c==c1 || c==c2)
1217 && 0==sqlite3StrNICmp(&zType[n], z, substrings[i].nSub) ){
danielk1977a37cdde2004-05-16 11:15:36 +00001218 return substrings[i].affinity;
1219 }
1220 }
1221 }
drh1ad3b9e2004-05-20 12:10:20 +00001222 return SQLITE_AFF_NUMERIC;
drh8e2ca022002-06-17 17:07:19 +00001223}
1224
1225/*
drh3f7d4e42004-07-24 14:35:58 +00001226** Generate code that will increment the schema cookie.
drh50e5dad2001-09-15 00:57:28 +00001227**
1228** The schema cookie is used to determine when the schema for the
1229** database changes. After each schema change, the cookie value
1230** changes. When a process first reads the schema it records the
1231** cookie. Thereafter, whenever it goes to access the database,
1232** it checks the cookie to make sure the schema has not changed
1233** since it was last read.
1234**
1235** This plan is not completely bullet-proof. It is possible for
1236** the schema to change multiple times and for the cookie to be
1237** set back to prior value. But schema changes are infrequent
1238** and the probability of hitting the same cookie value is only
1239** 1 chance in 2^32. So we're safe enough.
1240*/
drh9bb575f2004-09-06 17:24:11 +00001241void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
drh3f7d4e42004-07-24 14:35:58 +00001242 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].schema_cookie+1, 0);
danielk19771d850a72004-05-31 08:26:49 +00001243 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
drh50e5dad2001-09-15 00:57:28 +00001244}
1245
1246/*
drh969fa7c2002-02-18 18:30:32 +00001247** Measure the number of characters needed to output the given
1248** identifier. The number returned includes any quotes used
1249** but does not include the null terminator.
drh234c39d2004-07-24 03:30:47 +00001250**
1251** The estimate is conservative. It might be larger that what is
1252** really needed.
drh969fa7c2002-02-18 18:30:32 +00001253*/
1254static int identLength(const char *z){
1255 int n;
drh17f71932002-02-21 12:01:27 +00001256 for(n=0; *z; n++, z++){
drh234c39d2004-07-24 03:30:47 +00001257 if( *z=='"' ){ n++; }
drh969fa7c2002-02-18 18:30:32 +00001258 }
drh234c39d2004-07-24 03:30:47 +00001259 return n + 2;
drh969fa7c2002-02-18 18:30:32 +00001260}
1261
1262/*
1263** Write an identifier onto the end of the given string. Add
1264** quote characters as needed.
1265*/
drh4c755c02004-08-08 20:22:17 +00001266static void identPut(char *z, int *pIdx, char *zSignedIdent){
1267 unsigned char *zIdent = (unsigned char*)zSignedIdent;
drh17f71932002-02-21 12:01:27 +00001268 int i, j, needQuote;
drh969fa7c2002-02-18 18:30:32 +00001269 i = *pIdx;
drh17f71932002-02-21 12:01:27 +00001270 for(j=0; zIdent[j]; j++){
1271 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
1272 }
1273 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
danielk19774adee202004-05-08 08:23:19 +00001274 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
drh234c39d2004-07-24 03:30:47 +00001275 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001276 for(j=0; zIdent[j]; j++){
1277 z[i++] = zIdent[j];
drh234c39d2004-07-24 03:30:47 +00001278 if( zIdent[j]=='"' ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001279 }
drh234c39d2004-07-24 03:30:47 +00001280 if( needQuote ) z[i++] = '"';
drh969fa7c2002-02-18 18:30:32 +00001281 z[i] = 0;
1282 *pIdx = i;
1283}
1284
1285/*
1286** Generate a CREATE TABLE statement appropriate for the given
1287** table. Memory to hold the text of the statement is obtained
1288** from sqliteMalloc() and must be freed by the calling function.
1289*/
1290static char *createTableStmt(Table *p){
1291 int i, k, n;
1292 char *zStmt;
drh234c39d2004-07-24 03:30:47 +00001293 char *zSep, *zSep2, *zEnd, *z;
1294 Column *pCol;
drh969fa7c2002-02-18 18:30:32 +00001295 n = 0;
drh234c39d2004-07-24 03:30:47 +00001296 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
1297 n += identLength(pCol->zName);
1298 z = pCol->zType;
1299 if( z ){
1300 n += (strlen(z) + 1);
danielk1977517eb642004-06-07 10:00:31 +00001301 }
drh969fa7c2002-02-18 18:30:32 +00001302 }
1303 n += identLength(p->zName);
drh234c39d2004-07-24 03:30:47 +00001304 if( n<50 ){
drh969fa7c2002-02-18 18:30:32 +00001305 zSep = "";
1306 zSep2 = ",";
1307 zEnd = ")";
1308 }else{
1309 zSep = "\n ";
1310 zSep2 = ",\n ";
1311 zEnd = "\n)";
1312 }
drhe0bc4042002-06-25 01:09:11 +00001313 n += 35 + 6*p->nCol;
drh8c1238a2003-01-02 14:43:55 +00001314 zStmt = sqliteMallocRaw( n );
drh969fa7c2002-02-18 18:30:32 +00001315 if( zStmt==0 ) return 0;
drhd24cc422003-03-27 12:51:24 +00001316 strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
drh969fa7c2002-02-18 18:30:32 +00001317 k = strlen(zStmt);
1318 identPut(zStmt, &k, p->zName);
1319 zStmt[k++] = '(';
drh234c39d2004-07-24 03:30:47 +00001320 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
drh969fa7c2002-02-18 18:30:32 +00001321 strcpy(&zStmt[k], zSep);
1322 k += strlen(&zStmt[k]);
1323 zSep = zSep2;
drh234c39d2004-07-24 03:30:47 +00001324 identPut(zStmt, &k, pCol->zName);
1325 if( (z = pCol->zType)!=0 ){
danielk1977517eb642004-06-07 10:00:31 +00001326 zStmt[k++] = ' ';
drh234c39d2004-07-24 03:30:47 +00001327 strcpy(&zStmt[k], z);
1328 k += strlen(z);
danielk1977517eb642004-06-07 10:00:31 +00001329 }
drh969fa7c2002-02-18 18:30:32 +00001330 }
1331 strcpy(&zStmt[k], zEnd);
1332 return zStmt;
1333}
1334
1335/*
drh75897232000-05-29 14:26:00 +00001336** This routine is called to report the final ")" that terminates
1337** a CREATE TABLE statement.
1338**
drhf57b3392001-10-08 13:22:32 +00001339** The table structure that other action routines have been building
1340** is added to the internal hash tables, assuming no errors have
1341** occurred.
drh75897232000-05-29 14:26:00 +00001342**
drh1d85d932004-02-14 23:05:52 +00001343** An entry for the table is made in the master table on disk, unless
1344** this is a temporary table or db->init.busy==1. When db->init.busy==1
drhf57b3392001-10-08 13:22:32 +00001345** it means we are reading the sqlite_master table because we just
1346** connected to the database or because the sqlite_master table has
1347** recently changes, so the entry for this table already exists in
1348** the sqlite_master table. We do not want to create it again.
drh969fa7c2002-02-18 18:30:32 +00001349**
1350** If the pSelect argument is not NULL, it means that this routine
1351** was called to create a table generated from a
1352** "CREATE TABLE ... AS SELECT ..." statement. The column names of
1353** the new table will match the result set of the SELECT.
drh75897232000-05-29 14:26:00 +00001354*/
danielk19774adee202004-05-08 08:23:19 +00001355void sqlite3EndTable(Parse *pParse, Token *pEnd, Select *pSelect){
drh75897232000-05-29 14:26:00 +00001356 Table *p;
drh9bb575f2004-09-06 17:24:11 +00001357 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00001358
danielk197724b03fd2004-05-10 10:34:34 +00001359 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3_malloc_failed ) return;
drh28037572000-08-02 13:47:41 +00001360 p = pParse->pNewTable;
drhdaffd0e2001-04-11 14:28:42 +00001361 if( p==0 ) return;
drh75897232000-05-29 14:26:00 +00001362
danielk1977517eb642004-06-07 10:00:31 +00001363 assert( !db->init.busy || !pSelect );
1364
drh1d85d932004-02-14 23:05:52 +00001365 /* If the db->init.busy is 1 it means we are reading the SQL off the
drhe0bc4042002-06-25 01:09:11 +00001366 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
1367 ** So do not write to the disk again. Extract the root page number
drh1d85d932004-02-14 23:05:52 +00001368 ** for the table from the db->init.newTnum field. (The page number
drhe0bc4042002-06-25 01:09:11 +00001369 ** should have been put there by the sqliteOpenCb routine.)
drhd78eeee2001-09-13 16:18:53 +00001370 */
drh1d85d932004-02-14 23:05:52 +00001371 if( db->init.busy ){
1372 p->tnum = db->init.newTnum;
drhd78eeee2001-09-13 16:18:53 +00001373 }
1374
drhe3c41372001-09-17 20:25:58 +00001375 /* If not initializing, then create a record for the new table
drh17f71932002-02-21 12:01:27 +00001376 ** in the SQLITE_MASTER table of the database. The record number
1377 ** for the new table entry should already be on the stack.
drhf57b3392001-10-08 13:22:32 +00001378 **
drhe0bc4042002-06-25 01:09:11 +00001379 ** If this is a TEMPORARY table, write the entry into the auxiliary
1380 ** file instead of into the main database file.
drh75897232000-05-29 14:26:00 +00001381 */
drh1d85d932004-02-14 23:05:52 +00001382 if( !db->init.busy ){
drh4ff6dfa2002-03-03 23:06:00 +00001383 int n;
drhd8bc7082000-06-07 23:51:50 +00001384 Vdbe *v;
drh4794f732004-11-05 17:17:50 +00001385 char *zType; /* "view" or "table" */
1386 char *zType2; /* "VIEW" or "TABLE" */
1387 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
drh75897232000-05-29 14:26:00 +00001388
danielk19774adee202004-05-08 08:23:19 +00001389 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001390 if( v==0 ) return;
danielk1977517eb642004-06-07 10:00:31 +00001391
danielk1977e6efa742004-11-10 11:55:10 +00001392 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
1393
drh4794f732004-11-05 17:17:50 +00001394 /* Create the rootpage for the new table and push it onto the stack.
1395 ** A view has no rootpage, so just push a zero onto the stack for
1396 ** views. Initialize zType at the same time.
1397 */
drh4ff6dfa2002-03-03 23:06:00 +00001398 if( p->pSelect==0 ){
1399 /* A regular table */
drh234c39d2004-07-24 03:30:47 +00001400 sqlite3VdbeAddOp(v, OP_CreateTable, p->iDb, 0);
drh4794f732004-11-05 17:17:50 +00001401 zType = "table";
1402 zType2 = "TABLE";
drh4ff6dfa2002-03-03 23:06:00 +00001403 }else{
1404 /* A view */
danielk19774adee202004-05-08 08:23:19 +00001405 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
drh4794f732004-11-05 17:17:50 +00001406 zType = "view";
1407 zType2 = "VIEW";
drh4ff6dfa2002-03-03 23:06:00 +00001408 }
danielk1977517eb642004-06-07 10:00:31 +00001409
danielk1977517eb642004-06-07 10:00:31 +00001410 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
1411 ** statement to populate the new table. The root-page number for the
1412 ** new table is on the top of the vdbe stack.
1413 **
1414 ** Once the SELECT has been coded by sqlite3Select(), it is in a
1415 ** suitable state to query for the column names and types to be used
1416 ** by the new table.
1417 */
1418 if( pSelect ){
1419 Table *pSelTab;
1420 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1421 sqlite3VdbeAddOp(v, OP_Integer, p->iDb, 0);
1422 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
1423 pParse->nTab = 2;
1424 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
1425 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
1426 if( pParse->nErr==0 ){
1427 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
1428 if( pSelTab==0 ) return;
1429 assert( p->aCol==0 );
1430 p->nCol = pSelTab->nCol;
1431 p->aCol = pSelTab->aCol;
1432 pSelTab->nCol = 0;
1433 pSelTab->aCol = 0;
1434 sqlite3DeleteTable(0, pSelTab);
1435 }
1436 }
drh4794f732004-11-05 17:17:50 +00001437
drh4794f732004-11-05 17:17:50 +00001438 /* Compute the complete text of the CREATE statement */
1439 if( pSelect ){
1440 zStmt = createTableStmt(p);
1441 }else{
1442 n = Addr(pEnd->z) - Addr(pParse->sNameToken.z) + 1;
1443 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
1444 }
1445
1446 /* A slot for the record has already been allocated in the
1447 ** SQLITE_MASTER table. We just need to update that slot with all
1448 ** the information we've collected. The rowid for the preallocated
1449 ** slot is the 2nd item on the stack. The top of the stack is the
1450 ** root page for the new table (or a 0 if this is a view).
1451 */
1452 sqlite3NestedParse(pParse,
1453 "UPDATE %Q.%s "
1454 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
1455 "WHERE rowid=#1",
1456 db->aDb[p->iDb].zName, SCHEMA_TABLE(p->iDb),
1457 zType,
1458 p->zName,
1459 p->zName,
1460 zStmt
1461 );
1462 sqliteFree(zStmt);
drh2958a4e2004-11-12 03:56:15 +00001463 sqlite3ChangeCookie(db, v, p->iDb);
1464
1465#ifndef SQLITE_OMIT_AUTOINCREMENT
1466 /* Check to see if we need to create an sqlite_sequence table for
1467 ** keeping track of autoincrement keys.
1468 */
1469 if( p->autoInc ){
1470 Db *pDb = &db->aDb[p->iDb];
1471 if( pDb->pSeqTab==0 ){
1472 sqlite3NestedParse(pParse,
drhf3388142004-11-13 03:48:06 +00001473 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
1474 pDb->zName
drh2958a4e2004-11-12 03:56:15 +00001475 );
1476 }
1477 }
1478#endif
drh4794f732004-11-05 17:17:50 +00001479
1480 /* Reparse everything to update our internal data structures */
drh234c39d2004-07-24 03:30:47 +00001481 sqlite3VdbeOp3(v, OP_ParseSchema, p->iDb, 0,
1482 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
drh75897232000-05-29 14:26:00 +00001483 }
drh17e9e292003-02-01 13:53:28 +00001484
drh2958a4e2004-11-12 03:56:15 +00001485
drh17e9e292003-02-01 13:53:28 +00001486 /* Add the table to the in-memory representation of the database.
1487 */
drh234c39d2004-07-24 03:30:47 +00001488 if( db->init.busy && pParse->nErr==0 ){
drh17e9e292003-02-01 13:53:28 +00001489 Table *pOld;
drhbe5c89a2004-07-26 00:31:09 +00001490 FKey *pFKey;
1491 Db *pDb = &db->aDb[p->iDb];
1492 pOld = sqlite3HashInsert(&pDb->tblHash, p->zName, strlen(p->zName)+1, p);
drh17e9e292003-02-01 13:53:28 +00001493 if( pOld ){
1494 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
1495 return;
1496 }
1497 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1498 int nTo = strlen(pFKey->zTo) + 1;
drhbe5c89a2004-07-26 00:31:09 +00001499 pFKey->pNextTo = sqlite3HashFind(&pDb->aFKey, pFKey->zTo, nTo);
1500 sqlite3HashInsert(&pDb->aFKey, pFKey->zTo, nTo, pFKey);
drh17e9e292003-02-01 13:53:28 +00001501 }
1502 pParse->pNewTable = 0;
1503 db->nTable++;
1504 db->flags |= SQLITE_InternChanges;
1505 }
drh75897232000-05-29 14:26:00 +00001506}
1507
drhb7f91642004-10-31 02:22:47 +00001508#ifndef SQLITE_OMIT_VIEW
drh75897232000-05-29 14:26:00 +00001509/*
drha76b5df2002-02-23 02:32:10 +00001510** The parser calls this routine in order to create a new VIEW
1511*/
danielk19774adee202004-05-08 08:23:19 +00001512void sqlite3CreateView(
drha76b5df2002-02-23 02:32:10 +00001513 Parse *pParse, /* The parsing context */
1514 Token *pBegin, /* The CREATE token that begins the statement */
danielk197748dec7e2004-05-28 12:33:30 +00001515 Token *pName1, /* The token that holds the name of the view */
1516 Token *pName2, /* The token that holds the name of the view */
drh6276c1c2002-07-08 22:03:32 +00001517 Select *pSelect, /* A SELECT statement that will become the new view */
1518 int isTemp /* TRUE for a TEMPORARY view */
drha76b5df2002-02-23 02:32:10 +00001519){
drha76b5df2002-02-23 02:32:10 +00001520 Table *p;
drh4b59ab52002-08-24 18:24:51 +00001521 int n;
drh4c755c02004-08-08 20:22:17 +00001522 const unsigned char *z;
drh4b59ab52002-08-24 18:24:51 +00001523 Token sEnd;
drhf26e09c2003-05-31 16:21:12 +00001524 DbFixer sFix;
danielk197748dec7e2004-05-28 12:33:30 +00001525 Token *pName;
drha76b5df2002-02-23 02:32:10 +00001526
danielk197748dec7e2004-05-28 12:33:30 +00001527 sqlite3StartTable(pParse, pBegin, pName1, pName2, isTemp, 1);
drha76b5df2002-02-23 02:32:10 +00001528 p = pParse->pNewTable;
drhed6c8672003-01-12 18:02:16 +00001529 if( p==0 || pParse->nErr ){
danielk19774adee202004-05-08 08:23:19 +00001530 sqlite3SelectDelete(pSelect);
drh417be792002-03-03 18:59:40 +00001531 return;
1532 }
danielk1977ef2cb632004-05-29 02:37:19 +00001533 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk19774adee202004-05-08 08:23:19 +00001534 if( sqlite3FixInit(&sFix, pParse, p->iDb, "view", pName)
1535 && sqlite3FixSelect(&sFix, pSelect)
drhf26e09c2003-05-31 16:21:12 +00001536 ){
danielk19774adee202004-05-08 08:23:19 +00001537 sqlite3SelectDelete(pSelect);
drhf26e09c2003-05-31 16:21:12 +00001538 return;
1539 }
drh174b6192002-12-03 02:22:52 +00001540
drh4b59ab52002-08-24 18:24:51 +00001541 /* Make a copy of the entire SELECT statement that defines the view.
1542 ** This will force all the Expr.token.z values to be dynamically
1543 ** allocated rather than point to the input string - which means that
danielk197724b03fd2004-05-10 10:34:34 +00001544 ** they will persist after the current sqlite3_exec() call returns.
drh4b59ab52002-08-24 18:24:51 +00001545 */
danielk19774adee202004-05-08 08:23:19 +00001546 p->pSelect = sqlite3SelectDup(pSelect);
1547 sqlite3SelectDelete(pSelect);
drh1d85d932004-02-14 23:05:52 +00001548 if( !pParse->db->init.busy ){
danielk19774adee202004-05-08 08:23:19 +00001549 sqlite3ViewGetColumnNames(pParse, p);
drh417be792002-03-03 18:59:40 +00001550 }
drh4b59ab52002-08-24 18:24:51 +00001551
1552 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
1553 ** the end.
1554 */
drha76b5df2002-02-23 02:32:10 +00001555 sEnd = pParse->sLastToken;
1556 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
1557 sEnd.z += sEnd.n;
1558 }
1559 sEnd.n = 0;
drhb089c0b2004-06-26 14:46:39 +00001560 n = sEnd.z - pBegin->z;
drh4c755c02004-08-08 20:22:17 +00001561 z = (const unsigned char*)pBegin->z;
drh4ff6dfa2002-03-03 23:06:00 +00001562 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
1563 sEnd.z = &z[n-1];
1564 sEnd.n = 1;
drh4b59ab52002-08-24 18:24:51 +00001565
danielk19774adee202004-05-08 08:23:19 +00001566 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
1567 sqlite3EndTable(pParse, &sEnd, 0);
drha76b5df2002-02-23 02:32:10 +00001568 return;
drh417be792002-03-03 18:59:40 +00001569}
drhb7f91642004-10-31 02:22:47 +00001570#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001571
drhb7f91642004-10-31 02:22:47 +00001572#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001573/*
1574** The Table structure pTable is really a VIEW. Fill in the names of
1575** the columns of the view in the pTable structure. Return the number
jplyoncfa56842004-01-19 04:55:56 +00001576** of errors. If an error is seen leave an error message in pParse->zErrMsg.
drh417be792002-03-03 18:59:40 +00001577*/
danielk19774adee202004-05-08 08:23:19 +00001578int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
drh417be792002-03-03 18:59:40 +00001579 ExprList *pEList;
1580 Select *pSel;
1581 Table *pSelTab;
1582 int nErr = 0;
1583
1584 assert( pTable );
1585
1586 /* A positive nCol means the columns names for this view are
1587 ** already known.
1588 */
1589 if( pTable->nCol>0 ) return 0;
1590
1591 /* A negative nCol is a special marker meaning that we are currently
1592 ** trying to compute the column names. If we enter this routine with
1593 ** a negative nCol, it means two or more views form a loop, like this:
1594 **
1595 ** CREATE VIEW one AS SELECT * FROM two;
1596 ** CREATE VIEW two AS SELECT * FROM one;
drh3b167c72002-06-28 12:18:47 +00001597 **
1598 ** Actually, this error is caught previously and so the following test
1599 ** should always fail. But we will leave it in place just to be safe.
drh417be792002-03-03 18:59:40 +00001600 */
1601 if( pTable->nCol<0 ){
danielk19774adee202004-05-08 08:23:19 +00001602 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
drh417be792002-03-03 18:59:40 +00001603 return 1;
1604 }
1605
1606 /* If we get this far, it means we need to compute the table names.
1607 */
1608 assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
1609 pSel = pTable->pSelect;
1610
danielk19774adee202004-05-08 08:23:19 +00001611 /* Note that the call to sqlite3ResultSetOfSelect() will expand any
drh417be792002-03-03 18:59:40 +00001612 ** "*" elements in this list. But we will need to restore the list
1613 ** back to its original configuration afterwards, so we save a copy of
1614 ** the original in pEList.
1615 */
1616 pEList = pSel->pEList;
danielk19774adee202004-05-08 08:23:19 +00001617 pSel->pEList = sqlite3ExprListDup(pEList);
drh417be792002-03-03 18:59:40 +00001618 if( pSel->pEList==0 ){
1619 pSel->pEList = pEList;
1620 return 1; /* Malloc failed */
1621 }
1622 pTable->nCol = -1;
danielk19774adee202004-05-08 08:23:19 +00001623 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
drh417be792002-03-03 18:59:40 +00001624 if( pSelTab ){
1625 assert( pTable->aCol==0 );
1626 pTable->nCol = pSelTab->nCol;
1627 pTable->aCol = pSelTab->aCol;
1628 pSelTab->nCol = 0;
1629 pSelTab->aCol = 0;
danielk19774adee202004-05-08 08:23:19 +00001630 sqlite3DeleteTable(0, pSelTab);
drh8bf8dc92003-05-17 17:35:10 +00001631 DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
drh417be792002-03-03 18:59:40 +00001632 }else{
1633 pTable->nCol = 0;
1634 nErr++;
1635 }
danielk19774adee202004-05-08 08:23:19 +00001636 sqlite3SelectUnbind(pSel);
1637 sqlite3ExprListDelete(pSel->pEList);
drh417be792002-03-03 18:59:40 +00001638 pSel->pEList = pEList;
1639 return nErr;
1640}
drhb7f91642004-10-31 02:22:47 +00001641#endif /* SQLITE_OMIT_VIEW */
drh417be792002-03-03 18:59:40 +00001642
drhb7f91642004-10-31 02:22:47 +00001643#ifndef SQLITE_OMIT_VIEW
drh417be792002-03-03 18:59:40 +00001644/*
drh8bf8dc92003-05-17 17:35:10 +00001645** Clear the column names from every VIEW in database idx.
drh417be792002-03-03 18:59:40 +00001646*/
drh9bb575f2004-09-06 17:24:11 +00001647static void sqliteViewResetAll(sqlite3 *db, int idx){
drh417be792002-03-03 18:59:40 +00001648 HashElem *i;
drh8bf8dc92003-05-17 17:35:10 +00001649 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
drhd24cc422003-03-27 12:51:24 +00001650 for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
drh417be792002-03-03 18:59:40 +00001651 Table *pTab = sqliteHashData(i);
1652 if( pTab->pSelect ){
drh956bc922004-07-24 17:38:29 +00001653 sqliteResetColumnNames(pTab);
drh417be792002-03-03 18:59:40 +00001654 }
1655 }
drh8bf8dc92003-05-17 17:35:10 +00001656 DbClearProperty(db, idx, DB_UnresetViews);
drha76b5df2002-02-23 02:32:10 +00001657}
drhb7f91642004-10-31 02:22:47 +00001658#else
1659# define sqliteViewResetAll(A,B)
1660#endif /* SQLITE_OMIT_VIEW */
drha76b5df2002-02-23 02:32:10 +00001661
drh75897232000-05-29 14:26:00 +00001662/*
danielk1977a0bf2652004-11-04 14:30:04 +00001663** This function is called by the VDBE to adjust the internal schema
1664** used by SQLite when the btree layer moves a table root page. The
1665** root-page of a table or index in database iDb has changed from iFrom
1666** to iTo.
1667*/
1668#ifndef SQLITE_OMIT_AUTOVACUUM
1669void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
1670 HashElem *pElem;
1671
1672 for(pElem=sqliteHashFirst(&pDb->tblHash); pElem; pElem=sqliteHashNext(pElem)){
1673 Table *pTab = sqliteHashData(pElem);
1674 if( pTab->tnum==iFrom ){
1675 pTab->tnum = iTo;
1676 return;
1677 }
1678 }
1679 for(pElem=sqliteHashFirst(&pDb->idxHash); pElem; pElem=sqliteHashNext(pElem)){
1680 Index *pIdx = sqliteHashData(pElem);
1681 if( pIdx->tnum==iFrom ){
1682 pIdx->tnum = iTo;
1683 return;
1684 }
1685 }
1686 assert(0);
1687}
1688#endif
1689
1690/*
1691** Write code to erase the table with root-page iTable from database iDb.
1692** Also write code to modify the sqlite_master table and internal schema
1693** if a root-page of another table is moved by the btree-layer whilst
1694** erasing iTable (this can happen with an auto-vacuum database).
1695*/
drh4e0cff62004-11-05 05:10:28 +00001696static void destroyRootPage(Parse *pParse, int iTable, int iDb){
1697 Vdbe *v = sqlite3GetVdbe(pParse);
drh40e016e2004-11-04 14:47:11 +00001698 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
1699#ifndef SQLITE_OMIT_AUTOVACUUM
drh4e0cff62004-11-05 05:10:28 +00001700 /* OP_Destroy pushes an integer onto the stack. If this integer
1701 ** is non-zero, then it is the root page number of a table moved to
drh81db88e2004-12-07 12:29:17 +00001702 ** location iTable. The following code modifies the sqlite_master table to
drh4e0cff62004-11-05 05:10:28 +00001703 ** reflect this.
1704 **
1705 ** The "#0" in the SQL is a special constant that means whatever value
1706 ** is on the top of the stack. See sqlite3RegisterExpr().
1707 */
danielk197763e3e9f2004-11-05 09:19:27 +00001708 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001709 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
drh4e0cff62004-11-05 05:10:28 +00001710 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
danielk1977a0bf2652004-11-04 14:30:04 +00001711#endif
1712}
1713
1714/*
1715** Write VDBE code to erase table pTab and all associated indices on disk.
1716** Code to update the sqlite_master tables and internal schema definitions
1717** in case a root-page belonging to another table is moved by the btree layer
1718** is also added (this can happen with an auto-vacuum database).
1719*/
drh4e0cff62004-11-05 05:10:28 +00001720static void destroyTable(Parse *pParse, Table *pTab){
danielk1977a0bf2652004-11-04 14:30:04 +00001721#ifdef SQLITE_OMIT_AUTOVACUUM
drheee46cf2004-11-06 00:02:48 +00001722 Index *pIdx;
drh4e0cff62004-11-05 05:10:28 +00001723 destroyRootPage(pParse, pTab->tnum, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001724 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh7a638582004-11-05 05:23:59 +00001725 destroyRootPage(pParse, pIdx->tnum, pIdx->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001726 }
1727#else
1728 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
1729 ** is not defined), then it is important to call OP_Destroy on the
1730 ** table and index root-pages in order, starting with the numerically
1731 ** largest root-page number. This guarantees that none of the root-pages
1732 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
1733 ** following were coded:
1734 **
1735 ** OP_Destroy 4 0
1736 ** ...
1737 ** OP_Destroy 5 0
1738 **
1739 ** and root page 5 happened to be the largest root-page number in the
1740 ** database, then root page 5 would be moved to page 4 by the
1741 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
1742 ** a free-list page.
1743 */
1744 int iTab = pTab->tnum;
1745 int iDestroyed = 0;
1746
1747 while( 1 ){
1748 Index *pIdx;
1749 int iLargest = 0;
1750
1751 if( iDestroyed==0 || iTab<iDestroyed ){
1752 iLargest = iTab;
1753 }
1754 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1755 int iIdx = pIdx->tnum;
1756 assert( pIdx->iDb==pTab->iDb );
1757 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
1758 iLargest = iIdx;
1759 }
1760 }
1761 if( iLargest==0 ) return;
drh4e0cff62004-11-05 05:10:28 +00001762 destroyRootPage(pParse, iLargest, pTab->iDb);
danielk1977a0bf2652004-11-04 14:30:04 +00001763 iDestroyed = iLargest;
1764 }
1765#endif
1766}
1767
1768/*
drh75897232000-05-29 14:26:00 +00001769** This routine is called to do the work of a DROP TABLE statement.
drhd9b02572001-04-15 00:37:09 +00001770** pName is the name of the table to be dropped.
drh75897232000-05-29 14:26:00 +00001771*/
danielk1977a8858102004-05-28 12:11:21 +00001772void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView){
1773 Table *pTab;
drh75897232000-05-29 14:26:00 +00001774 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00001775 sqlite3 *db = pParse->db;
drhd24cc422003-03-27 12:51:24 +00001776 int iDb;
drh75897232000-05-29 14:26:00 +00001777
danielk1977a8858102004-05-28 12:11:21 +00001778 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_drop_table;
1779 assert( pName->nSrc==1 );
1780 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
1781
1782 if( pTab==0 ) goto exit_drop_table;
1783 iDb = pTab->iDb;
drhe22a3342003-04-22 20:30:37 +00001784 assert( iDb>=0 && iDb<db->nDb );
drhe5f9c642003-01-13 23:27:31 +00001785#ifndef SQLITE_OMIT_AUTHORIZATION
drhe5f9c642003-01-13 23:27:31 +00001786 {
1787 int code;
danielk1977a8858102004-05-28 12:11:21 +00001788 const char *zTab = SCHEMA_TABLE(pTab->iDb);
1789 const char *zDb = db->aDb[pTab->iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00001790 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
danielk1977a8858102004-05-28 12:11:21 +00001791 goto exit_drop_table;
drhe22a3342003-04-22 20:30:37 +00001792 }
drhe5f9c642003-01-13 23:27:31 +00001793 if( isView ){
drhd24cc422003-03-27 12:51:24 +00001794 if( iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001795 code = SQLITE_DROP_TEMP_VIEW;
1796 }else{
1797 code = SQLITE_DROP_VIEW;
1798 }
1799 }else{
drhd24cc422003-03-27 12:51:24 +00001800 if( iDb==1 ){
drhe5f9c642003-01-13 23:27:31 +00001801 code = SQLITE_DROP_TEMP_TABLE;
1802 }else{
1803 code = SQLITE_DROP_TABLE;
1804 }
1805 }
danielk1977a8858102004-05-28 12:11:21 +00001806 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
1807 goto exit_drop_table;
drhe5f9c642003-01-13 23:27:31 +00001808 }
danielk1977a8858102004-05-28 12:11:21 +00001809 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
1810 goto exit_drop_table;
drh77ad4e42003-01-14 02:49:27 +00001811 }
drhe5f9c642003-01-13 23:27:31 +00001812 }
1813#endif
drhf3388142004-11-13 03:48:06 +00001814 if( pTab->readOnly || pTab==db->aDb[iDb].pSeqTab ){
danielk1977a8858102004-05-28 12:11:21 +00001815 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
danielk1977a8858102004-05-28 12:11:21 +00001816 goto exit_drop_table;
drh75897232000-05-29 14:26:00 +00001817 }
danielk1977a8858102004-05-28 12:11:21 +00001818 if( isView && pTab->pSelect==0 ){
1819 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
1820 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001821 }
danielk1977a8858102004-05-28 12:11:21 +00001822 if( !isView && pTab->pSelect ){
1823 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
1824 goto exit_drop_table;
drh4ff6dfa2002-03-03 23:06:00 +00001825 }
drh75897232000-05-29 14:26:00 +00001826
drh1ccde152000-06-17 13:12:39 +00001827 /* Generate code to remove the table from the master table
1828 ** on disk.
1829 */
danielk19774adee202004-05-08 08:23:19 +00001830 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00001831 if( v ){
drhe0bc4042002-06-25 01:09:11 +00001832 Trigger *pTrigger;
drh2958a4e2004-11-12 03:56:15 +00001833 int iDb = pTab->iDb;
1834 Db *pDb = &db->aDb[iDb];
1835 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh8bf8dc92003-05-17 17:35:10 +00001836
danielk19778e227872004-06-07 07:52:17 +00001837 /* Drop all triggers associated with the table being dropped. Code
1838 ** is generated to remove entries from sqlite_master and/or
1839 ** sqlite_temp_master if required.
1840 */
danielk1977a8858102004-05-28 12:11:21 +00001841 pTrigger = pTab->pTrigger;
drhe0bc4042002-06-25 01:09:11 +00001842 while( pTrigger ){
drh2958a4e2004-11-12 03:56:15 +00001843 assert( pTrigger->iDb==iDb || pTrigger->iDb==1 );
danielk19774adee202004-05-08 08:23:19 +00001844 sqlite3DropTriggerPtr(pParse, pTrigger, 1);
drh956bc922004-07-24 17:38:29 +00001845 pTrigger = pTrigger->pNext;
danielk1977c3f9bad2002-05-15 08:30:12 +00001846 }
drh8bf8dc92003-05-17 17:35:10 +00001847
danielk19774d36b812004-11-19 07:07:30 +00001848#ifndef SQLITE_OMIT_AUTOINCREMENT
1849 /* Remove any entries of the sqlite_sequence table associated with
1850 ** the table being dropped. This is done before the table is dropped
1851 ** at the btree level, in case the sqlite_sequence table needs to
1852 ** move as a result of the drop (can happen in auto-vacuum mode).
1853 */
1854 if( pTab->autoInc ){
1855 sqlite3NestedParse(pParse,
1856 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
1857 pDb->zName, pTab->zName
1858 );
1859 }
1860#endif
1861
danielk19778e227872004-06-07 07:52:17 +00001862 /* Drop all SQLITE_MASTER table and index entries that refer to the
1863 ** table. The program name loops through the master table and deletes
1864 ** every row that refers to a table of the same name as the one being
1865 ** dropped. Triggers are handled seperately because a trigger can be
1866 ** created in the temp database that refers to a table in another
1867 ** database.
1868 */
drhf1974842004-11-05 03:56:00 +00001869 sqlite3NestedParse(pParse,
drh4794f732004-11-05 17:17:50 +00001870 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
drh2958a4e2004-11-12 03:56:15 +00001871 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
drh4ff6dfa2002-03-03 23:06:00 +00001872 if( !isView ){
drh4e0cff62004-11-05 05:10:28 +00001873 destroyTable(pParse, pTab);
drh5e00f6c2001-09-13 13:46:56 +00001874 }
drh2958a4e2004-11-12 03:56:15 +00001875
drh2958a4e2004-11-12 03:56:15 +00001876 /* Remove the table entry from SQLite's internal schema
1877 */
1878 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
drh75897232000-05-29 14:26:00 +00001879 }
drhd24cc422003-03-27 12:51:24 +00001880 sqliteViewResetAll(db, iDb);
danielk1977a8858102004-05-28 12:11:21 +00001881
1882exit_drop_table:
1883 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00001884}
1885
1886/*
drhc2eef3b2002-08-31 18:53:06 +00001887** This routine is called to create a new foreign key on the table
1888** currently under construction. pFromCol determines which columns
1889** in the current table point to the foreign key. If pFromCol==0 then
1890** connect the key to the last column inserted. pTo is the name of
1891** the table referred to. pToCol is a list of tables in the other
1892** pTo table that the foreign key points to. flags contains all
1893** information about the conflict resolution algorithms specified
1894** in the ON DELETE, ON UPDATE and ON INSERT clauses.
1895**
1896** An FKey structure is created and added to the table currently
1897** under construction in the pParse->pNewTable field. The new FKey
1898** is not linked into db->aFKey at this point - that does not happen
danielk19774adee202004-05-08 08:23:19 +00001899** until sqlite3EndTable().
drhc2eef3b2002-08-31 18:53:06 +00001900**
1901** The foreign key is set for IMMEDIATE processing. A subsequent call
danielk19774adee202004-05-08 08:23:19 +00001902** to sqlite3DeferForeignKey() might change this to DEFERRED.
drhc2eef3b2002-08-31 18:53:06 +00001903*/
danielk19774adee202004-05-08 08:23:19 +00001904void sqlite3CreateForeignKey(
drhc2eef3b2002-08-31 18:53:06 +00001905 Parse *pParse, /* Parsing context */
danielk19770202b292004-06-09 09:55:16 +00001906 ExprList *pFromCol, /* Columns in this table that point to other table */
drhc2eef3b2002-08-31 18:53:06 +00001907 Token *pTo, /* Name of the other table */
danielk19770202b292004-06-09 09:55:16 +00001908 ExprList *pToCol, /* Columns in the other table */
drhc2eef3b2002-08-31 18:53:06 +00001909 int flags /* Conflict resolution algorithms. */
1910){
drhb7f91642004-10-31 02:22:47 +00001911#ifndef SQLITE_OMIT_FOREIGN_KEY
drh40e016e2004-11-04 14:47:11 +00001912 FKey *pFKey = 0;
drhc2eef3b2002-08-31 18:53:06 +00001913 Table *p = pParse->pNewTable;
1914 int nByte;
1915 int i;
1916 int nCol;
1917 char *z;
drhc2eef3b2002-08-31 18:53:06 +00001918
1919 assert( pTo!=0 );
1920 if( p==0 || pParse->nErr ) goto fk_end;
1921 if( pFromCol==0 ){
1922 int iCol = p->nCol-1;
1923 if( iCol<0 ) goto fk_end;
danielk19770202b292004-06-09 09:55:16 +00001924 if( pToCol && pToCol->nExpr!=1 ){
danielk19774adee202004-05-08 08:23:19 +00001925 sqlite3ErrorMsg(pParse, "foreign key on %s"
drhf7a9e1a2004-02-22 18:40:56 +00001926 " should reference only one column of table %T",
1927 p->aCol[iCol].zName, pTo);
drhc2eef3b2002-08-31 18:53:06 +00001928 goto fk_end;
1929 }
1930 nCol = 1;
danielk19770202b292004-06-09 09:55:16 +00001931 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
danielk19774adee202004-05-08 08:23:19 +00001932 sqlite3ErrorMsg(pParse,
drhc2eef3b2002-08-31 18:53:06 +00001933 "number of columns in foreign key does not match the number of "
drhf7a9e1a2004-02-22 18:40:56 +00001934 "columns in the referenced table");
drhc2eef3b2002-08-31 18:53:06 +00001935 goto fk_end;
1936 }else{
danielk19770202b292004-06-09 09:55:16 +00001937 nCol = pFromCol->nExpr;
drhc2eef3b2002-08-31 18:53:06 +00001938 }
1939 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
1940 if( pToCol ){
danielk19770202b292004-06-09 09:55:16 +00001941 for(i=0; i<pToCol->nExpr; i++){
drhc2eef3b2002-08-31 18:53:06 +00001942 nByte += strlen(pToCol->a[i].zName) + 1;
1943 }
1944 }
1945 pFKey = sqliteMalloc( nByte );
1946 if( pFKey==0 ) goto fk_end;
1947 pFKey->pFrom = p;
1948 pFKey->pNextFrom = p->pFKey;
drhdf68f6b2002-09-21 15:57:57 +00001949 z = (char*)&pFKey[1];
1950 pFKey->aCol = (struct sColMap*)z;
1951 z += sizeof(struct sColMap)*nCol;
1952 pFKey->zTo = z;
drhc2eef3b2002-08-31 18:53:06 +00001953 memcpy(z, pTo->z, pTo->n);
1954 z[pTo->n] = 0;
1955 z += pTo->n+1;
1956 pFKey->pNextTo = 0;
1957 pFKey->nCol = nCol;
drhc2eef3b2002-08-31 18:53:06 +00001958 if( pFromCol==0 ){
1959 pFKey->aCol[0].iFrom = p->nCol-1;
1960 }else{
1961 for(i=0; i<nCol; i++){
1962 int j;
1963 for(j=0; j<p->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00001964 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
drhc2eef3b2002-08-31 18:53:06 +00001965 pFKey->aCol[i].iFrom = j;
1966 break;
1967 }
1968 }
1969 if( j>=p->nCol ){
danielk19774adee202004-05-08 08:23:19 +00001970 sqlite3ErrorMsg(pParse,
drhf7a9e1a2004-02-22 18:40:56 +00001971 "unknown column \"%s\" in foreign key definition",
1972 pFromCol->a[i].zName);
drhc2eef3b2002-08-31 18:53:06 +00001973 goto fk_end;
1974 }
1975 }
1976 }
1977 if( pToCol ){
1978 for(i=0; i<nCol; i++){
1979 int n = strlen(pToCol->a[i].zName);
1980 pFKey->aCol[i].zCol = z;
1981 memcpy(z, pToCol->a[i].zName, n);
1982 z[n] = 0;
1983 z += n+1;
1984 }
1985 }
1986 pFKey->isDeferred = 0;
1987 pFKey->deleteConf = flags & 0xff;
1988 pFKey->updateConf = (flags >> 8 ) & 0xff;
1989 pFKey->insertConf = (flags >> 16 ) & 0xff;
1990
1991 /* Link the foreign key to the table as the last step.
1992 */
1993 p->pFKey = pFKey;
1994 pFKey = 0;
1995
1996fk_end:
1997 sqliteFree(pFKey);
drhb7f91642004-10-31 02:22:47 +00001998#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
danielk19770202b292004-06-09 09:55:16 +00001999 sqlite3ExprListDelete(pFromCol);
2000 sqlite3ExprListDelete(pToCol);
drhc2eef3b2002-08-31 18:53:06 +00002001}
2002
2003/*
2004** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
2005** clause is seen as part of a foreign key definition. The isDeferred
2006** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
2007** The behavior of the most recently created foreign key is adjusted
2008** accordingly.
2009*/
danielk19774adee202004-05-08 08:23:19 +00002010void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
drhb7f91642004-10-31 02:22:47 +00002011#ifndef SQLITE_OMIT_FOREIGN_KEY
drhc2eef3b2002-08-31 18:53:06 +00002012 Table *pTab;
2013 FKey *pFKey;
2014 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
2015 pFKey->isDeferred = isDeferred;
drhb7f91642004-10-31 02:22:47 +00002016#endif
drhc2eef3b2002-08-31 18:53:06 +00002017}
2018
2019/*
drh063336a2004-11-05 20:58:39 +00002020** Generate code that will erase and refill index *pIdx. This is
2021** used to initialize a newly created index or to recompute the
2022** content of an index in response to a REINDEX command.
2023**
2024** if memRootPage is not negative, it means that the index is newly
2025** created. The memory cell specified by memRootPage contains the
2026** root page number of the index. If memRootPage is negative, then
2027** the index already exists and must be cleared before being refilled and
2028** the root page number of the index is taken from pIndex->tnum.
2029*/
2030static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
2031 Table *pTab = pIndex->pTable; /* The table that is indexed */
2032 int iTab = pParse->nTab; /* Btree cursor used for pTab */
2033 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
2034 int addr1; /* Address of top of loop */
2035 int tnum; /* Root page of index */
2036 Vdbe *v; /* Generate code into this virtual machine */
drh4343fea2004-11-05 23:46:15 +00002037 int isUnique; /* True for a unique index */
drh063336a2004-11-05 20:58:39 +00002038
danielk19771d54df82004-11-23 15:41:16 +00002039#ifndef SQLITE_OMIT_AUTHORIZATION
2040 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
2041 pParse->db->aDb[pIndex->iDb].zName ) ){
2042 return;
2043 }
2044#endif
2045
drh063336a2004-11-05 20:58:39 +00002046 v = sqlite3GetVdbe(pParse);
2047 if( v==0 ) return;
2048 if( memRootPage>=0 ){
2049 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
2050 tnum = 0;
2051 }else{
2052 tnum = pIndex->tnum;
2053 sqlite3VdbeAddOp(v, OP_Clear, tnum, pIndex->iDb);
2054 }
2055 sqlite3VdbeAddOp(v, OP_Integer, pIndex->iDb, 0);
2056 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum,
2057 (char*)&pIndex->keyInfo, P3_KEYINFO);
2058 sqlite3VdbeAddOp(v, OP_Integer, pTab->iDb, 0);
2059 sqlite3VdbeAddOp(v, OP_OpenRead, iTab, pTab->tnum);
2060 sqlite3VdbeAddOp(v, OP_SetNumColumns, iTab, pTab->nCol);
2061 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
2062 sqlite3GenerateIndexKey(v, pIndex, iTab);
drh4343fea2004-11-05 23:46:15 +00002063 isUnique = pIndex->onError!=OE_None;
2064 sqlite3VdbeAddOp(v, OP_IdxPut, iIdx, isUnique);
2065 if( isUnique ){
2066 sqlite3VdbeChangeP3(v, -1, "indexed columns are not unique", P3_STATIC);
2067 }
drh063336a2004-11-05 20:58:39 +00002068 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
2069 sqlite3VdbeChangeP2(v, addr1, sqlite3VdbeCurrentAddr(v));
2070 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
2071 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
2072}
2073
2074/*
drh23bf66d2004-12-14 03:34:34 +00002075** Create a new index for an SQL table. pName1.pName2 is the name of the index
2076** and pTblList is the name of the table that is to be indexed. Both will
drhadbca9c2001-09-27 15:11:53 +00002077** be NULL for a primary key or an index that is created to satisfy a
2078** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
drh382c0242001-10-06 16:33:02 +00002079** as the table to be indexed. pParse->pNewTable is a table that is
2080** currently being constructed by a CREATE TABLE statement.
drh75897232000-05-29 14:26:00 +00002081**
drh382c0242001-10-06 16:33:02 +00002082** pList is a list of columns to be indexed. pList will be NULL if this
2083** is a primary key or unique-constraint on the most recent column added
2084** to the table currently under construction.
drh75897232000-05-29 14:26:00 +00002085*/
danielk19774adee202004-05-08 08:23:19 +00002086void sqlite3CreateIndex(
drh23bf66d2004-12-14 03:34:34 +00002087 Parse *pParse, /* All information about this parse */
2088 Token *pName1, /* First part of index name. May be NULL */
2089 Token *pName2, /* Second part of index name. May be NULL */
2090 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
danielk19770202b292004-06-09 09:55:16 +00002091 ExprList *pList, /* A list of columns to be indexed */
drh23bf66d2004-12-14 03:34:34 +00002092 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
2093 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
2094 Token *pEnd /* The ")" that closes the CREATE INDEX statement */
drh75897232000-05-29 14:26:00 +00002095){
drh23bf66d2004-12-14 03:34:34 +00002096 Table *pTab = 0; /* Table to be indexed */
danielk1977d8123362004-06-12 09:25:12 +00002097 Index *pIndex = 0; /* The index to be created */
drh75897232000-05-29 14:26:00 +00002098 char *zName = 0;
drhbeae3192001-09-22 18:12:08 +00002099 int i, j;
drhf26e09c2003-05-31 16:21:12 +00002100 Token nullId; /* Fake token for an empty ID list */
2101 DbFixer sFix; /* For assigning database names to pTable */
drh4925ca02003-11-27 00:48:57 +00002102 int isTemp; /* True for a temporary index */
drh9bb575f2004-09-06 17:24:11 +00002103 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002104
danielk1977cbb18d22004-05-28 11:37:27 +00002105 int iDb; /* Index of the database that is being written */
2106 Token *pName = 0; /* Unqualified name of the index to create */
2107
danielk197724b03fd2004-05-10 10:34:34 +00002108 if( pParse->nErr || sqlite3_malloc_failed ) goto exit_create_index;
drhdaffd0e2001-04-11 14:28:42 +00002109
drh75897232000-05-29 14:26:00 +00002110 /*
2111 ** Find the table that is to be indexed. Return early if not found.
2112 */
danielk1977cbb18d22004-05-28 11:37:27 +00002113 if( pTblName!=0 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002114
2115 /* Use the two-part index name to determine the database
danielk1977ef2cb632004-05-29 02:37:19 +00002116 ** to search for the table. 'Fix' the table name to this db
2117 ** before looking up the table.
danielk1977cbb18d22004-05-28 11:37:27 +00002118 */
2119 assert( pName1 && pName2 );
danielk1977ef2cb632004-05-29 02:37:19 +00002120 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
danielk1977cbb18d22004-05-28 11:37:27 +00002121 if( iDb<0 ) goto exit_create_index;
2122
danielk1977ef2cb632004-05-29 02:37:19 +00002123 /* If the index name was unqualified, check if the the table
2124 ** is a temp table. If so, set the database to 1.
danielk1977cbb18d22004-05-28 11:37:27 +00002125 */
danielk1977ef2cb632004-05-29 02:37:19 +00002126 pTab = sqlite3SrcListLookup(pParse, pTblName);
2127 if( pName2 && pName2->n==0 && pTab && pTab->iDb==1 ){
2128 iDb = 1;
2129 }
2130
2131 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
2132 sqlite3FixSrcList(&sFix, pTblName)
2133 ){
danielk1977cbb18d22004-05-28 11:37:27 +00002134 goto exit_create_index;
2135 }
danielk1977ef2cb632004-05-29 02:37:19 +00002136 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
2137 pTblName->a[0].zDatabase);
danielk1977cbb18d22004-05-28 11:37:27 +00002138 if( !pTab ) goto exit_create_index;
danielk1977ef2cb632004-05-29 02:37:19 +00002139 assert( iDb==pTab->iDb );
drh75897232000-05-29 14:26:00 +00002140 }else{
drhe3c41372001-09-17 20:25:58 +00002141 assert( pName==0 );
drh75897232000-05-29 14:26:00 +00002142 pTab = pParse->pNewTable;
danielk1977cbb18d22004-05-28 11:37:27 +00002143 iDb = pTab->iDb;
drh75897232000-05-29 14:26:00 +00002144 }
danielk1977cbb18d22004-05-28 11:37:27 +00002145
drh75897232000-05-29 14:26:00 +00002146 if( pTab==0 || pParse->nErr ) goto exit_create_index;
drh0be9df02003-03-30 00:19:49 +00002147 if( pTab->readOnly ){
danielk19774adee202004-05-08 08:23:19 +00002148 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
drh0be9df02003-03-30 00:19:49 +00002149 goto exit_create_index;
2150 }
drha76b5df2002-02-23 02:32:10 +00002151 if( pTab->pSelect ){
danielk19774adee202004-05-08 08:23:19 +00002152 sqlite3ErrorMsg(pParse, "views may not be indexed");
drha76b5df2002-02-23 02:32:10 +00002153 goto exit_create_index;
2154 }
drh4925ca02003-11-27 00:48:57 +00002155 isTemp = pTab->iDb==1;
drh75897232000-05-29 14:26:00 +00002156
2157 /*
2158 ** Find the name of the index. Make sure there is not already another
drhf57b3392001-10-08 13:22:32 +00002159 ** index or table with the same name.
2160 **
2161 ** Exception: If we are reading the names of permanent indices from the
2162 ** sqlite_master table (because some other process changed the schema) and
2163 ** one of the index names collides with the name of a temporary table or
drhd24cc422003-03-27 12:51:24 +00002164 ** index, then we will continue to process this index.
drhf57b3392001-10-08 13:22:32 +00002165 **
2166 ** If pName==0 it means that we are
drhadbca9c2001-09-27 15:11:53 +00002167 ** dealing with a primary key or UNIQUE constraint. We have to invent our
2168 ** own name.
drh75897232000-05-29 14:26:00 +00002169 */
danielk1977d8123362004-06-12 09:25:12 +00002170 if( pName ){
drha99db3b2004-06-19 14:49:12 +00002171 zName = sqlite3NameFromToken(pName);
danielk19778a414492004-06-29 08:59:35 +00002172 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002173 if( zName==0 ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002174 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
drhd24cc422003-03-27 12:51:24 +00002175 goto exit_create_index;
drhe3c41372001-09-17 20:25:58 +00002176 }
danielk1977d8123362004-06-12 09:25:12 +00002177 if( !db->init.busy ){
2178 Index *pISameName; /* Another index with the same name */
2179 Table *pTSameName; /* A table with same name as the index */
danielk19778a414492004-06-29 08:59:35 +00002180 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
danielk1977d8123362004-06-12 09:25:12 +00002181 if( (pISameName = sqlite3FindIndex(db, zName, db->aDb[iDb].zName))!=0 ){
2182 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
2183 goto exit_create_index;
2184 }
2185 if( (pTSameName = sqlite3FindTable(db, zName, 0))!=0 ){
2186 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
2187 goto exit_create_index;
2188 }
drhe3c41372001-09-17 20:25:58 +00002189 }
drhd24cc422003-03-27 12:51:24 +00002190 }else if( pName==0 ){
drhadbca9c2001-09-27 15:11:53 +00002191 char zBuf[30];
2192 int n;
2193 Index *pLoop;
2194 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
danielk1977d8123362004-06-12 09:25:12 +00002195 sprintf(zBuf,"_%d",n);
drh75897232000-05-29 14:26:00 +00002196 zName = 0;
danielk1977d8123362004-06-12 09:25:12 +00002197 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
drhe3c41372001-09-17 20:25:58 +00002198 if( zName==0 ) goto exit_create_index;
drh75897232000-05-29 14:26:00 +00002199 }
2200
drhe5f9c642003-01-13 23:27:31 +00002201 /* Check for authorization to create an index.
2202 */
2203#ifndef SQLITE_OMIT_AUTHORIZATION
drhe22a3342003-04-22 20:30:37 +00002204 {
2205 const char *zDb = db->aDb[pTab->iDb].zName;
danielk19774adee202004-05-08 08:23:19 +00002206 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002207 goto exit_create_index;
2208 }
2209 i = SQLITE_CREATE_INDEX;
2210 if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002211 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
drhe22a3342003-04-22 20:30:37 +00002212 goto exit_create_index;
2213 }
drhe5f9c642003-01-13 23:27:31 +00002214 }
2215#endif
2216
drh75897232000-05-29 14:26:00 +00002217 /* If pList==0, it means this routine was called to make a primary
drh1ccde152000-06-17 13:12:39 +00002218 ** key out of the last column added to the table under construction.
drh75897232000-05-29 14:26:00 +00002219 ** So create a fake list to simulate this.
2220 */
2221 if( pList==0 ){
drh7020f652000-06-03 18:06:52 +00002222 nullId.z = pTab->aCol[pTab->nCol-1].zName;
drh75897232000-05-29 14:26:00 +00002223 nullId.n = strlen(nullId.z);
danielk19770202b292004-06-09 09:55:16 +00002224 pList = sqlite3ExprListAppend(0, 0, &nullId);
drh75897232000-05-29 14:26:00 +00002225 if( pList==0 ) goto exit_create_index;
2226 }
2227
2228 /*
2229 ** Allocate the index structure.
2230 */
drhdcc581c2000-05-30 13:44:19 +00002231 pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
danielk19770202b292004-06-09 09:55:16 +00002232 (sizeof(int) + sizeof(CollSeq*))*pList->nExpr );
drhdaffd0e2001-04-11 14:28:42 +00002233 if( pIndex==0 ) goto exit_create_index;
danielk19770202b292004-06-09 09:55:16 +00002234 pIndex->aiColumn = (int*)&pIndex->keyInfo.aColl[pList->nExpr];
2235 pIndex->zName = (char*)&pIndex->aiColumn[pList->nExpr];
drh75897232000-05-29 14:26:00 +00002236 strcpy(pIndex->zName, zName);
2237 pIndex->pTable = pTab;
danielk19770202b292004-06-09 09:55:16 +00002238 pIndex->nColumn = pList->nExpr;
drhea1ba172003-04-20 00:00:23 +00002239 pIndex->onError = onError;
drh485b39b2002-07-13 03:11:52 +00002240 pIndex->autoIndex = pName==0;
danielk1977cbb18d22004-05-28 11:37:27 +00002241 pIndex->iDb = iDb;
drh75897232000-05-29 14:26:00 +00002242
drh1ccde152000-06-17 13:12:39 +00002243 /* Scan the names of the columns of the table to be indexed and
2244 ** load the column indices into the Index structure. Report an error
2245 ** if any column is not found.
drh75897232000-05-29 14:26:00 +00002246 */
danielk19770202b292004-06-09 09:55:16 +00002247 for(i=0; i<pList->nExpr; i++){
drh75897232000-05-29 14:26:00 +00002248 for(j=0; j<pTab->nCol; j++){
danielk19774adee202004-05-08 08:23:19 +00002249 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
drh75897232000-05-29 14:26:00 +00002250 }
2251 if( j>=pTab->nCol ){
danielk19774adee202004-05-08 08:23:19 +00002252 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
drhf7a9e1a2004-02-22 18:40:56 +00002253 pTab->zName, pList->a[i].zName);
drh75897232000-05-29 14:26:00 +00002254 goto exit_create_index;
2255 }
drh967e8b72000-06-21 13:59:10 +00002256 pIndex->aiColumn[i] = j;
danielk19770202b292004-06-09 09:55:16 +00002257 if( pList->a[i].pExpr ){
2258 assert( pList->a[i].pExpr->pColl );
2259 pIndex->keyInfo.aColl[i] = pList->a[i].pExpr->pColl;
2260 }else{
2261 pIndex->keyInfo.aColl[i] = pTab->aCol[j].pColl;
2262 }
2263 assert( pIndex->keyInfo.aColl[i] );
danielk19777cedc8d2004-06-10 10:50:08 +00002264 if( !db->init.busy &&
2265 sqlite3CheckCollSeq(pParse, pIndex->keyInfo.aColl[i])
2266 ){
2267 goto exit_create_index;
2268 }
drh75897232000-05-29 14:26:00 +00002269 }
danielk19770202b292004-06-09 09:55:16 +00002270 pIndex->keyInfo.nField = pList->nExpr;
drh75897232000-05-29 14:26:00 +00002271
danielk1977d8123362004-06-12 09:25:12 +00002272 if( pTab==pParse->pNewTable ){
2273 /* This routine has been called to create an automatic index as a
2274 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
2275 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
2276 ** i.e. one of:
2277 **
2278 ** CREATE TABLE t(x PRIMARY KEY, y);
2279 ** CREATE TABLE t(x, y, UNIQUE(x, y));
2280 **
2281 ** Either way, check to see if the table already has such an index. If
2282 ** so, don't bother creating this one. This only applies to
2283 ** automatically created indices. Users can do as they wish with
2284 ** explicit indices.
2285 */
2286 Index *pIdx;
2287 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2288 int k;
2289 assert( pIdx->onError!=OE_None );
2290 assert( pIdx->autoIndex );
2291 assert( pIndex->onError!=OE_None );
2292
2293 if( pIdx->nColumn!=pIndex->nColumn ) continue;
2294 for(k=0; k<pIdx->nColumn; k++){
2295 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
2296 if( pIdx->keyInfo.aColl[k]!=pIndex->keyInfo.aColl[k] ) break;
2297 }
2298 if( k==pIdx->nColumn ){
danielk1977f736b772004-06-17 06:13:34 +00002299 if( pIdx->onError!=pIndex->onError ){
2300 /* This constraint creates the same index as a previous
2301 ** constraint specified somewhere in the CREATE TABLE statement.
2302 ** However the ON CONFLICT clauses are different. If both this
2303 ** constraint and the previous equivalent constraint have explicit
2304 ** ON CONFLICT clauses this is an error. Otherwise, use the
2305 ** explicitly specified behaviour for the index.
2306 */
2307 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
2308 sqlite3ErrorMsg(pParse,
2309 "conflicting ON CONFLICT clauses specified", 0);
2310 }
2311 if( pIdx->onError==OE_Default ){
2312 pIdx->onError = pIndex->onError;
2313 }
2314 }
danielk1977d8123362004-06-12 09:25:12 +00002315 goto exit_create_index;
2316 }
2317 }
2318 }
2319
drh75897232000-05-29 14:26:00 +00002320 /* Link the new Index structure to its table and to the other
drhadbca9c2001-09-27 15:11:53 +00002321 ** in-memory database structures.
drh75897232000-05-29 14:26:00 +00002322 */
drh234c39d2004-07-24 03:30:47 +00002323 if( db->init.busy ){
drh6d4abfb2001-10-22 02:58:08 +00002324 Index *p;
danielk19774adee202004-05-08 08:23:19 +00002325 p = sqlite3HashInsert(&db->aDb[pIndex->iDb].idxHash,
drh3c8bf552003-07-01 18:13:14 +00002326 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
drh6d4abfb2001-10-22 02:58:08 +00002327 if( p ){
2328 assert( p==pIndex ); /* Malloc must have failed */
drh6d4abfb2001-10-22 02:58:08 +00002329 goto exit_create_index;
2330 }
drh5e00f6c2001-09-13 13:46:56 +00002331 db->flags |= SQLITE_InternChanges;
drh234c39d2004-07-24 03:30:47 +00002332 if( pTblName!=0 ){
2333 pIndex->tnum = db->init.newTnum;
2334 }
drhd78eeee2001-09-13 16:18:53 +00002335 }
2336
drh1d85d932004-02-14 23:05:52 +00002337 /* If the db->init.busy is 0 then create the index on disk. This
drh75897232000-05-29 14:26:00 +00002338 ** involves writing the index into the master table and filling in the
2339 ** index with the current table contents.
2340 **
drh1d85d932004-02-14 23:05:52 +00002341 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
2342 ** command. db->init.busy is 1 when a database is opened and
drh75897232000-05-29 14:26:00 +00002343 ** CREATE INDEX statements are read out of the master table. In
2344 ** the latter case the index already exists on disk, which is why
2345 ** we don't want to recreate it.
drh5edc3122001-09-13 21:53:09 +00002346 **
danielk1977cbb18d22004-05-28 11:37:27 +00002347 ** If pTblName==0 it means this index is generated as a primary key
drh382c0242001-10-06 16:33:02 +00002348 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
2349 ** has just been created, it contains no data and the index initialization
2350 ** step can be skipped.
drh75897232000-05-29 14:26:00 +00002351 */
drh1d85d932004-02-14 23:05:52 +00002352 else if( db->init.busy==0 ){
drhadbca9c2001-09-27 15:11:53 +00002353 Vdbe *v;
drh063336a2004-11-05 20:58:39 +00002354 char *zStmt;
2355 int iMem = pParse->nMem++;
drh75897232000-05-29 14:26:00 +00002356
danielk19774adee202004-05-08 08:23:19 +00002357 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002358 if( v==0 ) goto exit_create_index;
drh063336a2004-11-05 20:58:39 +00002359
2360 /* Create the rootpage for the index
2361 */
2362 sqlite3BeginWriteOperation(pParse, 0, iDb);
drh234c39d2004-07-24 03:30:47 +00002363 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
drh063336a2004-11-05 20:58:39 +00002364 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2365
2366 /* Gather the complete text of the CREATE INDEX statement into
2367 ** the zStmt variable
2368 */
drhe0bc4042002-06-25 01:09:11 +00002369 if( pStart && pEnd ){
drh063336a2004-11-05 20:58:39 +00002370 /* A named index with an explicit CREATE INDEX statement */
danielk19779fd2a9a2004-11-12 13:42:30 +00002371 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
drh063336a2004-11-05 20:58:39 +00002372 onError==OE_None ? "" : " UNIQUE",
2373 Addr(pEnd->z) - Addr(pName->z) + 1,
2374 pName->z);
2375 }else{
2376 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
drhe497f002004-11-07 13:01:49 +00002377 /* zStmt = sqlite3MPrintf(""); */
2378 zStmt = 0;
drh75897232000-05-29 14:26:00 +00002379 }
drh063336a2004-11-05 20:58:39 +00002380
2381 /* Add an entry in sqlite_master for this index
2382 */
2383 sqlite3NestedParse(pParse,
drhe497f002004-11-07 13:01:49 +00002384 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
drh063336a2004-11-05 20:58:39 +00002385 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2386 pIndex->zName,
2387 pTab->zName,
2388 zStmt
2389 );
2390 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2391 sqliteFree(zStmt);
2392
2393 /* Fill the index with data and reparse the schema
2394 */
danielk1977cbb18d22004-05-28 11:37:27 +00002395 if( pTblName ){
drh063336a2004-11-05 20:58:39 +00002396 sqlite3RefillIndex(pParse, pIndex, iMem);
drhc275b4e2004-07-19 17:25:24 +00002397 sqlite3ChangeCookie(db, v, iDb);
drh234c39d2004-07-24 03:30:47 +00002398 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
2399 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
drh5e00f6c2001-09-13 13:46:56 +00002400 }
drh75897232000-05-29 14:26:00 +00002401 }
2402
danielk1977d8123362004-06-12 09:25:12 +00002403 /* When adding an index to the list of indices for a table, make
2404 ** sure all indices labeled OE_Replace come after all those labeled
2405 ** OE_Ignore. This is necessary for the correct operation of UPDATE
2406 ** and INSERT.
2407 */
drh234c39d2004-07-24 03:30:47 +00002408 if( db->init.busy || pTblName==0 ){
2409 if( onError!=OE_Replace || pTab->pIndex==0
2410 || pTab->pIndex->onError==OE_Replace){
2411 pIndex->pNext = pTab->pIndex;
2412 pTab->pIndex = pIndex;
2413 }else{
2414 Index *pOther = pTab->pIndex;
2415 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
2416 pOther = pOther->pNext;
2417 }
2418 pIndex->pNext = pOther->pNext;
2419 pOther->pNext = pIndex;
danielk1977d8123362004-06-12 09:25:12 +00002420 }
drh234c39d2004-07-24 03:30:47 +00002421 pIndex = 0;
danielk1977d8123362004-06-12 09:25:12 +00002422 }
danielk1977d8123362004-06-12 09:25:12 +00002423
drh75897232000-05-29 14:26:00 +00002424 /* Clean up before exiting */
2425exit_create_index:
drh956bc922004-07-24 17:38:29 +00002426 if( pIndex ){
2427 freeIndex(pIndex);
2428 }
danielk19770202b292004-06-09 09:55:16 +00002429 sqlite3ExprListDelete(pList);
danielk1977e0048402004-06-15 16:51:01 +00002430 sqlite3SrcListDelete(pTblName);
drh75897232000-05-29 14:26:00 +00002431 sqliteFree(zName);
2432 return;
2433}
2434
2435/*
drh74e24cd2002-01-09 03:19:59 +00002436** This routine will drop an existing named index. This routine
2437** implements the DROP INDEX statement.
drh75897232000-05-29 14:26:00 +00002438*/
danielk19774adee202004-05-08 08:23:19 +00002439void sqlite3DropIndex(Parse *pParse, SrcList *pName){
drh75897232000-05-29 14:26:00 +00002440 Index *pIndex;
drh75897232000-05-29 14:26:00 +00002441 Vdbe *v;
drh9bb575f2004-09-06 17:24:11 +00002442 sqlite3 *db = pParse->db;
drh75897232000-05-29 14:26:00 +00002443
danielk197724b03fd2004-05-10 10:34:34 +00002444 if( pParse->nErr || sqlite3_malloc_failed ) return;
drhd24cc422003-03-27 12:51:24 +00002445 assert( pName->nSrc==1 );
danielk19778a414492004-06-29 08:59:35 +00002446 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) return;
danielk19774adee202004-05-08 08:23:19 +00002447 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
drh75897232000-05-29 14:26:00 +00002448 if( pIndex==0 ){
danielk19774adee202004-05-08 08:23:19 +00002449 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
drha6ecd332004-06-10 00:29:09 +00002450 pParse->checkSchema = 1;
drhd24cc422003-03-27 12:51:24 +00002451 goto exit_drop_index;
drh75897232000-05-29 14:26:00 +00002452 }
drh485b39b2002-07-13 03:11:52 +00002453 if( pIndex->autoIndex ){
danielk19774adee202004-05-08 08:23:19 +00002454 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
drh485b39b2002-07-13 03:11:52 +00002455 "or PRIMARY KEY constraint cannot be dropped", 0);
drhd24cc422003-03-27 12:51:24 +00002456 goto exit_drop_index;
2457 }
drhe5f9c642003-01-13 23:27:31 +00002458#ifndef SQLITE_OMIT_AUTHORIZATION
2459 {
2460 int code = SQLITE_DROP_INDEX;
2461 Table *pTab = pIndex->pTable;
drhe22a3342003-04-22 20:30:37 +00002462 const char *zDb = db->aDb[pIndex->iDb].zName;
2463 const char *zTab = SCHEMA_TABLE(pIndex->iDb);
danielk19774adee202004-05-08 08:23:19 +00002464 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002465 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002466 }
drhd24cc422003-03-27 12:51:24 +00002467 if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
danielk19774adee202004-05-08 08:23:19 +00002468 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
drhd24cc422003-03-27 12:51:24 +00002469 goto exit_drop_index;
drhe5f9c642003-01-13 23:27:31 +00002470 }
drhed6c8672003-01-12 18:02:16 +00002471 }
drhe5f9c642003-01-13 23:27:31 +00002472#endif
drh75897232000-05-29 14:26:00 +00002473
2474 /* Generate code to remove the index and from the master table */
danielk19774adee202004-05-08 08:23:19 +00002475 v = sqlite3GetVdbe(pParse);
drh75897232000-05-29 14:26:00 +00002476 if( v ){
drhb17131a2004-11-05 22:18:49 +00002477 int iDb = pIndex->iDb;
2478 sqlite3NestedParse(pParse,
2479 "DELETE FROM %Q.%s WHERE name=%Q",
2480 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
2481 pIndex->zName
2482 );
2483 sqlite3ChangeCookie(db, v, iDb);
2484 destroyRootPage(pParse, pIndex->tnum, iDb);
2485 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
drh75897232000-05-29 14:26:00 +00002486 }
2487
drhd24cc422003-03-27 12:51:24 +00002488exit_drop_index:
danielk19774adee202004-05-08 08:23:19 +00002489 sqlite3SrcListDelete(pName);
drh75897232000-05-29 14:26:00 +00002490}
2491
2492/*
drh75897232000-05-29 14:26:00 +00002493** Append a new element to the given IdList. Create a new IdList if
2494** need be.
drhdaffd0e2001-04-11 14:28:42 +00002495**
2496** A new IdList is returned, or NULL if malloc() fails.
drh75897232000-05-29 14:26:00 +00002497*/
danielk19774adee202004-05-08 08:23:19 +00002498IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
drh75897232000-05-29 14:26:00 +00002499 if( pList==0 ){
2500 pList = sqliteMalloc( sizeof(IdList) );
2501 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002502 pList->nAlloc = 0;
drh75897232000-05-29 14:26:00 +00002503 }
drh4305d102003-07-30 12:34:12 +00002504 if( pList->nId>=pList->nAlloc ){
drh6d4abfb2001-10-22 02:58:08 +00002505 struct IdList_item *a;
drh4305d102003-07-30 12:34:12 +00002506 pList->nAlloc = pList->nAlloc*2 + 5;
2507 a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
drh6d4abfb2001-10-22 02:58:08 +00002508 if( a==0 ){
danielk19774adee202004-05-08 08:23:19 +00002509 sqlite3IdListDelete(pList);
drhdaffd0e2001-04-11 14:28:42 +00002510 return 0;
drh75897232000-05-29 14:26:00 +00002511 }
drh6d4abfb2001-10-22 02:58:08 +00002512 pList->a = a;
drh75897232000-05-29 14:26:00 +00002513 }
2514 memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
drha99db3b2004-06-19 14:49:12 +00002515 pList->a[pList->nId].zName = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002516 pList->nId++;
2517 return pList;
2518}
2519
2520/*
drhad3cab52002-05-24 02:04:32 +00002521** Append a new table name to the given SrcList. Create a new SrcList if
2522** need be. A new entry is created in the SrcList even if pToken is NULL.
2523**
2524** A new SrcList is returned, or NULL if malloc() fails.
drh113088e2003-03-20 01:16:58 +00002525**
2526** If pDatabase is not null, it means that the table has an optional
2527** database name prefix. Like this: "database.table". The pDatabase
2528** points to the table name and the pTable points to the database name.
2529** The SrcList.a[].zName field is filled with the table name which might
2530** come from pTable (if pDatabase is NULL) or from pDatabase.
2531** SrcList.a[].zDatabase is filled with the database name from pTable,
2532** or with NULL if no database is specified.
2533**
2534** In other words, if call like this:
2535**
danielk19774adee202004-05-08 08:23:19 +00002536** sqlite3SrcListAppend(A,B,0);
drh113088e2003-03-20 01:16:58 +00002537**
2538** Then B is a table name and the database name is unspecified. If called
2539** like this:
2540**
danielk19774adee202004-05-08 08:23:19 +00002541** sqlite3SrcListAppend(A,B,C);
drh113088e2003-03-20 01:16:58 +00002542**
2543** Then C is the table name and B is the database name.
drhad3cab52002-05-24 02:04:32 +00002544*/
danielk19774adee202004-05-08 08:23:19 +00002545SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
drha99db3b2004-06-19 14:49:12 +00002546 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002547 if( pList==0 ){
drh113088e2003-03-20 01:16:58 +00002548 pList = sqliteMalloc( sizeof(SrcList) );
drhad3cab52002-05-24 02:04:32 +00002549 if( pList==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00002550 pList->nAlloc = 1;
drhad3cab52002-05-24 02:04:32 +00002551 }
drh4305d102003-07-30 12:34:12 +00002552 if( pList->nSrc>=pList->nAlloc ){
drh113088e2003-03-20 01:16:58 +00002553 SrcList *pNew;
drh4305d102003-07-30 12:34:12 +00002554 pList->nAlloc *= 2;
drh113088e2003-03-20 01:16:58 +00002555 pNew = sqliteRealloc(pList,
drh4305d102003-07-30 12:34:12 +00002556 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
drh113088e2003-03-20 01:16:58 +00002557 if( pNew==0 ){
danielk19774adee202004-05-08 08:23:19 +00002558 sqlite3SrcListDelete(pList);
drhad3cab52002-05-24 02:04:32 +00002559 return 0;
2560 }
drh113088e2003-03-20 01:16:58 +00002561 pList = pNew;
drhad3cab52002-05-24 02:04:32 +00002562 }
drha99db3b2004-06-19 14:49:12 +00002563 pItem = &pList->a[pList->nSrc];
2564 memset(pItem, 0, sizeof(pList->a[0]));
drh113088e2003-03-20 01:16:58 +00002565 if( pDatabase && pDatabase->z==0 ){
2566 pDatabase = 0;
2567 }
2568 if( pDatabase && pTable ){
2569 Token *pTemp = pDatabase;
2570 pDatabase = pTable;
2571 pTable = pTemp;
2572 }
drha99db3b2004-06-19 14:49:12 +00002573 pItem->zName = sqlite3NameFromToken(pTable);
2574 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
2575 pItem->iCursor = -1;
drhad3cab52002-05-24 02:04:32 +00002576 pList->nSrc++;
2577 return pList;
2578}
2579
2580/*
drh63eb5f22003-04-29 16:20:44 +00002581** Assign cursors to all tables in a SrcList
2582*/
danielk19774adee202004-05-08 08:23:19 +00002583void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
drh63eb5f22003-04-29 16:20:44 +00002584 int i;
2585 for(i=0; i<pList->nSrc; i++){
2586 if( pList->a[i].iCursor<0 ){
drh6a3ea0e2003-05-02 14:32:12 +00002587 pList->a[i].iCursor = pParse->nTab++;
drh63eb5f22003-04-29 16:20:44 +00002588 }
2589 }
2590}
2591
2592/*
drh75897232000-05-29 14:26:00 +00002593** Add an alias to the last identifier on the given identifier list.
2594*/
danielk19774adee202004-05-08 08:23:19 +00002595void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
drhad3cab52002-05-24 02:04:32 +00002596 if( pList && pList->nSrc>0 ){
drha99db3b2004-06-19 14:49:12 +00002597 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
drh75897232000-05-29 14:26:00 +00002598 }
2599}
2600
2601/*
drhad3cab52002-05-24 02:04:32 +00002602** Delete an IdList.
drh75897232000-05-29 14:26:00 +00002603*/
danielk19774adee202004-05-08 08:23:19 +00002604void sqlite3IdListDelete(IdList *pList){
drh75897232000-05-29 14:26:00 +00002605 int i;
2606 if( pList==0 ) return;
2607 for(i=0; i<pList->nId; i++){
2608 sqliteFree(pList->a[i].zName);
drhad3cab52002-05-24 02:04:32 +00002609 }
2610 sqliteFree(pList->a);
2611 sqliteFree(pList);
2612}
2613
2614/*
drhad2d8302002-05-24 20:31:36 +00002615** Return the index in pList of the identifier named zId. Return -1
2616** if not found.
2617*/
danielk19774adee202004-05-08 08:23:19 +00002618int sqlite3IdListIndex(IdList *pList, const char *zName){
drhad2d8302002-05-24 20:31:36 +00002619 int i;
2620 if( pList==0 ) return -1;
2621 for(i=0; i<pList->nId; i++){
danielk19774adee202004-05-08 08:23:19 +00002622 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
drhad2d8302002-05-24 20:31:36 +00002623 }
2624 return -1;
2625}
2626
2627/*
drhad3cab52002-05-24 02:04:32 +00002628** Delete an entire SrcList including all its substructure.
2629*/
danielk19774adee202004-05-08 08:23:19 +00002630void sqlite3SrcListDelete(SrcList *pList){
drhad3cab52002-05-24 02:04:32 +00002631 int i;
drhbe5c89a2004-07-26 00:31:09 +00002632 struct SrcList_item *pItem;
drhad3cab52002-05-24 02:04:32 +00002633 if( pList==0 ) return;
drhbe5c89a2004-07-26 00:31:09 +00002634 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
2635 sqliteFree(pItem->zDatabase);
2636 sqliteFree(pItem->zName);
2637 sqliteFree(pItem->zAlias);
2638 if( pItem->pTab && pItem->pTab->isTransient ){
2639 sqlite3DeleteTable(0, pItem->pTab);
drhdaffd0e2001-04-11 14:28:42 +00002640 }
drhbe5c89a2004-07-26 00:31:09 +00002641 sqlite3SelectDelete(pItem->pSelect);
2642 sqlite3ExprDelete(pItem->pOn);
2643 sqlite3IdListDelete(pItem->pUsing);
drh75897232000-05-29 14:26:00 +00002644 }
drh75897232000-05-29 14:26:00 +00002645 sqliteFree(pList);
2646}
2647
drh982cef72000-05-30 16:27:03 +00002648/*
drhc4a3c772001-04-04 11:48:57 +00002649** Begin a transaction
2650*/
drh684917c2004-10-05 02:41:42 +00002651void sqlite3BeginTransaction(Parse *pParse, int type){
drh9bb575f2004-09-06 17:24:11 +00002652 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002653 Vdbe *v;
drh684917c2004-10-05 02:41:42 +00002654 int i;
drh5e00f6c2001-09-13 13:46:56 +00002655
drh001bbcb2003-03-19 03:14:00 +00002656 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002657 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002658 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002659
2660 v = sqlite3GetVdbe(pParse);
2661 if( !v ) return;
drh684917c2004-10-05 02:41:42 +00002662 if( type!=TK_DEFERRED ){
2663 for(i=0; i<db->nDb; i++){
2664 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
2665 }
2666 }
danielk19771d850a72004-05-31 08:26:49 +00002667 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
drhc4a3c772001-04-04 11:48:57 +00002668}
2669
2670/*
2671** Commit a transaction
2672*/
danielk19774adee202004-05-08 08:23:19 +00002673void sqlite3CommitTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002674 sqlite3 *db;
danielk19771d850a72004-05-31 08:26:49 +00002675 Vdbe *v;
drh5e00f6c2001-09-13 13:46:56 +00002676
drh001bbcb2003-03-19 03:14:00 +00002677 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002678 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002679 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002680
2681 v = sqlite3GetVdbe(pParse);
2682 if( v ){
2683 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
drh02f75f12004-02-24 01:04:11 +00002684 }
drhc4a3c772001-04-04 11:48:57 +00002685}
2686
2687/*
2688** Rollback a transaction
2689*/
danielk19774adee202004-05-08 08:23:19 +00002690void sqlite3RollbackTransaction(Parse *pParse){
drh9bb575f2004-09-06 17:24:11 +00002691 sqlite3 *db;
drh5e00f6c2001-09-13 13:46:56 +00002692 Vdbe *v;
2693
drh001bbcb2003-03-19 03:14:00 +00002694 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
danielk197724b03fd2004-05-10 10:34:34 +00002695 if( pParse->nErr || sqlite3_malloc_failed ) return;
danielk19774adee202004-05-08 08:23:19 +00002696 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
danielk19771d850a72004-05-31 08:26:49 +00002697
danielk19774adee202004-05-08 08:23:19 +00002698 v = sqlite3GetVdbe(pParse);
drh5e00f6c2001-09-13 13:46:56 +00002699 if( v ){
danielk19771d850a72004-05-31 08:26:49 +00002700 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
drh02f75f12004-02-24 01:04:11 +00002701 }
drhc4a3c772001-04-04 11:48:57 +00002702}
drhf57b14a2001-09-14 18:54:08 +00002703
2704/*
drhdc3ff9c2004-08-18 02:10:15 +00002705** Make sure the TEMP database is open and available for use. Return
2706** the number of errors. Leave any error messages in the pParse structure.
2707*/
2708static int sqlite3OpenTempDatabase(Parse *pParse){
2709 sqlite3 *db = pParse->db;
2710 if( db->aDb[1].pBt==0 && !pParse->explain ){
2711 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
2712 if( rc!=SQLITE_OK ){
2713 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
2714 "file for storing temporary tables");
2715 pParse->rc = rc;
2716 return 1;
2717 }
2718 if( db->flags & !db->autoCommit ){
2719 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
2720 if( rc!=SQLITE_OK ){
2721 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
2722 "the temporary database file");
2723 pParse->rc = rc;
2724 return 1;
2725 }
2726 }
2727 }
2728 return 0;
2729}
2730
2731/*
drh80242052004-06-09 00:48:12 +00002732** Generate VDBE code that will verify the schema cookie and start
2733** a read-transaction for all named database files.
2734**
2735** It is important that all schema cookies be verified and all
2736** read transactions be started before anything else happens in
2737** the VDBE program. But this routine can be called after much other
2738** code has been generated. So here is what we do:
2739**
drhc275b4e2004-07-19 17:25:24 +00002740** The first time this routine is called, we code an OP_Goto that
drh80242052004-06-09 00:48:12 +00002741** will jump to a subroutine at the end of the program. Then we
2742** record every database that needs its schema verified in the
2743** pParse->cookieMask field. Later, after all other code has been
2744** generated, the subroutine that does the cookie verifications and
drhc275b4e2004-07-19 17:25:24 +00002745** starts the transactions will be coded and the OP_Goto P2 value
drh80242052004-06-09 00:48:12 +00002746** will be made to point to that subroutine. The generation of the
2747** cookie verification subroutine code happens in sqlite3FinishCoding().
drhc275b4e2004-07-19 17:25:24 +00002748**
2749** If iDb<0 then code the OP_Goto only - don't set flag to verify the
2750** schema on any databases. This can be used to position the OP_Goto
2751** early in the code, before we know if any database tables will be used.
drh001bbcb2003-03-19 03:14:00 +00002752*/
danielk19774adee202004-05-08 08:23:19 +00002753void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
drh9bb575f2004-09-06 17:24:11 +00002754 sqlite3 *db;
drh80242052004-06-09 00:48:12 +00002755 Vdbe *v;
2756 int mask;
2757
2758 v = sqlite3GetVdbe(pParse);
2759 if( v==0 ) return; /* This only happens if there was a prior error */
2760 db = pParse->db;
drhc275b4e2004-07-19 17:25:24 +00002761 if( pParse->cookieGoto==0 ){
2762 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
drh80242052004-06-09 00:48:12 +00002763 }
drhc275b4e2004-07-19 17:25:24 +00002764 if( iDb>=0 ){
2765 assert( iDb<db->nDb );
2766 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
2767 assert( iDb<32 );
2768 mask = 1<<iDb;
2769 if( (pParse->cookieMask & mask)==0 ){
2770 pParse->cookieMask |= mask;
2771 pParse->cookieValue[iDb] = db->aDb[iDb].schema_cookie;
drhdc3ff9c2004-08-18 02:10:15 +00002772 if( iDb==1 ){
2773 sqlite3OpenTempDatabase(pParse);
2774 }
drhc275b4e2004-07-19 17:25:24 +00002775 }
drh001bbcb2003-03-19 03:14:00 +00002776 }
drh001bbcb2003-03-19 03:14:00 +00002777}
2778
2779/*
drh1c928532002-01-31 15:54:21 +00002780** Generate VDBE code that prepares for doing an operation that
drhc977f7f2002-05-21 11:38:11 +00002781** might change the database.
2782**
2783** This routine starts a new transaction if we are not already within
2784** a transaction. If we are already within a transaction, then a checkpoint
drh7f0f12e2004-05-21 13:39:50 +00002785** is set if the setStatement parameter is true. A checkpoint should
drhc977f7f2002-05-21 11:38:11 +00002786** be set for operations that might fail (due to a constraint) part of
2787** the way through and which will need to undo some writes without having to
2788** rollback the whole transaction. For operations where all constraints
2789** can be checked before any changes are made to the database, it is never
2790** necessary to undo a write and the checkpoint should not be set.
drhcabb0812002-09-14 13:47:32 +00002791**
drh8bf8dc92003-05-17 17:35:10 +00002792** Only database iDb and the temp database are made writable by this call.
2793** If iDb==0, then the main and temp databases are made writable. If
2794** iDb==1 then only the temp database is made writable. If iDb>1 then the
2795** specified auxiliary database and the temp database are made writable.
drh1c928532002-01-31 15:54:21 +00002796*/
drh7f0f12e2004-05-21 13:39:50 +00002797void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
danielk19771d850a72004-05-31 08:26:49 +00002798 Vdbe *v = sqlite3GetVdbe(pParse);
drh663fc632002-02-02 18:49:19 +00002799 if( v==0 ) return;
drh80242052004-06-09 00:48:12 +00002800 sqlite3CodeVerifySchema(pParse, iDb);
2801 pParse->writeMask |= 1<<iDb;
danielk197763e3e9f2004-11-05 09:19:27 +00002802 if( setStatement && pParse->nested==0 ){
drh7f0f12e2004-05-21 13:39:50 +00002803 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
danielk19771d850a72004-05-31 08:26:49 +00002804 }
drh34f47322004-08-18 15:58:22 +00002805 if( iDb!=1 && pParse->db->aDb[1].pBt!=0 ){
danielk19771d850a72004-05-31 08:26:49 +00002806 sqlite3BeginWriteOperation(pParse, setStatement, 1);
drh663fc632002-02-02 18:49:19 +00002807 }
2808}
2809
danielk1977bfd6cce2004-06-18 04:24:54 +00002810/*
2811** Return the transient sqlite3_value object used for encoding conversions
2812** during SQL compilation.
2813*/
drh9bb575f2004-09-06 17:24:11 +00002814sqlite3_value *sqlite3GetTransientValue(sqlite3 *db){
danielk1977bfd6cce2004-06-18 04:24:54 +00002815 if( !db->pValue ){
2816 db->pValue = sqlite3ValueNew();
2817 }
2818 return db->pValue;
2819}
drh4343fea2004-11-05 23:46:15 +00002820
2821/*
2822** Check to see if pIndex uses the collating sequence pColl. Return
2823** true if it does and false if it does not.
2824*/
2825#ifndef SQLITE_OMIT_REINDEX
2826static int collationMatch(CollSeq *pColl, Index *pIndex){
2827 int n = pIndex->keyInfo.nField;
2828 CollSeq **pp = pIndex->keyInfo.aColl;
2829 while( n-- ){
2830 if( *pp==pColl ) return 1;
2831 pp++;
2832 }
2833 return 0;
2834}
2835#endif
2836
2837/*
2838** Recompute all indices of pTab that use the collating sequence pColl.
2839** If pColl==0 then recompute all indices of pTab.
2840*/
2841#ifndef SQLITE_OMIT_REINDEX
2842void reindexTable(Parse *pParse, Table *pTab, CollSeq *pColl){
2843 Index *pIndex; /* An index associated with pTab */
2844
2845 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
2846 if( pColl==0 || collationMatch(pColl,pIndex) ){
2847 sqlite3BeginWriteOperation(pParse, 0, pTab->iDb);
2848 sqlite3RefillIndex(pParse, pIndex, -1);
2849 }
2850 }
2851}
2852#endif
2853
2854/*
2855** Recompute all indices of all tables in all databases where the
2856** indices use the collating sequence pColl. If pColl==0 then recompute
2857** all indices everywhere.
2858*/
2859#ifndef SQLITE_OMIT_REINDEX
2860void reindexDatabases(Parse *pParse, CollSeq *pColl){
2861 Db *pDb; /* A single database */
2862 int iDb; /* The database index number */
2863 sqlite3 *db = pParse->db; /* The database connection */
2864 HashElem *k; /* For looping over tables in pDb */
2865 Table *pTab; /* A table in the database */
2866
2867 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
2868 if( pDb==0 ) continue;
2869 for(k=sqliteHashFirst(&pDb->tblHash); k; k=sqliteHashNext(k)){
2870 pTab = (Table*)sqliteHashData(k);
2871 reindexTable(pParse, pTab, pColl);
2872 }
2873 }
2874}
2875#endif
2876
2877/*
drheee46cf2004-11-06 00:02:48 +00002878** Generate code for the REINDEX command.
2879**
2880** REINDEX -- 1
2881** REINDEX <collation> -- 2
2882** REINDEX ?<database>.?<tablename> -- 3
2883** REINDEX ?<database>.?<indexname> -- 4
2884**
2885** Form 1 causes all indices in all attached databases to be rebuilt.
2886** Form 2 rebuilds all indices in all databases that use the named
2887** collating function. Forms 3 and 4 rebuild the named index or all
2888** indices associated with the named table.
drh4343fea2004-11-05 23:46:15 +00002889*/
2890#ifndef SQLITE_OMIT_REINDEX
2891void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
2892 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
2893 char *z; /* Name of a table or index */
2894 const char *zDb; /* Name of the database */
2895 Table *pTab; /* A table in the database */
2896 Index *pIndex; /* An index associated with pTab */
2897 int iDb; /* The database index number */
2898 sqlite3 *db = pParse->db; /* The database connection */
2899 Token *pObjName; /* Name of the table or index to be reindexed */
2900
drhe497f002004-11-07 13:01:49 +00002901 if( pName1==0 || pName1->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002902 reindexDatabases(pParse, 0);
2903 return;
drhe497f002004-11-07 13:01:49 +00002904 }else if( pName2==0 || pName2->z==0 ){
drh4343fea2004-11-05 23:46:15 +00002905 pColl = sqlite3FindCollSeq(db, db->enc, pName1->z, pName1->n, 0);
2906 if( pColl ){
2907 reindexDatabases(pParse, pColl);
2908 return;
2909 }
2910 }
2911 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
2912 if( iDb<0 ) return;
2913 z = sqlite3NameFromToken(pObjName);
2914 zDb = db->aDb[iDb].zName;
2915 pTab = sqlite3FindTable(db, z, zDb);
2916 if( pTab ){
2917 reindexTable(pParse, pTab, 0);
2918 sqliteFree(z);
2919 return;
2920 }
2921 pIndex = sqlite3FindIndex(db, z, zDb);
2922 sqliteFree(z);
2923 if( pIndex ){
2924 sqlite3BeginWriteOperation(pParse, 0, iDb);
2925 sqlite3RefillIndex(pParse, pIndex, -1);
2926 return;
2927 }
2928 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
2929}
2930#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00002931
2932#ifndef SQLITE_OMIT_ALTERTABLE
2933/*
2934** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
2935** command.
2936*/
2937void sqlite3AlterRenameTable(
2938 Parse *pParse, /* Parser context. */
2939 SrcList *pSrc, /* The table to rename. */
2940 Token *pName /* The new table name. */
2941){
2942 int iDb; /* Database that contains the table */
danielk19771c8c23c2004-11-12 15:53:37 +00002943 char *zDb; /* Name of database iDb */
danielk19779fd2a9a2004-11-12 13:42:30 +00002944 Table *pTab; /* Table being renamed */
danielk19779fd2a9a2004-11-12 13:42:30 +00002945 char *zName = 0; /* NULL-terminated version of pName */
2946 char *zWhere = 0; /* Where clause of schema elements to reparse */
danielk19771c8c23c2004-11-12 15:53:37 +00002947 sqlite3 *db = pParse->db; /* Database connection */
danielk19779fd2a9a2004-11-12 13:42:30 +00002948 Vdbe *v;
danielk1977343e9262004-11-19 05:14:54 +00002949#ifndef SQLITE_OMIT_TRIGGER
2950 char *zTempTrig = 0; /* Where clause to locate temp triggers */
2951#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00002952
2953 assert( pSrc->nSrc==1 );
2954
2955 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
danielk19778b840012004-11-23 16:31:16 +00002956 if( !pTab ) goto exit_alter_table;
danielk19779fd2a9a2004-11-12 13:42:30 +00002957 iDb = pTab->iDb;
danielk19771c8c23c2004-11-12 15:53:37 +00002958 zDb = db->aDb[iDb].zName;
danielk19779fd2a9a2004-11-12 13:42:30 +00002959
2960 /* Get a NULL terminated version of the new table name. */
2961 zName = sqlite3NameFromToken(pName);
danielk19778b840012004-11-23 16:31:16 +00002962 if( !zName ) goto exit_alter_table;
danielk19779fd2a9a2004-11-12 13:42:30 +00002963
2964 /* Check that a table or index named 'zName' does not already exist
2965 ** in database iDb. If so, this is an error.
2966 */
danielk19771c8c23c2004-11-12 15:53:37 +00002967 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
danielk19779fd2a9a2004-11-12 13:42:30 +00002968 sqlite3ErrorMsg(pParse,
2969 "there is already another table or index with this name: %s", zName);
danielk19778b840012004-11-23 16:31:16 +00002970 goto exit_alter_table;
danielk19779fd2a9a2004-11-12 13:42:30 +00002971 }
2972
danielk1977023f4172004-11-19 08:41:34 +00002973 /* Make sure it is not a system table being altered, or a reserved name
2974 ** that the table is being renamed to.
2975 */
2976 if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
2977 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danielk19778b840012004-11-23 16:31:16 +00002978 goto exit_alter_table;
danielk1977023f4172004-11-19 08:41:34 +00002979 }
2980 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
danielk19778b840012004-11-23 16:31:16 +00002981 goto exit_alter_table;
danielk1977023f4172004-11-19 08:41:34 +00002982 }
2983
danielk19771c8c23c2004-11-12 15:53:37 +00002984#ifndef SQLITE_OMIT_AUTHORIZATION
2985 /* Invoke the authorization callback. */
2986 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
danielk19778b840012004-11-23 16:31:16 +00002987 goto exit_alter_table;
danielk19771c8c23c2004-11-12 15:53:37 +00002988 }
2989#endif
2990
danielk19779fd2a9a2004-11-12 13:42:30 +00002991 /* Begin a transaction and code the VerifyCookie for database iDb.
2992 ** Then modify the schema cookie (since the ALTER TABLE modifies the
2993 ** schema).
2994 */
2995 v = sqlite3GetVdbe(pParse);
danielk19771c8c23c2004-11-12 15:53:37 +00002996 if( v==0 ){
danielk19778b840012004-11-23 16:31:16 +00002997 goto exit_alter_table;
danielk19771c8c23c2004-11-12 15:53:37 +00002998 }
danielk19779fd2a9a2004-11-12 13:42:30 +00002999 sqlite3BeginWriteOperation(pParse, 0, iDb);
3000 sqlite3ChangeCookie(db, v, iDb);
3001
3002 /* Modify the sqlite_master table to use the new table name. */
3003 sqlite3NestedParse(pParse,
3004 "UPDATE %Q.%s SET "
danielk1977d641d642004-11-18 15:44:29 +00003005#ifdef SQLITE_OMIT_TRIGGER
danielk19779fd2a9a2004-11-12 13:42:30 +00003006 "sql = sqlite_alter_table(sql, %Q), "
danielk1977d641d642004-11-18 15:44:29 +00003007#else
3008 "sql = CASE "
3009 "WHEN type = 'trigger' THEN sqlite_alter_trigger(sql, %Q)"
3010 "ELSE sqlite_alter_table(sql, %Q) END, "
3011#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00003012 "tbl_name = %Q, "
3013 "name = CASE "
3014 "WHEN type='table' THEN %Q "
3015 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
3016 "'sqlite_autoindex_' || %Q || substr(name, %d+18,10) "
3017 "ELSE name END "
danielk1977d641d642004-11-18 15:44:29 +00003018 "WHERE tbl_name=%Q AND type IN ('table', 'index', 'trigger');",
danielk197781650dc2004-11-22 11:51:13 +00003019 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
3020#ifndef SQLITE_OMIT_TRIGGER
3021zName,
3022#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00003023 zName, strlen(pTab->zName), pTab->zName
3024 );
3025
danielk1977aacd7322004-11-19 08:02:14 +00003026#ifndef SQLITE_OMIT_AUTOINCREMENT
3027 /* If the sqlite_sequence table exists in this database, then update
3028 ** it with the new table name.
3029 */
3030 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
3031 sqlite3NestedParse(pParse,
3032 "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
3033 zDb, zName, pTab->zName);
3034 }
3035#endif
3036
danielk1977343e9262004-11-19 05:14:54 +00003037#ifndef SQLITE_OMIT_TRIGGER
3038 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
3039 ** table. Don't do this if the table being ALTERed is itself located in
3040 ** the temp database.
3041 */
3042 if( iDb!=1 ){
3043 Trigger *pTrig;
3044 char *tmp = 0;
3045 for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
3046 if( pTrig->iDb==1 ){
3047 if( !zTempTrig ){
3048 zTempTrig =
3049 sqlite3MPrintf("type = 'trigger' AND name IN(%Q", pTrig->name);
3050 }else{
3051 tmp = zTempTrig;
3052 zTempTrig = sqlite3MPrintf("%s, %Q", zTempTrig, pTrig->name);
3053 sqliteFree(tmp);
3054 }
3055 }
3056 }
3057 if( zTempTrig ){
3058 tmp = zTempTrig;
3059 zTempTrig = sqlite3MPrintf("%s)", zTempTrig);
3060 sqliteFree(tmp);
3061 sqlite3NestedParse(pParse,
3062 "UPDATE sqlite_temp_master SET "
3063 "sql = sqlite_alter_trigger(sql, %Q), "
3064 "tbl_name = %Q "
3065 "WHERE %s;", zName, zName, zTempTrig);
3066 }
3067 }
3068#endif
3069
danielk19779fd2a9a2004-11-12 13:42:30 +00003070 /* Drop the elements of the in-memory schema that refered to the table
3071 ** renamed and load the new versions from the database.
3072 */
3073 if( pParse->nErr==0 ){
danielk1977d641d642004-11-18 15:44:29 +00003074#ifndef SQLITE_OMIT_TRIGGER
3075 Trigger *pTrig;
3076 for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
danielk1977343e9262004-11-19 05:14:54 +00003077 assert( pTrig->iDb==iDb || pTrig->iDb==1 );
3078 sqlite3VdbeOp3(v, OP_DropTrigger, pTrig->iDb, 0, pTrig->name, 0);
danielk1977d641d642004-11-18 15:44:29 +00003079 }
3080#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00003081 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
3082 zWhere = sqlite3MPrintf("tbl_name=%Q", zName);
3083 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
danielk1977343e9262004-11-19 05:14:54 +00003084#ifndef SQLITE_OMIT_TRIGGER
3085 if( zTempTrig ){
3086 sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zTempTrig, P3_DYNAMIC);
3087 }
3088 }else{
3089 sqliteFree(zTempTrig);
3090#endif
danielk19779fd2a9a2004-11-12 13:42:30 +00003091 }
3092
danielk19778b840012004-11-23 16:31:16 +00003093exit_alter_table:
3094 sqlite3SrcListDelete(pSrc);
danielk19779fd2a9a2004-11-12 13:42:30 +00003095 sqliteFree(zName);
3096}
3097#endif