1434
|
1 /*
|
|
2 ** 2001 September 15
|
|
3 **
|
|
4 ** The author disclaims copyright to this source code. In place of
|
|
5 ** a legal notice, here is a blessing:
|
|
6 **
|
|
7 ** 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.
|
|
10 **
|
|
11 *************************************************************************
|
|
12 ** 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:
|
|
15 **
|
|
16 ** CREATE TABLE
|
|
17 ** DROP TABLE
|
|
18 ** CREATE INDEX
|
|
19 ** DROP INDEX
|
|
20 ** creating ID lists
|
|
21 ** BEGIN TRANSACTION
|
|
22 ** COMMIT
|
|
23 ** ROLLBACK
|
|
24 **
|
|
25 ** $Id: build.c,v 1.394 2006/05/11 23:14:59 drh Exp $
|
|
26 */
|
|
27 #include "sqliteInt.h"
|
|
28 #include <ctype.h>
|
|
29
|
|
30 /*
|
|
31 ** This routine is called when a new SQL statement is beginning to
|
|
32 ** be parsed. Initialize the pParse structure as needed.
|
|
33 */
|
|
34 void sqlite3BeginParse(Parse *pParse, int explainFlag){
|
|
35 pParse->explain = explainFlag;
|
|
36 pParse->nVar = 0;
|
|
37 }
|
|
38
|
|
39 #ifndef SQLITE_OMIT_SHARED_CACHE
|
|
40 /*
|
|
41 ** The TableLock structure is only used by the sqlite3TableLock() and
|
|
42 ** codeTableLocks() functions.
|
|
43 */
|
|
44 struct TableLock {
|
|
45 int iDb; /* The database containing the table to be locked */
|
|
46 int iTab; /* The root page of the table to be locked */
|
|
47 u8 isWriteLock; /* True for write lock. False for a read lock */
|
|
48 const char *zName; /* Name of the table */
|
|
49 };
|
|
50
|
|
51 /*
|
|
52 ** Record the fact that we want to lock a table at run-time.
|
|
53 **
|
|
54 ** The table to be locked has root page iTab and is found in database iDb.
|
|
55 ** A read or a write lock can be taken depending on isWritelock.
|
|
56 **
|
|
57 ** This routine just records the fact that the lock is desired. The
|
|
58 ** code to make the lock occur is generated by a later call to
|
|
59 ** codeTableLocks() which occurs during sqlite3FinishCoding().
|
|
60 */
|
|
61 void sqlite3TableLock(
|
|
62 Parse *pParse, /* Parsing context */
|
|
63 int iDb, /* Index of the database containing the table to lock */
|
|
64 int iTab, /* Root page number of the table to be locked */
|
|
65 u8 isWriteLock, /* True for a write lock */
|
|
66 const char *zName /* Name of the table to be locked */
|
|
67 ){
|
|
68 int i;
|
|
69 int nBytes;
|
|
70 TableLock *p;
|
|
71
|
|
72 if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){
|
|
73 return;
|
|
74 }
|
|
75
|
|
76 for(i=0; i<pParse->nTableLock; i++){
|
|
77 p = &pParse->aTableLock[i];
|
|
78 if( p->iDb==iDb && p->iTab==iTab ){
|
|
79 p->isWriteLock = (p->isWriteLock || isWriteLock);
|
|
80 return;
|
|
81 }
|
|
82 }
|
|
83
|
|
84 nBytes = sizeof(TableLock) * (pParse->nTableLock+1);
|
|
85 sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes);
|
|
86 if( pParse->aTableLock ){
|
|
87 p = &pParse->aTableLock[pParse->nTableLock++];
|
|
88 p->iDb = iDb;
|
|
89 p->iTab = iTab;
|
|
90 p->isWriteLock = isWriteLock;
|
|
91 p->zName = zName;
|
|
92 }
|
|
93 }
|
|
94
|
|
95 /*
|
|
96 ** Code an OP_TableLock instruction for each table locked by the
|
|
97 ** statement (configured by calls to sqlite3TableLock()).
|
|
98 */
|
|
99 static void codeTableLocks(Parse *pParse){
|
|
100 int i;
|
|
101 Vdbe *pVdbe;
|
|
102 assert( sqlite3ThreadDataReadOnly()->useSharedData || pParse->nTableLock==0 );
|
|
103
|
|
104 if( 0==(pVdbe = sqlite3GetVdbe(pParse)) ){
|
|
105 return;
|
|
106 }
|
|
107
|
|
108 for(i=0; i<pParse->nTableLock; i++){
|
|
109 TableLock *p = &pParse->aTableLock[i];
|
|
110 int p1 = p->iDb;
|
|
111 if( p->isWriteLock ){
|
|
112 p1 = -1*(p1+1);
|
|
113 }
|
|
114 sqlite3VdbeOp3(pVdbe, OP_TableLock, p1, p->iTab, p->zName, P3_STATIC);
|
|
115 }
|
|
116 }
|
|
117 #else
|
|
118 #define codeTableLocks(x)
|
|
119 #endif
|
|
120
|
|
121 /*
|
|
122 ** This routine is called after a single SQL statement has been
|
|
123 ** parsed and a VDBE program to execute that statement has been
|
|
124 ** prepared. This routine puts the finishing touches on the
|
|
125 ** VDBE program and resets the pParse structure for the next
|
|
126 ** parse.
|
|
127 **
|
|
128 ** Note that if an error occurred, it might be the case that
|
|
129 ** no VDBE code was generated.
|
|
130 */
|
|
131 void sqlite3FinishCoding(Parse *pParse){
|
|
132 sqlite3 *db;
|
|
133 Vdbe *v;
|
|
134
|
|
135 if( sqlite3MallocFailed() ) return;
|
|
136 if( pParse->nested ) return;
|
|
137 if( !pParse->pVdbe ){
|
|
138 if( pParse->rc==SQLITE_OK && pParse->nErr ){
|
|
139 pParse->rc = SQLITE_ERROR;
|
|
140 return;
|
|
141 }
|
|
142 }
|
|
143
|
|
144 /* Begin by generating some termination code at the end of the
|
|
145 ** vdbe program
|
|
146 */
|
|
147 db = pParse->db;
|
|
148 v = sqlite3GetVdbe(pParse);
|
|
149 if( v ){
|
|
150 sqlite3VdbeAddOp(v, OP_Halt, 0, 0);
|
|
151
|
|
152 /* The cookie mask contains one bit for each database file open.
|
|
153 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
|
|
154 ** set for each database that is used. Generate code to start a
|
|
155 ** transaction on each used database and to verify the schema cookie
|
|
156 ** on each used database.
|
|
157 */
|
|
158 if( pParse->cookieGoto>0 ){
|
|
159 u32 mask;
|
|
160 int iDb;
|
|
161 sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
|
|
162 for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
|
|
163 if( (mask & pParse->cookieMask)==0 ) continue;
|
|
164 sqlite3VdbeAddOp(v, OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
|
|
165 sqlite3VdbeAddOp(v, OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
|
|
166 }
|
|
167
|
|
168 /* Once all the cookies have been verified and transactions opened,
|
|
169 ** obtain the required table-locks. This is a no-op unless the
|
|
170 ** shared-cache feature is enabled.
|
|
171 */
|
|
172 codeTableLocks(pParse);
|
|
173 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->cookieGoto);
|
|
174 }
|
|
175
|
|
176 #ifndef SQLITE_OMIT_TRACE
|
|
177 /* Add a No-op that contains the complete text of the compiled SQL
|
|
178 ** statement as its P3 argument. This does not change the functionality
|
|
179 ** of the program.
|
|
180 **
|
|
181 ** This is used to implement sqlite3_trace().
|
|
182 */
|
|
183 sqlite3VdbeOp3(v, OP_Noop, 0, 0, pParse->zSql, pParse->zTail-pParse->zSql);
|
|
184 #endif /* SQLITE_OMIT_TRACE */
|
|
185 }
|
|
186
|
|
187
|
|
188 /* Get the VDBE program ready for execution
|
|
189 */
|
|
190 if( v && pParse->nErr==0 && !sqlite3MallocFailed() ){
|
|
191 FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
|
|
192 sqlite3VdbeTrace(v, trace);
|
|
193 sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem+3,
|
|
194 pParse->nTab+3, pParse->explain);
|
|
195 pParse->rc = SQLITE_DONE;
|
|
196 pParse->colNamesSet = 0;
|
|
197 }else if( pParse->rc==SQLITE_OK ){
|
|
198 pParse->rc = SQLITE_ERROR;
|
|
199 }
|
|
200 pParse->nTab = 0;
|
|
201 pParse->nMem = 0;
|
|
202 pParse->nSet = 0;
|
|
203 pParse->nVar = 0;
|
|
204 pParse->cookieMask = 0;
|
|
205 pParse->cookieGoto = 0;
|
|
206 }
|
|
207
|
|
208 /*
|
|
209 ** Run the parser and code generator recursively in order to generate
|
|
210 ** code for the SQL statement given onto the end of the pParse context
|
|
211 ** currently under construction. When the parser is run recursively
|
|
212 ** this way, the final OP_Halt is not appended and other initialization
|
|
213 ** and finalization steps are omitted because those are handling by the
|
|
214 ** outermost parser.
|
|
215 **
|
|
216 ** Not everything is nestable. This facility is designed to permit
|
|
217 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
|
|
218 ** care if you decide to try to use this routine for some other purposes.
|
|
219 */
|
|
220 void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
|
|
221 va_list ap;
|
|
222 char *zSql;
|
|
223 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
|
|
224 char saveBuf[SAVE_SZ];
|
|
225
|
|
226 if( pParse->nErr ) return;
|
|
227 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
|
|
228 va_start(ap, zFormat);
|
|
229 zSql = sqlite3VMPrintf(zFormat, ap);
|
|
230 va_end(ap);
|
|
231 if( zSql==0 ){
|
|
232 return; /* A malloc must have failed */
|
|
233 }
|
|
234 pParse->nested++;
|
|
235 memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
|
|
236 memset(&pParse->nVar, 0, SAVE_SZ);
|
|
237 sqlite3RunParser(pParse, zSql, 0);
|
|
238 sqliteFree(zSql);
|
|
239 memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
|
|
240 pParse->nested--;
|
|
241 }
|
|
242
|
|
243 /*
|
|
244 ** Locate the in-memory structure that describes a particular database
|
|
245 ** table given the name of that table and (optionally) the name of the
|
|
246 ** database containing the table. Return NULL if not found.
|
|
247 **
|
|
248 ** If zDatabase is 0, all databases are searched for the table and the
|
|
249 ** first matching table is returned. (No checking for duplicate table
|
|
250 ** names is done.) The search order is TEMP first, then MAIN, then any
|
|
251 ** auxiliary databases added using the ATTACH command.
|
|
252 **
|
|
253 ** See also sqlite3LocateTable().
|
|
254 */
|
|
255 Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
|
|
256 Table *p = 0;
|
|
257 int i;
|
|
258 assert( zName!=0 );
|
|
259 for(i=OMIT_TEMPDB; i<db->nDb; i++){
|
|
260 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
|
|
261 if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
|
|
262 p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
|
|
263 if( p ) break;
|
|
264 }
|
|
265 return p;
|
|
266 }
|
|
267
|
|
268 /*
|
|
269 ** Locate the in-memory structure that describes a particular database
|
|
270 ** table given the name of that table and (optionally) the name of the
|
|
271 ** database containing the table. Return NULL if not found. Also leave an
|
|
272 ** error message in pParse->zErrMsg.
|
|
273 **
|
|
274 ** The difference between this routine and sqlite3FindTable() is that this
|
|
275 ** routine leaves an error message in pParse->zErrMsg where
|
|
276 ** sqlite3FindTable() does not.
|
|
277 */
|
|
278 Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
|
|
279 Table *p;
|
|
280
|
|
281 /* Read the database schema. If an error occurs, leave an error message
|
|
282 ** and code in pParse and return NULL. */
|
|
283 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
|
|
284 return 0;
|
|
285 }
|
|
286
|
|
287 p = sqlite3FindTable(pParse->db, zName, zDbase);
|
|
288 if( p==0 ){
|
|
289 if( zDbase ){
|
|
290 sqlite3ErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
|
|
291 }else{
|
|
292 sqlite3ErrorMsg(pParse, "no such table: %s", zName);
|
|
293 }
|
|
294 pParse->checkSchema = 1;
|
|
295 }
|
|
296 return p;
|
|
297 }
|
|
298
|
|
299 /*
|
|
300 ** Locate the in-memory structure that describes
|
|
301 ** a particular index given the name of that index
|
|
302 ** and the name of the database that contains the index.
|
|
303 ** Return NULL if not found.
|
|
304 **
|
|
305 ** If zDatabase is 0, all databases are searched for the
|
|
306 ** table and the first matching index is returned. (No checking
|
|
307 ** for duplicate index names is done.) The search order is
|
|
308 ** TEMP first, then MAIN, then any auxiliary databases added
|
|
309 ** using the ATTACH command.
|
|
310 */
|
|
311 Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
|
|
312 Index *p = 0;
|
|
313 int i;
|
|
314 for(i=OMIT_TEMPDB; i<db->nDb; i++){
|
|
315 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
|
|
316 Schema *pSchema = db->aDb[j].pSchema;
|
|
317 if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
|
|
318 assert( pSchema || (j==1 && !db->aDb[1].pBt) );
|
|
319 if( pSchema ){
|
|
320 p = sqlite3HashFind(&pSchema->idxHash, zName, strlen(zName)+1);
|
|
321 }
|
|
322 if( p ) break;
|
|
323 }
|
|
324 return p;
|
|
325 }
|
|
326
|
|
327 /*
|
|
328 ** Reclaim the memory used by an index
|
|
329 */
|
|
330 static void freeIndex(Index *p){
|
|
331 sqliteFree(p->zColAff);
|
|
332 sqliteFree(p);
|
|
333 }
|
|
334
|
|
335 /*
|
|
336 ** Remove the given index from the index hash table, and free
|
|
337 ** its memory structures.
|
|
338 **
|
|
339 ** The index is removed from the database hash tables but
|
|
340 ** it is not unlinked from the Table that it indexes.
|
|
341 ** Unlinking from the Table must be done by the calling function.
|
|
342 */
|
|
343 static void sqliteDeleteIndex(Index *p){
|
|
344 Index *pOld;
|
|
345 const char *zName = p->zName;
|
|
346
|
|
347 pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName, strlen( zName)+1, 0);
|
|
348 assert( pOld==0 || pOld==p );
|
|
349 freeIndex(p);
|
|
350 }
|
|
351
|
|
352 /*
|
|
353 ** For the index called zIdxName which is found in the database iDb,
|
|
354 ** unlike that index from its Table then remove the index from
|
|
355 ** the index hash table and free all memory structures associated
|
|
356 ** with the index.
|
|
357 */
|
|
358 void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
|
|
359 Index *pIndex;
|
|
360 int len;
|
|
361 Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
|
|
362
|
|
363 len = strlen(zIdxName);
|
|
364 pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
|
|
365 if( pIndex ){
|
|
366 if( pIndex->pTable->pIndex==pIndex ){
|
|
367 pIndex->pTable->pIndex = pIndex->pNext;
|
|
368 }else{
|
|
369 Index *p;
|
|
370 for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
|
|
371 if( p && p->pNext==pIndex ){
|
|
372 p->pNext = pIndex->pNext;
|
|
373 }
|
|
374 }
|
|
375 freeIndex(pIndex);
|
|
376 }
|
|
377 db->flags |= SQLITE_InternChanges;
|
|
378 }
|
|
379
|
|
380 /*
|
|
381 ** Erase all schema information from the in-memory hash tables of
|
|
382 ** a single database. This routine is called to reclaim memory
|
|
383 ** before the database closes. It is also called during a rollback
|
|
384 ** if there were schema changes during the transaction or if a
|
|
385 ** schema-cookie mismatch occurs.
|
|
386 **
|
|
387 ** If iDb<=0 then reset the internal schema tables for all database
|
|
388 ** files. If iDb>=2 then reset the internal schema for only the
|
|
389 ** single file indicated.
|
|
390 */
|
|
391 void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
|
|
392 int i, j;
|
|
393
|
|
394 assert( iDb>=0 && iDb<db->nDb );
|
|
395 for(i=iDb; i<db->nDb; i++){
|
|
396 Db *pDb = &db->aDb[i];
|
|
397 if( pDb->pSchema ){
|
|
398 sqlite3SchemaFree(pDb->pSchema);
|
|
399 }
|
|
400 if( iDb>0 ) return;
|
|
401 }
|
|
402 assert( iDb==0 );
|
|
403 db->flags &= ~SQLITE_InternChanges;
|
|
404
|
|
405 /* If one or more of the auxiliary database files has been closed,
|
|
406 ** then remove them from the auxiliary database list. We take the
|
|
407 ** opportunity to do this here since we have just deleted all of the
|
|
408 ** schema hash tables and therefore do not have to make any changes
|
|
409 ** to any of those tables.
|
|
410 */
|
|
411 for(i=0; i<db->nDb; i++){
|
|
412 struct Db *pDb = &db->aDb[i];
|
|
413 if( pDb->pBt==0 ){
|
|
414 if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
|
|
415 pDb->pAux = 0;
|
|
416 }
|
|
417 }
|
|
418 for(i=j=2; i<db->nDb; i++){
|
|
419 struct Db *pDb = &db->aDb[i];
|
|
420 if( pDb->pBt==0 ){
|
|
421 sqliteFree(pDb->zName);
|
|
422 pDb->zName = 0;
|
|
423 continue;
|
|
424 }
|
|
425 if( j<i ){
|
|
426 db->aDb[j] = db->aDb[i];
|
|
427 }
|
|
428 j++;
|
|
429 }
|
|
430 memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
|
|
431 db->nDb = j;
|
|
432 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
|
|
433 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
|
|
434 sqliteFree(db->aDb);
|
|
435 db->aDb = db->aDbStatic;
|
|
436 }
|
|
437 }
|
|
438
|
|
439 /*
|
|
440 ** This routine is called whenever a rollback occurs. If there were
|
|
441 ** schema changes during the transaction, then we have to reset the
|
|
442 ** internal hash tables and reload them from disk.
|
|
443 */
|
|
444 void sqlite3RollbackInternalChanges(sqlite3 *db){
|
|
445 if( db->flags & SQLITE_InternChanges ){
|
|
446 sqlite3ResetInternalSchema(db, 0);
|
|
447 }
|
|
448 }
|
|
449
|
|
450 /*
|
|
451 ** This routine is called when a commit occurs.
|
|
452 */
|
|
453 void sqlite3CommitInternalChanges(sqlite3 *db){
|
|
454 db->flags &= ~SQLITE_InternChanges;
|
|
455 }
|
|
456
|
|
457 /*
|
|
458 ** Clear the column names from a table or view.
|
|
459 */
|
|
460 static void sqliteResetColumnNames(Table *pTable){
|
|
461 int i;
|
|
462 Column *pCol;
|
|
463 assert( pTable!=0 );
|
|
464 if( (pCol = pTable->aCol)!=0 ){
|
|
465 for(i=0; i<pTable->nCol; i++, pCol++){
|
|
466 sqliteFree(pCol->zName);
|
|
467 sqlite3ExprDelete(pCol->pDflt);
|
|
468 sqliteFree(pCol->zType);
|
|
469 sqliteFree(pCol->zColl);
|
|
470 }
|
|
471 sqliteFree(pTable->aCol);
|
|
472 }
|
|
473 pTable->aCol = 0;
|
|
474 pTable->nCol = 0;
|
|
475 }
|
|
476
|
|
477 /*
|
|
478 ** Remove the memory data structures associated with the given
|
|
479 ** Table. No changes are made to disk by this routine.
|
|
480 **
|
|
481 ** This routine just deletes the data structure. It does not unlink
|
|
482 ** the table data structure from the hash table. Nor does it remove
|
|
483 ** foreign keys from the sqlite.aFKey hash table. But it does destroy
|
|
484 ** memory structures of the indices and foreign keys associated with
|
|
485 ** the table.
|
|
486 **
|
|
487 ** Indices associated with the table are unlinked from the "db"
|
|
488 ** data structure if db!=NULL. If db==NULL, indices attached to
|
|
489 ** the table are deleted, but it is assumed they have already been
|
|
490 ** unlinked.
|
|
491 */
|
|
492 void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
|
|
493 Index *pIndex, *pNext;
|
|
494 FKey *pFKey, *pNextFKey;
|
|
495
|
|
496 db = 0;
|
|
497
|
|
498 if( pTable==0 ) return;
|
|
499
|
|
500 /* Do not delete the table until the reference count reaches zero. */
|
|
501 pTable->nRef--;
|
|
502 if( pTable->nRef>0 ){
|
|
503 return;
|
|
504 }
|
|
505 assert( pTable->nRef==0 );
|
|
506
|
|
507 /* Delete all indices associated with this table
|
|
508 */
|
|
509 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
|
|
510 pNext = pIndex->pNext;
|
|
511 assert( pIndex->pSchema==pTable->pSchema );
|
|
512 sqliteDeleteIndex(pIndex);
|
|
513 }
|
|
514
|
|
515 #ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
516 /* Delete all foreign keys associated with this table. The keys
|
|
517 ** should have already been unlinked from the db->aFKey hash table
|
|
518 */
|
|
519 for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
|
|
520 pNextFKey = pFKey->pNextFrom;
|
|
521 assert( sqlite3HashFind(&pTable->pSchema->aFKey,
|
|
522 pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
|
|
523 sqliteFree(pFKey);
|
|
524 }
|
|
525 #endif
|
|
526
|
|
527 /* Delete the Table structure itself.
|
|
528 */
|
|
529 sqliteResetColumnNames(pTable);
|
|
530 sqliteFree(pTable->zName);
|
|
531 sqliteFree(pTable->zColAff);
|
|
532 sqlite3SelectDelete(pTable->pSelect);
|
|
533 #ifndef SQLITE_OMIT_CHECK
|
|
534 sqlite3ExprDelete(pTable->pCheck);
|
|
535 #endif
|
|
536 sqliteFree(pTable);
|
|
537 }
|
|
538
|
|
539 /*
|
|
540 ** Unlink the given table from the hash tables and the delete the
|
|
541 ** table structure with all its indices and foreign keys.
|
|
542 */
|
|
543 void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
|
|
544 Table *p;
|
|
545 FKey *pF1, *pF2;
|
|
546 Db *pDb;
|
|
547
|
|
548 assert( db!=0 );
|
|
549 assert( iDb>=0 && iDb<db->nDb );
|
|
550 assert( zTabName && zTabName[0] );
|
|
551 pDb = &db->aDb[iDb];
|
|
552 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, strlen(zTabName)+1,0);
|
|
553 if( p ){
|
|
554 #ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
555 for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
|
|
556 int nTo = strlen(pF1->zTo) + 1;
|
|
557 pF2 = sqlite3HashFind(&pDb->pSchema->aFKey, pF1->zTo, nTo);
|
|
558 if( pF2==pF1 ){
|
|
559 sqlite3HashInsert(&pDb->pSchema->aFKey, pF1->zTo, nTo, pF1->pNextTo);
|
|
560 }else{
|
|
561 while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
|
|
562 if( pF2 ){
|
|
563 pF2->pNextTo = pF1->pNextTo;
|
|
564 }
|
|
565 }
|
|
566 }
|
|
567 #endif
|
|
568 sqlite3DeleteTable(db, p);
|
|
569 }
|
|
570 db->flags |= SQLITE_InternChanges;
|
|
571 }
|
|
572
|
|
573 /*
|
|
574 ** Given a token, return a string that consists of the text of that
|
|
575 ** token with any quotations removed. Space to hold the returned string
|
|
576 ** is obtained from sqliteMalloc() and must be freed by the calling
|
|
577 ** function.
|
|
578 **
|
|
579 ** Tokens are often just pointers into the original SQL text and so
|
|
580 ** are not \000 terminated and are not persistent. The returned string
|
|
581 ** is \000 terminated and is persistent.
|
|
582 */
|
|
583 char *sqlite3NameFromToken(Token *pName){
|
|
584 char *zName;
|
|
585 if( pName ){
|
|
586 zName = sqliteStrNDup((char*)pName->z, pName->n);
|
|
587 sqlite3Dequote(zName);
|
|
588 }else{
|
|
589 zName = 0;
|
|
590 }
|
|
591 return zName;
|
|
592 }
|
|
593
|
|
594 /*
|
|
595 ** Open the sqlite_master table stored in database number iDb for
|
|
596 ** writing. The table is opened using cursor 0.
|
|
597 */
|
|
598 void sqlite3OpenMasterTable(Parse *p, int iDb){
|
|
599 Vdbe *v = sqlite3GetVdbe(p);
|
|
600 sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
|
|
601 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
|
|
602 sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
|
|
603 sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
|
|
604 }
|
|
605
|
|
606 /*
|
|
607 ** The token *pName contains the name of a database (either "main" or
|
|
608 ** "temp" or the name of an attached db). This routine returns the
|
|
609 ** index of the named database in db->aDb[], or -1 if the named db
|
|
610 ** does not exist.
|
|
611 */
|
|
612 int sqlite3FindDb(sqlite3 *db, Token *pName){
|
|
613 int i = -1; /* Database number */
|
|
614 int n; /* Number of characters in the name */
|
|
615 Db *pDb; /* A database whose name space is being searched */
|
|
616 char *zName; /* Name we are searching for */
|
|
617
|
|
618 zName = sqlite3NameFromToken(pName);
|
|
619 if( zName ){
|
|
620 n = strlen(zName);
|
|
621 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
|
|
622 if( (!OMIT_TEMPDB || i!=1 ) && n==strlen(pDb->zName) &&
|
|
623 0==sqlite3StrICmp(pDb->zName, zName) ){
|
|
624 break;
|
|
625 }
|
|
626 }
|
|
627 sqliteFree(zName);
|
|
628 }
|
|
629 return i;
|
|
630 }
|
|
631
|
|
632 /* The table or view or trigger name is passed to this routine via tokens
|
|
633 ** pName1 and pName2. If the table name was fully qualified, for example:
|
|
634 **
|
|
635 ** CREATE TABLE xxx.yyy (...);
|
|
636 **
|
|
637 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
|
|
638 ** the table name is not fully qualified, i.e.:
|
|
639 **
|
|
640 ** CREATE TABLE yyy(...);
|
|
641 **
|
|
642 ** Then pName1 is set to "yyy" and pName2 is "".
|
|
643 **
|
|
644 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
|
|
645 ** pName2) that stores the unqualified table name. The index of the
|
|
646 ** database "xxx" is returned.
|
|
647 */
|
|
648 int sqlite3TwoPartName(
|
|
649 Parse *pParse, /* Parsing and code generating context */
|
|
650 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
|
|
651 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
|
|
652 Token **pUnqual /* Write the unqualified object name here */
|
|
653 ){
|
|
654 int iDb; /* Database holding the object */
|
|
655 sqlite3 *db = pParse->db;
|
|
656
|
|
657 if( pName2 && pName2->n>0 ){
|
|
658 assert( !db->init.busy );
|
|
659 *pUnqual = pName2;
|
|
660 iDb = sqlite3FindDb(db, pName1);
|
|
661 if( iDb<0 ){
|
|
662 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
|
|
663 pParse->nErr++;
|
|
664 return -1;
|
|
665 }
|
|
666 }else{
|
|
667 assert( db->init.iDb==0 || db->init.busy );
|
|
668 iDb = db->init.iDb;
|
|
669 *pUnqual = pName1;
|
|
670 }
|
|
671 return iDb;
|
|
672 }
|
|
673
|
|
674 /*
|
|
675 ** This routine is used to check if the UTF-8 string zName is a legal
|
|
676 ** unqualified name for a new schema object (table, index, view or
|
|
677 ** trigger). All names are legal except those that begin with the string
|
|
678 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
|
|
679 ** is reserved for internal use.
|
|
680 */
|
|
681 int sqlite3CheckObjectName(Parse *pParse, const char *zName){
|
|
682 if( !pParse->db->init.busy && pParse->nested==0
|
|
683 && (pParse->db->flags & SQLITE_WriteSchema)==0
|
|
684 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
|
|
685 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
|
|
686 return SQLITE_ERROR;
|
|
687 }
|
|
688 return SQLITE_OK;
|
|
689 }
|
|
690
|
|
691 /*
|
|
692 ** Begin constructing a new table representation in memory. This is
|
|
693 ** the first of several action routines that get called in response
|
|
694 ** to a CREATE TABLE statement. In particular, this routine is called
|
|
695 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
|
|
696 ** flag is true if the table should be stored in the auxiliary database
|
|
697 ** file instead of in the main database file. This is normally the case
|
|
698 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
|
|
699 ** CREATE and TABLE.
|
|
700 **
|
|
701 ** The new table record is initialized and put in pParse->pNewTable.
|
|
702 ** As more of the CREATE TABLE statement is parsed, additional action
|
|
703 ** routines will be called to add more information to this record.
|
|
704 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
|
|
705 ** is called to complete the construction of the new table record.
|
|
706 */
|
|
707 void sqlite3StartTable(
|
|
708 Parse *pParse, /* Parser context */
|
|
709 Token *pName1, /* First part of the name of the table or view */
|
|
710 Token *pName2, /* Second part of the name of the table or view */
|
|
711 int isTemp, /* True if this is a TEMP table */
|
|
712 int isView, /* True if this is a VIEW */
|
|
713 int noErr /* Do nothing if table already exists */
|
|
714 ){
|
|
715 Table *pTable;
|
|
716 char *zName = 0; /* The name of the new table */
|
|
717 sqlite3 *db = pParse->db;
|
|
718 Vdbe *v;
|
|
719 int iDb; /* Database number to create the table in */
|
|
720 Token *pName; /* Unqualified name of the table to create */
|
|
721
|
|
722 /* The table or view name to create is passed to this routine via tokens
|
|
723 ** pName1 and pName2. If the table name was fully qualified, for example:
|
|
724 **
|
|
725 ** CREATE TABLE xxx.yyy (...);
|
|
726 **
|
|
727 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
|
|
728 ** the table name is not fully qualified, i.e.:
|
|
729 **
|
|
730 ** CREATE TABLE yyy(...);
|
|
731 **
|
|
732 ** Then pName1 is set to "yyy" and pName2 is "".
|
|
733 **
|
|
734 ** The call below sets the pName pointer to point at the token (pName1 or
|
|
735 ** pName2) that stores the unqualified table name. The variable iDb is
|
|
736 ** set to the index of the database that the table or view is to be
|
|
737 ** created in.
|
|
738 */
|
|
739 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
|
|
740 if( iDb<0 ) return;
|
|
741 if( !OMIT_TEMPDB && isTemp && iDb>1 ){
|
|
742 /* If creating a temp table, the name may not be qualified */
|
|
743 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
|
|
744 return;
|
|
745 }
|
|
746 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
|
|
747
|
|
748 pParse->sNameToken = *pName;
|
|
749 zName = sqlite3NameFromToken(pName);
|
|
750 if( zName==0 ) return;
|
|
751 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
|
|
752 goto begin_table_error;
|
|
753 }
|
|
754 if( db->init.iDb==1 ) isTemp = 1;
|
|
755 #ifndef SQLITE_OMIT_AUTHORIZATION
|
|
756 assert( (isTemp & 1)==isTemp );
|
|
757 {
|
|
758 int code;
|
|
759 char *zDb = db->aDb[iDb].zName;
|
|
760 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
|
|
761 goto begin_table_error;
|
|
762 }
|
|
763 if( isView ){
|
|
764 if( !OMIT_TEMPDB && isTemp ){
|
|
765 code = SQLITE_CREATE_TEMP_VIEW;
|
|
766 }else{
|
|
767 code = SQLITE_CREATE_VIEW;
|
|
768 }
|
|
769 }else{
|
|
770 if( !OMIT_TEMPDB && isTemp ){
|
|
771 code = SQLITE_CREATE_TEMP_TABLE;
|
|
772 }else{
|
|
773 code = SQLITE_CREATE_TABLE;
|
|
774 }
|
|
775 }
|
|
776 if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
|
|
777 goto begin_table_error;
|
|
778 }
|
|
779 }
|
|
780 #endif
|
|
781
|
|
782 /* Make sure the new table name does not collide with an existing
|
|
783 ** index or table name in the same database. Issue an error message if
|
|
784 ** it does.
|
|
785 */
|
|
786 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
|
|
787 goto begin_table_error;
|
|
788 }
|
|
789 pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
|
|
790 if( pTable ){
|
|
791 if( !noErr ){
|
|
792 sqlite3ErrorMsg(pParse, "table %T already exists", pName);
|
|
793 }
|
|
794 goto begin_table_error;
|
|
795 }
|
|
796 if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
|
|
797 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
|
|
798 goto begin_table_error;
|
|
799 }
|
|
800 pTable = sqliteMalloc( sizeof(Table) );
|
|
801 if( pTable==0 ){
|
|
802 pParse->rc = SQLITE_NOMEM;
|
|
803 pParse->nErr++;
|
|
804 goto begin_table_error;
|
|
805 }
|
|
806 pTable->zName = zName;
|
|
807 pTable->nCol = 0;
|
|
808 pTable->aCol = 0;
|
|
809 pTable->iPKey = -1;
|
|
810 pTable->pIndex = 0;
|
|
811 pTable->pSchema = db->aDb[iDb].pSchema;
|
|
812 pTable->nRef = 1;
|
|
813 if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable);
|
|
814 pParse->pNewTable = pTable;
|
|
815
|
|
816 /* If this is the magic sqlite_sequence table used by autoincrement,
|
|
817 ** then record a pointer to this table in the main database structure
|
|
818 ** so that INSERT can find the table easily.
|
|
819 */
|
|
820 #ifndef SQLITE_OMIT_AUTOINCREMENT
|
|
821 if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
|
|
822 pTable->pSchema->pSeqTab = pTable;
|
|
823 }
|
|
824 #endif
|
|
825
|
|
826 /* Begin generating the code that will insert the table record into
|
|
827 ** the SQLITE_MASTER table. Note in particular that we must go ahead
|
|
828 ** and allocate the record number for the table entry now. Before any
|
|
829 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
|
|
830 ** indices to be created and the table record must come before the
|
|
831 ** indices. Hence, the record number for the table must be allocated
|
|
832 ** now.
|
|
833 */
|
|
834 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
|
|
835 int lbl;
|
|
836 int fileFormat;
|
|
837 sqlite3BeginWriteOperation(pParse, 0, iDb);
|
|
838
|
|
839 /* If the file format and encoding in the database have not been set,
|
|
840 ** set them now.
|
|
841 */
|
|
842 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /* file_format */
|
|
843 lbl = sqlite3VdbeMakeLabel(v);
|
|
844 sqlite3VdbeAddOp(v, OP_If, 0, lbl);
|
|
845 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
|
|
846 1 : SQLITE_DEFAULT_FILE_FORMAT;
|
|
847 sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0);
|
|
848 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
|
|
849 sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0);
|
|
850 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4);
|
|
851 sqlite3VdbeResolveLabel(v, lbl);
|
|
852
|
|
853 /* This just creates a place-holder record in the sqlite_master table.
|
|
854 ** The record created does not contain anything yet. It will be replaced
|
|
855 ** by the real entry in code generated at sqlite3EndTable().
|
|
856 **
|
|
857 ** The rowid for the new entry is left on the top of the stack.
|
|
858 ** The rowid value is needed by the code that sqlite3EndTable will
|
|
859 ** generate.
|
|
860 */
|
|
861 #ifndef SQLITE_OMIT_VIEW
|
|
862 if( isView ){
|
|
863 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
|
|
864 }else
|
|
865 #endif
|
|
866 {
|
|
867 sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0);
|
|
868 }
|
|
869 sqlite3OpenMasterTable(pParse, iDb);
|
|
870 sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0);
|
|
871 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
|
|
872 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
|
|
873 sqlite3VdbeAddOp(v, OP_Insert, 0, 0);
|
|
874 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
|
|
875 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
|
|
876 }
|
|
877
|
|
878 /* Normal (non-error) return. */
|
|
879 return;
|
|
880
|
|
881 /* If an error occurs, we jump here */
|
|
882 begin_table_error:
|
|
883 sqliteFree(zName);
|
|
884 return;
|
|
885 }
|
|
886
|
|
887 /*
|
|
888 ** This macro is used to compare two strings in a case-insensitive manner.
|
|
889 ** It is slightly faster than calling sqlite3StrICmp() directly, but
|
|
890 ** produces larger code.
|
|
891 **
|
|
892 ** WARNING: This macro is not compatible with the strcmp() family. It
|
|
893 ** returns true if the two strings are equal, otherwise false.
|
|
894 */
|
|
895 #define STRICMP(x, y) (\
|
|
896 sqlite3UpperToLower[*(unsigned char *)(x)]== \
|
|
897 sqlite3UpperToLower[*(unsigned char *)(y)] \
|
|
898 && sqlite3StrICmp((x)+1,(y)+1)==0 )
|
|
899
|
|
900 /*
|
|
901 ** Add a new column to the table currently being constructed.
|
|
902 **
|
|
903 ** The parser calls this routine once for each column declaration
|
|
904 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
|
|
905 ** first to get things going. Then this routine is called for each
|
|
906 ** column.
|
|
907 */
|
|
908 void sqlite3AddColumn(Parse *pParse, Token *pName){
|
|
909 Table *p;
|
|
910 int i;
|
|
911 char *z;
|
|
912 Column *pCol;
|
|
913 if( (p = pParse->pNewTable)==0 ) return;
|
|
914 z = sqlite3NameFromToken(pName);
|
|
915 if( z==0 ) return;
|
|
916 for(i=0; i<p->nCol; i++){
|
|
917 if( STRICMP(z, p->aCol[i].zName) ){
|
|
918 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
|
|
919 sqliteFree(z);
|
|
920 return;
|
|
921 }
|
|
922 }
|
|
923 if( (p->nCol & 0x7)==0 ){
|
|
924 Column *aNew;
|
|
925 aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
|
|
926 if( aNew==0 ){
|
|
927 sqliteFree(z);
|
|
928 return;
|
|
929 }
|
|
930 p->aCol = aNew;
|
|
931 }
|
|
932 pCol = &p->aCol[p->nCol];
|
|
933 memset(pCol, 0, sizeof(p->aCol[0]));
|
|
934 pCol->zName = z;
|
|
935
|
|
936 /* If there is no type specified, columns have the default affinity
|
|
937 ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
|
|
938 ** be called next to set pCol->affinity correctly.
|
|
939 */
|
|
940 pCol->affinity = SQLITE_AFF_NONE;
|
|
941 p->nCol++;
|
|
942 }
|
|
943
|
|
944 /*
|
|
945 ** This routine is called by the parser while in the middle of
|
|
946 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
|
|
947 ** been seen on a column. This routine sets the notNull flag on
|
|
948 ** the column currently under construction.
|
|
949 */
|
|
950 void sqlite3AddNotNull(Parse *pParse, int onError){
|
|
951 Table *p;
|
|
952 int i;
|
|
953 if( (p = pParse->pNewTable)==0 ) return;
|
|
954 i = p->nCol-1;
|
|
955 if( i>=0 ) p->aCol[i].notNull = onError;
|
|
956 }
|
|
957
|
|
958 /*
|
|
959 ** Scan the column type name zType (length nType) and return the
|
|
960 ** associated affinity type.
|
|
961 **
|
|
962 ** This routine does a case-independent search of zType for the
|
|
963 ** substrings in the following table. If one of the substrings is
|
|
964 ** found, the corresponding affinity is returned. If zType contains
|
|
965 ** more than one of the substrings, entries toward the top of
|
|
966 ** the table take priority. For example, if zType is 'BLOBINT',
|
|
967 ** SQLITE_AFF_INTEGER is returned.
|
|
968 **
|
|
969 ** Substring | Affinity
|
|
970 ** --------------------------------
|
|
971 ** 'INT' | SQLITE_AFF_INTEGER
|
|
972 ** 'CHAR' | SQLITE_AFF_TEXT
|
|
973 ** 'CLOB' | SQLITE_AFF_TEXT
|
|
974 ** 'TEXT' | SQLITE_AFF_TEXT
|
|
975 ** 'BLOB' | SQLITE_AFF_NONE
|
|
976 ** 'REAL' | SQLITE_AFF_REAL
|
|
977 ** 'FLOA' | SQLITE_AFF_REAL
|
|
978 ** 'DOUB' | SQLITE_AFF_REAL
|
|
979 **
|
|
980 ** If none of the substrings in the above table are found,
|
|
981 ** SQLITE_AFF_NUMERIC is returned.
|
|
982 */
|
|
983 char sqlite3AffinityType(const Token *pType){
|
|
984 u32 h = 0;
|
|
985 char aff = SQLITE_AFF_NUMERIC;
|
|
986 const unsigned char *zIn = pType->z;
|
|
987 const unsigned char *zEnd = &pType->z[pType->n];
|
|
988
|
|
989 while( zIn!=zEnd ){
|
|
990 h = (h<<8) + sqlite3UpperToLower[*zIn];
|
|
991 zIn++;
|
|
992 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
|
|
993 aff = SQLITE_AFF_TEXT;
|
|
994 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
|
|
995 aff = SQLITE_AFF_TEXT;
|
|
996 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
|
|
997 aff = SQLITE_AFF_TEXT;
|
|
998 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
|
|
999 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
|
|
1000 aff = SQLITE_AFF_NONE;
|
|
1001 #ifndef SQLITE_OMIT_FLOATING_POINT
|
|
1002 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
|
|
1003 && aff==SQLITE_AFF_NUMERIC ){
|
|
1004 aff = SQLITE_AFF_REAL;
|
|
1005 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
|
|
1006 && aff==SQLITE_AFF_NUMERIC ){
|
|
1007 aff = SQLITE_AFF_REAL;
|
|
1008 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
|
|
1009 && aff==SQLITE_AFF_NUMERIC ){
|
|
1010 aff = SQLITE_AFF_REAL;
|
|
1011 #endif
|
|
1012 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
|
|
1013 aff = SQLITE_AFF_INTEGER;
|
|
1014 break;
|
|
1015 }
|
|
1016 }
|
|
1017
|
|
1018 return aff;
|
|
1019 }
|
|
1020
|
|
1021 /*
|
|
1022 ** This routine is called by the parser while in the middle of
|
|
1023 ** parsing a CREATE TABLE statement. The pFirst token is the first
|
|
1024 ** token in the sequence of tokens that describe the type of the
|
|
1025 ** column currently under construction. pLast is the last token
|
|
1026 ** in the sequence. Use this information to construct a string
|
|
1027 ** that contains the typename of the column and store that string
|
|
1028 ** in zType.
|
|
1029 */
|
|
1030 void sqlite3AddColumnType(Parse *pParse, Token *pType){
|
|
1031 Table *p;
|
|
1032 int i;
|
|
1033 Column *pCol;
|
|
1034
|
|
1035 if( (p = pParse->pNewTable)==0 ) return;
|
|
1036 i = p->nCol-1;
|
|
1037 if( i<0 ) return;
|
|
1038 pCol = &p->aCol[i];
|
|
1039 sqliteFree(pCol->zType);
|
|
1040 pCol->zType = sqlite3NameFromToken(pType);
|
|
1041 pCol->affinity = sqlite3AffinityType(pType);
|
|
1042 }
|
|
1043
|
|
1044 /*
|
|
1045 ** The expression is the default value for the most recently added column
|
|
1046 ** of the table currently under construction.
|
|
1047 **
|
|
1048 ** Default value expressions must be constant. Raise an exception if this
|
|
1049 ** is not the case.
|
|
1050 **
|
|
1051 ** This routine is called by the parser while in the middle of
|
|
1052 ** parsing a CREATE TABLE statement.
|
|
1053 */
|
|
1054 void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
|
|
1055 Table *p;
|
|
1056 Column *pCol;
|
|
1057 if( (p = pParse->pNewTable)!=0 ){
|
|
1058 pCol = &(p->aCol[p->nCol-1]);
|
|
1059 if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
|
|
1060 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
|
|
1061 pCol->zName);
|
|
1062 }else{
|
|
1063 sqlite3ExprDelete(pCol->pDflt);
|
|
1064 pCol->pDflt = sqlite3ExprDup(pExpr);
|
|
1065 }
|
|
1066 }
|
|
1067 sqlite3ExprDelete(pExpr);
|
|
1068 }
|
|
1069
|
|
1070 /*
|
|
1071 ** Designate the PRIMARY KEY for the table. pList is a list of names
|
|
1072 ** of columns that form the primary key. If pList is NULL, then the
|
|
1073 ** most recently added column of the table is the primary key.
|
|
1074 **
|
|
1075 ** A table can have at most one primary key. If the table already has
|
|
1076 ** a primary key (and this is the second primary key) then create an
|
|
1077 ** error.
|
|
1078 **
|
|
1079 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
|
|
1080 ** then we will try to use that column as the rowid. Set the Table.iPKey
|
|
1081 ** field of the table under construction to be the index of the
|
|
1082 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
|
|
1083 ** no INTEGER PRIMARY KEY.
|
|
1084 **
|
|
1085 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
|
|
1086 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
|
|
1087 */
|
|
1088 void sqlite3AddPrimaryKey(
|
|
1089 Parse *pParse, /* Parsing context */
|
|
1090 ExprList *pList, /* List of field names to be indexed */
|
|
1091 int onError, /* What to do with a uniqueness conflict */
|
|
1092 int autoInc, /* True if the AUTOINCREMENT keyword is present */
|
|
1093 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
|
|
1094 ){
|
|
1095 Table *pTab = pParse->pNewTable;
|
|
1096 char *zType = 0;
|
|
1097 int iCol = -1, i;
|
|
1098 if( pTab==0 ) goto primary_key_exit;
|
|
1099 if( pTab->hasPrimKey ){
|
|
1100 sqlite3ErrorMsg(pParse,
|
|
1101 "table \"%s\" has more than one primary key", pTab->zName);
|
|
1102 goto primary_key_exit;
|
|
1103 }
|
|
1104 pTab->hasPrimKey = 1;
|
|
1105 if( pList==0 ){
|
|
1106 iCol = pTab->nCol - 1;
|
|
1107 pTab->aCol[iCol].isPrimKey = 1;
|
|
1108 }else{
|
|
1109 for(i=0; i<pList->nExpr; i++){
|
|
1110 for(iCol=0; iCol<pTab->nCol; iCol++){
|
|
1111 if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
|
|
1112 break;
|
|
1113 }
|
|
1114 }
|
|
1115 if( iCol<pTab->nCol ){
|
|
1116 pTab->aCol[iCol].isPrimKey = 1;
|
|
1117 }
|
|
1118 }
|
|
1119 if( pList->nExpr>1 ) iCol = -1;
|
|
1120 }
|
|
1121 if( iCol>=0 && iCol<pTab->nCol ){
|
|
1122 zType = pTab->aCol[iCol].zType;
|
|
1123 }
|
|
1124 if( zType && sqlite3StrICmp(zType, "INTEGER")==0
|
|
1125 && sortOrder==SQLITE_SO_ASC ){
|
|
1126 pTab->iPKey = iCol;
|
|
1127 pTab->keyConf = onError;
|
|
1128 pTab->autoInc = autoInc;
|
|
1129 }else if( autoInc ){
|
|
1130 #ifndef SQLITE_OMIT_AUTOINCREMENT
|
|
1131 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
|
|
1132 "INTEGER PRIMARY KEY");
|
|
1133 #endif
|
|
1134 }else{
|
|
1135 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
|
|
1136 pList = 0;
|
|
1137 }
|
|
1138
|
|
1139 primary_key_exit:
|
|
1140 sqlite3ExprListDelete(pList);
|
|
1141 return;
|
|
1142 }
|
|
1143
|
|
1144 /*
|
|
1145 ** Add a new CHECK constraint to the table currently under construction.
|
|
1146 */
|
|
1147 void sqlite3AddCheckConstraint(
|
|
1148 Parse *pParse, /* Parsing context */
|
|
1149 Expr *pCheckExpr /* The check expression */
|
|
1150 ){
|
|
1151 #ifndef SQLITE_OMIT_CHECK
|
|
1152 Table *pTab = pParse->pNewTable;
|
|
1153 if( pTab ){
|
|
1154 /* The CHECK expression must be duplicated so that tokens refer
|
|
1155 ** to malloced space and not the (ephemeral) text of the CREATE TABLE
|
|
1156 ** statement */
|
|
1157 pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
|
|
1158 }
|
|
1159 #endif
|
|
1160 sqlite3ExprDelete(pCheckExpr);
|
|
1161 }
|
|
1162
|
|
1163 /*
|
|
1164 ** Set the collation function of the most recently parsed table column
|
|
1165 ** to the CollSeq given.
|
|
1166 */
|
|
1167 void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
|
|
1168 Table *p;
|
|
1169 int i;
|
|
1170
|
|
1171 if( (p = pParse->pNewTable)==0 ) return;
|
|
1172 i = p->nCol-1;
|
|
1173
|
|
1174 if( sqlite3LocateCollSeq(pParse, zType, nType) ){
|
|
1175 Index *pIdx;
|
|
1176 p->aCol[i].zColl = sqliteStrNDup(zType, nType);
|
|
1177
|
|
1178 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
|
|
1179 ** then an index may have been created on this column before the
|
|
1180 ** collation type was added. Correct this if it is the case.
|
|
1181 */
|
|
1182 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
1183 assert( pIdx->nColumn==1 );
|
|
1184 if( pIdx->aiColumn[0]==i ){
|
|
1185 pIdx->azColl[0] = p->aCol[i].zColl;
|
|
1186 }
|
|
1187 }
|
|
1188 }
|
|
1189 }
|
|
1190
|
|
1191 /*
|
|
1192 ** This function returns the collation sequence for database native text
|
|
1193 ** encoding identified by the string zName, length nName.
|
|
1194 **
|
|
1195 ** If the requested collation sequence is not available, or not available
|
|
1196 ** in the database native encoding, the collation factory is invoked to
|
|
1197 ** request it. If the collation factory does not supply such a sequence,
|
|
1198 ** and the sequence is available in another text encoding, then that is
|
|
1199 ** returned instead.
|
|
1200 **
|
|
1201 ** If no versions of the requested collations sequence are available, or
|
|
1202 ** another error occurs, NULL is returned and an error message written into
|
|
1203 ** pParse.
|
|
1204 */
|
|
1205 CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
|
|
1206 sqlite3 *db = pParse->db;
|
|
1207 u8 enc = ENC(db);
|
|
1208 u8 initbusy = db->init.busy;
|
|
1209 CollSeq *pColl;
|
|
1210
|
|
1211 pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
|
|
1212 if( !initbusy && (!pColl || !pColl->xCmp) ){
|
|
1213 pColl = sqlite3GetCollSeq(db, pColl, zName, nName);
|
|
1214 if( !pColl ){
|
|
1215 if( nName<0 ){
|
|
1216 nName = strlen(zName);
|
|
1217 }
|
|
1218 sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName);
|
|
1219 pColl = 0;
|
|
1220 }
|
|
1221 }
|
|
1222
|
|
1223 return pColl;
|
|
1224 }
|
|
1225
|
|
1226
|
|
1227 /*
|
|
1228 ** Generate code that will increment the schema cookie.
|
|
1229 **
|
|
1230 ** The schema cookie is used to determine when the schema for the
|
|
1231 ** database changes. After each schema change, the cookie value
|
|
1232 ** changes. When a process first reads the schema it records the
|
|
1233 ** cookie. Thereafter, whenever it goes to access the database,
|
|
1234 ** it checks the cookie to make sure the schema has not changed
|
|
1235 ** since it was last read.
|
|
1236 **
|
|
1237 ** This plan is not completely bullet-proof. It is possible for
|
|
1238 ** the schema to change multiple times and for the cookie to be
|
|
1239 ** set back to prior value. But schema changes are infrequent
|
|
1240 ** and the probability of hitting the same cookie value is only
|
|
1241 ** 1 chance in 2^32. So we're safe enough.
|
|
1242 */
|
|
1243 void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
|
|
1244 sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
|
|
1245 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
|
|
1246 }
|
|
1247
|
|
1248 /*
|
|
1249 ** Measure the number of characters needed to output the given
|
|
1250 ** identifier. The number returned includes any quotes used
|
|
1251 ** but does not include the null terminator.
|
|
1252 **
|
|
1253 ** The estimate is conservative. It might be larger that what is
|
|
1254 ** really needed.
|
|
1255 */
|
|
1256 static int identLength(const char *z){
|
|
1257 int n;
|
|
1258 for(n=0; *z; n++, z++){
|
|
1259 if( *z=='"' ){ n++; }
|
|
1260 }
|
|
1261 return n + 2;
|
|
1262 }
|
|
1263
|
|
1264 /*
|
|
1265 ** Write an identifier onto the end of the given string. Add
|
|
1266 ** quote characters as needed.
|
|
1267 */
|
|
1268 static void identPut(char *z, int *pIdx, char *zSignedIdent){
|
|
1269 unsigned char *zIdent = (unsigned char*)zSignedIdent;
|
|
1270 int i, j, needQuote;
|
|
1271 i = *pIdx;
|
|
1272 for(j=0; zIdent[j]; j++){
|
|
1273 if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
|
|
1274 }
|
|
1275 needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
|
|
1276 || sqlite3KeywordCode(zIdent, j)!=TK_ID;
|
|
1277 if( needQuote ) z[i++] = '"';
|
|
1278 for(j=0; zIdent[j]; j++){
|
|
1279 z[i++] = zIdent[j];
|
|
1280 if( zIdent[j]=='"' ) z[i++] = '"';
|
|
1281 }
|
|
1282 if( needQuote ) z[i++] = '"';
|
|
1283 z[i] = 0;
|
|
1284 *pIdx = i;
|
|
1285 }
|
|
1286
|
|
1287 /*
|
|
1288 ** Generate a CREATE TABLE statement appropriate for the given
|
|
1289 ** table. Memory to hold the text of the statement is obtained
|
|
1290 ** from sqliteMalloc() and must be freed by the calling function.
|
|
1291 */
|
|
1292 static char *createTableStmt(Table *p, int isTemp){
|
|
1293 int i, k, n;
|
|
1294 char *zStmt;
|
|
1295 char *zSep, *zSep2, *zEnd, *z;
|
|
1296 Column *pCol;
|
|
1297 n = 0;
|
|
1298 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
|
|
1299 n += identLength(pCol->zName);
|
|
1300 z = pCol->zType;
|
|
1301 if( z ){
|
|
1302 n += (strlen(z) + 1);
|
|
1303 }
|
|
1304 }
|
|
1305 n += identLength(p->zName);
|
|
1306 if( n<50 ){
|
|
1307 zSep = "";
|
|
1308 zSep2 = ",";
|
|
1309 zEnd = ")";
|
|
1310 }else{
|
|
1311 zSep = "\n ";
|
|
1312 zSep2 = ",\n ";
|
|
1313 zEnd = "\n)";
|
|
1314 }
|
|
1315 n += 35 + 6*p->nCol;
|
|
1316 zStmt = sqliteMallocRaw( n );
|
|
1317 if( zStmt==0 ) return 0;
|
|
1318 strcpy(zStmt, !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
|
|
1319 k = strlen(zStmt);
|
|
1320 identPut(zStmt, &k, p->zName);
|
|
1321 zStmt[k++] = '(';
|
|
1322 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
|
|
1323 strcpy(&zStmt[k], zSep);
|
|
1324 k += strlen(&zStmt[k]);
|
|
1325 zSep = zSep2;
|
|
1326 identPut(zStmt, &k, pCol->zName);
|
|
1327 if( (z = pCol->zType)!=0 ){
|
|
1328 zStmt[k++] = ' ';
|
|
1329 strcpy(&zStmt[k], z);
|
|
1330 k += strlen(z);
|
|
1331 }
|
|
1332 }
|
|
1333 strcpy(&zStmt[k], zEnd);
|
|
1334 return zStmt;
|
|
1335 }
|
|
1336
|
|
1337 /*
|
|
1338 ** This routine is called to report the final ")" that terminates
|
|
1339 ** a CREATE TABLE statement.
|
|
1340 **
|
|
1341 ** The table structure that other action routines have been building
|
|
1342 ** is added to the internal hash tables, assuming no errors have
|
|
1343 ** occurred.
|
|
1344 **
|
|
1345 ** An entry for the table is made in the master table on disk, unless
|
|
1346 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
|
|
1347 ** it means we are reading the sqlite_master table because we just
|
|
1348 ** connected to the database or because the sqlite_master table has
|
|
1349 ** recently changed, so the entry for this table already exists in
|
|
1350 ** the sqlite_master table. We do not want to create it again.
|
|
1351 **
|
|
1352 ** If the pSelect argument is not NULL, it means that this routine
|
|
1353 ** was called to create a table generated from a
|
|
1354 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
|
|
1355 ** the new table will match the result set of the SELECT.
|
|
1356 */
|
|
1357 void sqlite3EndTable(
|
|
1358 Parse *pParse, /* Parse context */
|
|
1359 Token *pCons, /* The ',' token after the last column defn. */
|
|
1360 Token *pEnd, /* The final ')' token in the CREATE TABLE */
|
|
1361 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
|
|
1362 ){
|
|
1363 Table *p;
|
|
1364 sqlite3 *db = pParse->db;
|
|
1365 int iDb;
|
|
1366
|
|
1367 if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) {
|
|
1368 return;
|
|
1369 }
|
|
1370 p = pParse->pNewTable;
|
|
1371 if( p==0 ) return;
|
|
1372
|
|
1373 assert( !db->init.busy || !pSelect );
|
|
1374
|
|
1375 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
|
|
1376
|
|
1377 #ifndef SQLITE_OMIT_CHECK
|
|
1378 /* Resolve names in all CHECK constraint expressions.
|
|
1379 */
|
|
1380 if( p->pCheck ){
|
|
1381 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
|
|
1382 NameContext sNC; /* Name context for pParse->pNewTable */
|
|
1383
|
|
1384 memset(&sNC, 0, sizeof(sNC));
|
|
1385 memset(&sSrc, 0, sizeof(sSrc));
|
|
1386 sSrc.nSrc = 1;
|
|
1387 sSrc.a[0].zName = p->zName;
|
|
1388 sSrc.a[0].pTab = p;
|
|
1389 sSrc.a[0].iCursor = -1;
|
|
1390 sNC.pParse = pParse;
|
|
1391 sNC.pSrcList = &sSrc;
|
|
1392 sNC.isCheck = 1;
|
|
1393 if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){
|
|
1394 return;
|
|
1395 }
|
|
1396 }
|
|
1397 #endif /* !defined(SQLITE_OMIT_CHECK) */
|
|
1398
|
|
1399 /* If the db->init.busy is 1 it means we are reading the SQL off the
|
|
1400 ** "sqlite_master" or "sqlite_temp_master" table on the disk.
|
|
1401 ** So do not write to the disk again. Extract the root page number
|
|
1402 ** for the table from the db->init.newTnum field. (The page number
|
|
1403 ** should have been put there by the sqliteOpenCb routine.)
|
|
1404 */
|
|
1405 if( db->init.busy ){
|
|
1406 p->tnum = db->init.newTnum;
|
|
1407 }
|
|
1408
|
|
1409 /* If not initializing, then create a record for the new table
|
|
1410 ** in the SQLITE_MASTER table of the database. The record number
|
|
1411 ** for the new table entry should already be on the stack.
|
|
1412 **
|
|
1413 ** If this is a TEMPORARY table, write the entry into the auxiliary
|
|
1414 ** file instead of into the main database file.
|
|
1415 */
|
|
1416 if( !db->init.busy ){
|
|
1417 int n;
|
|
1418 Vdbe *v;
|
|
1419 char *zType; /* "view" or "table" */
|
|
1420 char *zType2; /* "VIEW" or "TABLE" */
|
|
1421 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
|
|
1422
|
|
1423 v = sqlite3GetVdbe(pParse);
|
|
1424 if( v==0 ) return;
|
|
1425
|
|
1426 sqlite3VdbeAddOp(v, OP_Close, 0, 0);
|
|
1427
|
|
1428 /* Create the rootpage for the new table and push it onto the stack.
|
|
1429 ** A view has no rootpage, so just push a zero onto the stack for
|
|
1430 ** views. Initialize zType at the same time.
|
|
1431 */
|
|
1432 if( p->pSelect==0 ){
|
|
1433 /* A regular table */
|
|
1434 zType = "table";
|
|
1435 zType2 = "TABLE";
|
|
1436 #ifndef SQLITE_OMIT_VIEW
|
|
1437 }else{
|
|
1438 /* A view */
|
|
1439 zType = "view";
|
|
1440 zType2 = "VIEW";
|
|
1441 #endif
|
|
1442 }
|
|
1443
|
|
1444 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
|
|
1445 ** statement to populate the new table. The root-page number for the
|
|
1446 ** new table is on the top of the vdbe stack.
|
|
1447 **
|
|
1448 ** Once the SELECT has been coded by sqlite3Select(), it is in a
|
|
1449 ** suitable state to query for the column names and types to be used
|
|
1450 ** by the new table.
|
|
1451 **
|
|
1452 ** A shared-cache write-lock is not required to write to the new table,
|
|
1453 ** as a schema-lock must have already been obtained to create it. Since
|
|
1454 ** a schema-lock excludes all other database users, the write-lock would
|
|
1455 ** be redundant.
|
|
1456 */
|
|
1457 if( pSelect ){
|
|
1458 Table *pSelTab;
|
|
1459 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
|
|
1460 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
|
|
1461 sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0);
|
|
1462 pParse->nTab = 2;
|
|
1463 sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0);
|
|
1464 sqlite3VdbeAddOp(v, OP_Close, 1, 0);
|
|
1465 if( pParse->nErr==0 ){
|
|
1466 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect);
|
|
1467 if( pSelTab==0 ) return;
|
|
1468 assert( p->aCol==0 );
|
|
1469 p->nCol = pSelTab->nCol;
|
|
1470 p->aCol = pSelTab->aCol;
|
|
1471 pSelTab->nCol = 0;
|
|
1472 pSelTab->aCol = 0;
|
|
1473 sqlite3DeleteTable(0, pSelTab);
|
|
1474 }
|
|
1475 }
|
|
1476
|
|
1477 /* Compute the complete text of the CREATE statement */
|
|
1478 if( pSelect ){
|
|
1479 zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema);
|
|
1480 }else{
|
|
1481 n = pEnd->z - pParse->sNameToken.z + 1;
|
|
1482 zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z);
|
|
1483 }
|
|
1484
|
|
1485 /* A slot for the record has already been allocated in the
|
|
1486 ** SQLITE_MASTER table. We just need to update that slot with all
|
|
1487 ** the information we've collected. The rowid for the preallocated
|
|
1488 ** slot is the 2nd item on the stack. The top of the stack is the
|
|
1489 ** root page for the new table (or a 0 if this is a view).
|
|
1490 */
|
|
1491 sqlite3NestedParse(pParse,
|
|
1492 "UPDATE %Q.%s "
|
|
1493 "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q "
|
|
1494 "WHERE rowid=#1",
|
|
1495 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
|
|
1496 zType,
|
|
1497 p->zName,
|
|
1498 p->zName,
|
|
1499 zStmt
|
|
1500 );
|
|
1501 sqliteFree(zStmt);
|
|
1502 sqlite3ChangeCookie(db, v, iDb);
|
|
1503
|
|
1504 #ifndef SQLITE_OMIT_AUTOINCREMENT
|
|
1505 /* Check to see if we need to create an sqlite_sequence table for
|
|
1506 ** keeping track of autoincrement keys.
|
|
1507 */
|
|
1508 if( p->autoInc ){
|
|
1509 Db *pDb = &db->aDb[iDb];
|
|
1510 if( pDb->pSchema->pSeqTab==0 ){
|
|
1511 sqlite3NestedParse(pParse,
|
|
1512 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
|
|
1513 pDb->zName
|
|
1514 );
|
|
1515 }
|
|
1516 }
|
|
1517 #endif
|
|
1518
|
|
1519 /* Reparse everything to update our internal data structures */
|
|
1520 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
|
|
1521 sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC);
|
|
1522 }
|
|
1523
|
|
1524
|
|
1525 /* Add the table to the in-memory representation of the database.
|
|
1526 */
|
|
1527 if( db->init.busy && pParse->nErr==0 ){
|
|
1528 Table *pOld;
|
|
1529 FKey *pFKey;
|
|
1530 Schema *pSchema = p->pSchema;
|
|
1531 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p);
|
|
1532 if( pOld ){
|
|
1533 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
|
|
1534 return;
|
|
1535 }
|
|
1536 #ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
1537 for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
|
|
1538 int nTo = strlen(pFKey->zTo) + 1;
|
|
1539 pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo);
|
|
1540 sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey);
|
|
1541 }
|
|
1542 #endif
|
|
1543 pParse->pNewTable = 0;
|
|
1544 db->nTable++;
|
|
1545 db->flags |= SQLITE_InternChanges;
|
|
1546
|
|
1547 #ifndef SQLITE_OMIT_ALTERTABLE
|
|
1548 if( !p->pSelect ){
|
|
1549 const char *zName = (const char *)pParse->sNameToken.z;
|
|
1550 int nName;
|
|
1551 assert( !pSelect && pCons && pEnd );
|
|
1552 if( pCons->z==0 ){
|
|
1553 pCons = pEnd;
|
|
1554 }
|
|
1555 nName = (const char *)pCons->z - zName;
|
|
1556 p->addColOffset = 13 + sqlite3utf8CharLen(zName, nName);
|
|
1557 }
|
|
1558 #endif
|
|
1559 }
|
|
1560 }
|
|
1561
|
|
1562 #ifndef SQLITE_OMIT_VIEW
|
|
1563 /*
|
|
1564 ** The parser calls this routine in order to create a new VIEW
|
|
1565 */
|
|
1566 void sqlite3CreateView(
|
|
1567 Parse *pParse, /* The parsing context */
|
|
1568 Token *pBegin, /* The CREATE token that begins the statement */
|
|
1569 Token *pName1, /* The token that holds the name of the view */
|
|
1570 Token *pName2, /* The token that holds the name of the view */
|
|
1571 Select *pSelect, /* A SELECT statement that will become the new view */
|
|
1572 int isTemp /* TRUE for a TEMPORARY view */
|
|
1573 ){
|
|
1574 Table *p;
|
|
1575 int n;
|
|
1576 const unsigned char *z;
|
|
1577 Token sEnd;
|
|
1578 DbFixer sFix;
|
|
1579 Token *pName;
|
|
1580 int iDb;
|
|
1581
|
|
1582 if( pParse->nVar>0 ){
|
|
1583 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
|
|
1584 sqlite3SelectDelete(pSelect);
|
|
1585 return;
|
|
1586 }
|
|
1587 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0);
|
|
1588 p = pParse->pNewTable;
|
|
1589 if( p==0 || pParse->nErr ){
|
|
1590 sqlite3SelectDelete(pSelect);
|
|
1591 return;
|
|
1592 }
|
|
1593 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
|
|
1594 iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
|
|
1595 if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
|
|
1596 && sqlite3FixSelect(&sFix, pSelect)
|
|
1597 ){
|
|
1598 sqlite3SelectDelete(pSelect);
|
|
1599 return;
|
|
1600 }
|
|
1601
|
|
1602 /* Make a copy of the entire SELECT statement that defines the view.
|
|
1603 ** This will force all the Expr.token.z values to be dynamically
|
|
1604 ** allocated rather than point to the input string - which means that
|
|
1605 ** they will persist after the current sqlite3_exec() call returns.
|
|
1606 */
|
|
1607 p->pSelect = sqlite3SelectDup(pSelect);
|
|
1608 sqlite3SelectDelete(pSelect);
|
|
1609 if( sqlite3MallocFailed() ){
|
|
1610 return;
|
|
1611 }
|
|
1612 if( !pParse->db->init.busy ){
|
|
1613 sqlite3ViewGetColumnNames(pParse, p);
|
|
1614 }
|
|
1615
|
|
1616 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
|
|
1617 ** the end.
|
|
1618 */
|
|
1619 sEnd = pParse->sLastToken;
|
|
1620 if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
|
|
1621 sEnd.z += sEnd.n;
|
|
1622 }
|
|
1623 sEnd.n = 0;
|
|
1624 n = sEnd.z - pBegin->z;
|
|
1625 z = (const unsigned char*)pBegin->z;
|
|
1626 while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
|
|
1627 sEnd.z = &z[n-1];
|
|
1628 sEnd.n = 1;
|
|
1629
|
|
1630 /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
|
|
1631 sqlite3EndTable(pParse, 0, &sEnd, 0);
|
|
1632 return;
|
|
1633 }
|
|
1634 #endif /* SQLITE_OMIT_VIEW */
|
|
1635
|
|
1636 #ifndef SQLITE_OMIT_VIEW
|
|
1637 /*
|
|
1638 ** The Table structure pTable is really a VIEW. Fill in the names of
|
|
1639 ** the columns of the view in the pTable structure. Return the number
|
|
1640 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
|
|
1641 */
|
|
1642 int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
|
|
1643 Table *pSelTab; /* A fake table from which we get the result set */
|
|
1644 Select *pSel; /* Copy of the SELECT that implements the view */
|
|
1645 int nErr = 0; /* Number of errors encountered */
|
|
1646 int n; /* Temporarily holds the number of cursors assigned */
|
|
1647
|
|
1648 assert( pTable );
|
|
1649
|
|
1650 /* A positive nCol means the columns names for this view are
|
|
1651 ** already known.
|
|
1652 */
|
|
1653 if( pTable->nCol>0 ) return 0;
|
|
1654
|
|
1655 /* A negative nCol is a special marker meaning that we are currently
|
|
1656 ** trying to compute the column names. If we enter this routine with
|
|
1657 ** a negative nCol, it means two or more views form a loop, like this:
|
|
1658 **
|
|
1659 ** CREATE VIEW one AS SELECT * FROM two;
|
|
1660 ** CREATE VIEW two AS SELECT * FROM one;
|
|
1661 **
|
|
1662 ** Actually, this error is caught previously and so the following test
|
|
1663 ** should always fail. But we will leave it in place just to be safe.
|
|
1664 */
|
|
1665 if( pTable->nCol<0 ){
|
|
1666 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
|
|
1667 return 1;
|
|
1668 }
|
|
1669 assert( pTable->nCol>=0 );
|
|
1670
|
|
1671 /* If we get this far, it means we need to compute the table names.
|
|
1672 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
|
|
1673 ** "*" elements in the results set of the view and will assign cursors
|
|
1674 ** to the elements of the FROM clause. But we do not want these changes
|
|
1675 ** to be permanent. So the computation is done on a copy of the SELECT
|
|
1676 ** statement that defines the view.
|
|
1677 */
|
|
1678 assert( pTable->pSelect );
|
|
1679 pSel = sqlite3SelectDup(pTable->pSelect);
|
|
1680 if( pSel ){
|
|
1681 n = pParse->nTab;
|
|
1682 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
|
|
1683 pTable->nCol = -1;
|
|
1684 pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSel);
|
|
1685 pParse->nTab = n;
|
|
1686 if( pSelTab ){
|
|
1687 assert( pTable->aCol==0 );
|
|
1688 pTable->nCol = pSelTab->nCol;
|
|
1689 pTable->aCol = pSelTab->aCol;
|
|
1690 pSelTab->nCol = 0;
|
|
1691 pSelTab->aCol = 0;
|
|
1692 sqlite3DeleteTable(0, pSelTab);
|
|
1693 pTable->pSchema->flags |= DB_UnresetViews;
|
|
1694 }else{
|
|
1695 pTable->nCol = 0;
|
|
1696 nErr++;
|
|
1697 }
|
|
1698 sqlite3SelectDelete(pSel);
|
|
1699 } else {
|
|
1700 nErr++;
|
|
1701 }
|
|
1702 return nErr;
|
|
1703 }
|
|
1704 #endif /* SQLITE_OMIT_VIEW */
|
|
1705
|
|
1706 #ifndef SQLITE_OMIT_VIEW
|
|
1707 /*
|
|
1708 ** Clear the column names from every VIEW in database idx.
|
|
1709 */
|
|
1710 static void sqliteViewResetAll(sqlite3 *db, int idx){
|
|
1711 HashElem *i;
|
|
1712 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
|
|
1713 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
|
|
1714 Table *pTab = sqliteHashData(i);
|
|
1715 if( pTab->pSelect ){
|
|
1716 sqliteResetColumnNames(pTab);
|
|
1717 }
|
|
1718 }
|
|
1719 DbClearProperty(db, idx, DB_UnresetViews);
|
|
1720 }
|
|
1721 #else
|
|
1722 # define sqliteViewResetAll(A,B)
|
|
1723 #endif /* SQLITE_OMIT_VIEW */
|
|
1724
|
|
1725 /*
|
|
1726 ** This function is called by the VDBE to adjust the internal schema
|
|
1727 ** used by SQLite when the btree layer moves a table root page. The
|
|
1728 ** root-page of a table or index in database iDb has changed from iFrom
|
|
1729 ** to iTo.
|
|
1730 **
|
|
1731 ** Ticket #1728: The symbol table might still contain information
|
|
1732 ** on tables and/or indices that are the process of being deleted.
|
|
1733 ** If you are unlucky, one of those deleted indices or tables might
|
|
1734 ** have the same rootpage number as the real table or index that is
|
|
1735 ** being moved. So we cannot stop searching after the first match
|
|
1736 ** because the first match might be for one of the deleted indices
|
|
1737 ** or tables and not the table/index that is actually being moved.
|
|
1738 ** We must continue looping until all tables and indices with
|
|
1739 ** rootpage==iFrom have been converted to have a rootpage of iTo
|
|
1740 ** in order to be certain that we got the right one.
|
|
1741 */
|
|
1742 #ifndef SQLITE_OMIT_AUTOVACUUM
|
|
1743 void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
|
|
1744 HashElem *pElem;
|
|
1745 Hash *pHash;
|
|
1746
|
|
1747 pHash = &pDb->pSchema->tblHash;
|
|
1748 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
|
|
1749 Table *pTab = sqliteHashData(pElem);
|
|
1750 if( pTab->tnum==iFrom ){
|
|
1751 pTab->tnum = iTo;
|
|
1752 }
|
|
1753 }
|
|
1754 pHash = &pDb->pSchema->idxHash;
|
|
1755 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
|
|
1756 Index *pIdx = sqliteHashData(pElem);
|
|
1757 if( pIdx->tnum==iFrom ){
|
|
1758 pIdx->tnum = iTo;
|
|
1759 }
|
|
1760 }
|
|
1761 }
|
|
1762 #endif
|
|
1763
|
|
1764 /*
|
|
1765 ** Write code to erase the table with root-page iTable from database iDb.
|
|
1766 ** Also write code to modify the sqlite_master table and internal schema
|
|
1767 ** if a root-page of another table is moved by the btree-layer whilst
|
|
1768 ** erasing iTable (this can happen with an auto-vacuum database).
|
|
1769 */
|
|
1770 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
|
|
1771 Vdbe *v = sqlite3GetVdbe(pParse);
|
|
1772 sqlite3VdbeAddOp(v, OP_Destroy, iTable, iDb);
|
|
1773 #ifndef SQLITE_OMIT_AUTOVACUUM
|
|
1774 /* OP_Destroy pushes an integer onto the stack. If this integer
|
|
1775 ** is non-zero, then it is the root page number of a table moved to
|
|
1776 ** location iTable. The following code modifies the sqlite_master table to
|
|
1777 ** reflect this.
|
|
1778 **
|
|
1779 ** The "#0" in the SQL is a special constant that means whatever value
|
|
1780 ** is on the top of the stack. See sqlite3RegisterExpr().
|
|
1781 */
|
|
1782 sqlite3NestedParse(pParse,
|
|
1783 "UPDATE %Q.%s SET rootpage=%d WHERE #0 AND rootpage=#0",
|
|
1784 pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable);
|
|
1785 #endif
|
|
1786 }
|
|
1787
|
|
1788 /*
|
|
1789 ** Write VDBE code to erase table pTab and all associated indices on disk.
|
|
1790 ** Code to update the sqlite_master tables and internal schema definitions
|
|
1791 ** in case a root-page belonging to another table is moved by the btree layer
|
|
1792 ** is also added (this can happen with an auto-vacuum database).
|
|
1793 */
|
|
1794 static void destroyTable(Parse *pParse, Table *pTab){
|
|
1795 #ifdef SQLITE_OMIT_AUTOVACUUM
|
|
1796 Index *pIdx;
|
|
1797 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
|
1798 destroyRootPage(pParse, pTab->tnum, iDb);
|
|
1799 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
1800 destroyRootPage(pParse, pIdx->tnum, iDb);
|
|
1801 }
|
|
1802 #else
|
|
1803 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
|
|
1804 ** is not defined), then it is important to call OP_Destroy on the
|
|
1805 ** table and index root-pages in order, starting with the numerically
|
|
1806 ** largest root-page number. This guarantees that none of the root-pages
|
|
1807 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
|
|
1808 ** following were coded:
|
|
1809 **
|
|
1810 ** OP_Destroy 4 0
|
|
1811 ** ...
|
|
1812 ** OP_Destroy 5 0
|
|
1813 **
|
|
1814 ** and root page 5 happened to be the largest root-page number in the
|
|
1815 ** database, then root page 5 would be moved to page 4 by the
|
|
1816 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
|
|
1817 ** a free-list page.
|
|
1818 */
|
|
1819 int iTab = pTab->tnum;
|
|
1820 int iDestroyed = 0;
|
|
1821
|
|
1822 while( 1 ){
|
|
1823 Index *pIdx;
|
|
1824 int iLargest = 0;
|
|
1825
|
|
1826 if( iDestroyed==0 || iTab<iDestroyed ){
|
|
1827 iLargest = iTab;
|
|
1828 }
|
|
1829 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
1830 int iIdx = pIdx->tnum;
|
|
1831 assert( pIdx->pSchema==pTab->pSchema );
|
|
1832 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
|
|
1833 iLargest = iIdx;
|
|
1834 }
|
|
1835 }
|
|
1836 if( iLargest==0 ){
|
|
1837 return;
|
|
1838 }else{
|
|
1839 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
|
1840 destroyRootPage(pParse, iLargest, iDb);
|
|
1841 iDestroyed = iLargest;
|
|
1842 }
|
|
1843 }
|
|
1844 #endif
|
|
1845 }
|
|
1846
|
|
1847 /*
|
|
1848 ** This routine is called to do the work of a DROP TABLE statement.
|
|
1849 ** pName is the name of the table to be dropped.
|
|
1850 */
|
|
1851 void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
|
|
1852 Table *pTab;
|
|
1853 Vdbe *v;
|
|
1854 sqlite3 *db = pParse->db;
|
|
1855 int iDb;
|
|
1856
|
|
1857 if( pParse->nErr || sqlite3MallocFailed() ){
|
|
1858 goto exit_drop_table;
|
|
1859 }
|
|
1860 assert( pName->nSrc==1 );
|
|
1861 pTab = sqlite3LocateTable(pParse, pName->a[0].zName, pName->a[0].zDatabase);
|
|
1862
|
|
1863 if( pTab==0 ){
|
|
1864 if( noErr ){
|
|
1865 sqlite3ErrorClear(pParse);
|
|
1866 }
|
|
1867 goto exit_drop_table;
|
|
1868 }
|
|
1869 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
|
1870 assert( iDb>=0 && iDb<db->nDb );
|
|
1871 #ifndef SQLITE_OMIT_AUTHORIZATION
|
|
1872 {
|
|
1873 int code;
|
|
1874 const char *zTab = SCHEMA_TABLE(iDb);
|
|
1875 const char *zDb = db->aDb[iDb].zName;
|
|
1876 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
|
|
1877 goto exit_drop_table;
|
|
1878 }
|
|
1879 if( isView ){
|
|
1880 if( !OMIT_TEMPDB && iDb==1 ){
|
|
1881 code = SQLITE_DROP_TEMP_VIEW;
|
|
1882 }else{
|
|
1883 code = SQLITE_DROP_VIEW;
|
|
1884 }
|
|
1885 }else{
|
|
1886 if( !OMIT_TEMPDB && iDb==1 ){
|
|
1887 code = SQLITE_DROP_TEMP_TABLE;
|
|
1888 }else{
|
|
1889 code = SQLITE_DROP_TABLE;
|
|
1890 }
|
|
1891 }
|
|
1892 if( sqlite3AuthCheck(pParse, code, pTab->zName, 0, zDb) ){
|
|
1893 goto exit_drop_table;
|
|
1894 }
|
|
1895 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
|
|
1896 goto exit_drop_table;
|
|
1897 }
|
|
1898 }
|
|
1899 #endif
|
|
1900 if( pTab->readOnly || pTab==db->aDb[iDb].pSchema->pSeqTab ){
|
|
1901 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
|
|
1902 goto exit_drop_table;
|
|
1903 }
|
|
1904
|
|
1905 #ifndef SQLITE_OMIT_VIEW
|
|
1906 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
|
|
1907 ** on a table.
|
|
1908 */
|
|
1909 if( isView && pTab->pSelect==0 ){
|
|
1910 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
|
|
1911 goto exit_drop_table;
|
|
1912 }
|
|
1913 if( !isView && pTab->pSelect ){
|
|
1914 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
|
|
1915 goto exit_drop_table;
|
|
1916 }
|
|
1917 #endif
|
|
1918
|
|
1919 /* Generate code to remove the table from the master table
|
|
1920 ** on disk.
|
|
1921 */
|
|
1922 v = sqlite3GetVdbe(pParse);
|
|
1923 if( v ){
|
|
1924 Trigger *pTrigger;
|
|
1925 Db *pDb = &db->aDb[iDb];
|
|
1926 sqlite3BeginWriteOperation(pParse, 0, iDb);
|
|
1927
|
|
1928 /* Drop all triggers associated with the table being dropped. Code
|
|
1929 ** is generated to remove entries from sqlite_master and/or
|
|
1930 ** sqlite_temp_master if required.
|
|
1931 */
|
|
1932 pTrigger = pTab->pTrigger;
|
|
1933 while( pTrigger ){
|
|
1934 assert( pTrigger->pSchema==pTab->pSchema ||
|
|
1935 pTrigger->pSchema==db->aDb[1].pSchema );
|
|
1936 sqlite3DropTriggerPtr(pParse, pTrigger);
|
|
1937 pTrigger = pTrigger->pNext;
|
|
1938 }
|
|
1939
|
|
1940 #ifndef SQLITE_OMIT_AUTOINCREMENT
|
|
1941 /* Remove any entries of the sqlite_sequence table associated with
|
|
1942 ** the table being dropped. This is done before the table is dropped
|
|
1943 ** at the btree level, in case the sqlite_sequence table needs to
|
|
1944 ** move as a result of the drop (can happen in auto-vacuum mode).
|
|
1945 */
|
|
1946 if( pTab->autoInc ){
|
|
1947 sqlite3NestedParse(pParse,
|
|
1948 "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
|
|
1949 pDb->zName, pTab->zName
|
|
1950 );
|
|
1951 }
|
|
1952 #endif
|
|
1953
|
|
1954 /* Drop all SQLITE_MASTER table and index entries that refer to the
|
|
1955 ** table. The program name loops through the master table and deletes
|
|
1956 ** every row that refers to a table of the same name as the one being
|
|
1957 ** dropped. Triggers are handled seperately because a trigger can be
|
|
1958 ** created in the temp database that refers to a table in another
|
|
1959 ** database.
|
|
1960 */
|
|
1961 sqlite3NestedParse(pParse,
|
|
1962 "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
|
|
1963 pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
|
|
1964 if( !isView ){
|
|
1965 destroyTable(pParse, pTab);
|
|
1966 }
|
|
1967
|
|
1968 /* Remove the table entry from SQLite's internal schema and modify
|
|
1969 ** the schema cookie.
|
|
1970 */
|
|
1971 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
|
|
1972 sqlite3ChangeCookie(db, v, iDb);
|
|
1973 }
|
|
1974 sqliteViewResetAll(db, iDb);
|
|
1975
|
|
1976 exit_drop_table:
|
|
1977 sqlite3SrcListDelete(pName);
|
|
1978 }
|
|
1979
|
|
1980 /*
|
|
1981 ** This routine is called to create a new foreign key on the table
|
|
1982 ** currently under construction. pFromCol determines which columns
|
|
1983 ** in the current table point to the foreign key. If pFromCol==0 then
|
|
1984 ** connect the key to the last column inserted. pTo is the name of
|
|
1985 ** the table referred to. pToCol is a list of tables in the other
|
|
1986 ** pTo table that the foreign key points to. flags contains all
|
|
1987 ** information about the conflict resolution algorithms specified
|
|
1988 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
|
|
1989 **
|
|
1990 ** An FKey structure is created and added to the table currently
|
|
1991 ** under construction in the pParse->pNewTable field. The new FKey
|
|
1992 ** is not linked into db->aFKey at this point - that does not happen
|
|
1993 ** until sqlite3EndTable().
|
|
1994 **
|
|
1995 ** The foreign key is set for IMMEDIATE processing. A subsequent call
|
|
1996 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
|
|
1997 */
|
|
1998 void sqlite3CreateForeignKey(
|
|
1999 Parse *pParse, /* Parsing context */
|
|
2000 ExprList *pFromCol, /* Columns in this table that point to other table */
|
|
2001 Token *pTo, /* Name of the other table */
|
|
2002 ExprList *pToCol, /* Columns in the other table */
|
|
2003 int flags /* Conflict resolution algorithms. */
|
|
2004 ){
|
|
2005 #ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
2006 FKey *pFKey = 0;
|
|
2007 Table *p = pParse->pNewTable;
|
|
2008 int nByte;
|
|
2009 int i;
|
|
2010 int nCol;
|
|
2011 char *z;
|
|
2012
|
|
2013 assert( pTo!=0 );
|
|
2014 if( p==0 || pParse->nErr ) goto fk_end;
|
|
2015 if( pFromCol==0 ){
|
|
2016 int iCol = p->nCol-1;
|
|
2017 if( iCol<0 ) goto fk_end;
|
|
2018 if( pToCol && pToCol->nExpr!=1 ){
|
|
2019 sqlite3ErrorMsg(pParse, "foreign key on %s"
|
|
2020 " should reference only one column of table %T",
|
|
2021 p->aCol[iCol].zName, pTo);
|
|
2022 goto fk_end;
|
|
2023 }
|
|
2024 nCol = 1;
|
|
2025 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
|
|
2026 sqlite3ErrorMsg(pParse,
|
|
2027 "number of columns in foreign key does not match the number of "
|
|
2028 "columns in the referenced table");
|
|
2029 goto fk_end;
|
|
2030 }else{
|
|
2031 nCol = pFromCol->nExpr;
|
|
2032 }
|
|
2033 nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
|
|
2034 if( pToCol ){
|
|
2035 for(i=0; i<pToCol->nExpr; i++){
|
|
2036 nByte += strlen(pToCol->a[i].zName) + 1;
|
|
2037 }
|
|
2038 }
|
|
2039 pFKey = sqliteMalloc( nByte );
|
|
2040 if( pFKey==0 ) goto fk_end;
|
|
2041 pFKey->pFrom = p;
|
|
2042 pFKey->pNextFrom = p->pFKey;
|
|
2043 z = (char*)&pFKey[1];
|
|
2044 pFKey->aCol = (struct sColMap*)z;
|
|
2045 z += sizeof(struct sColMap)*nCol;
|
|
2046 pFKey->zTo = z;
|
|
2047 memcpy(z, pTo->z, pTo->n);
|
|
2048 z[pTo->n] = 0;
|
|
2049 z += pTo->n+1;
|
|
2050 pFKey->pNextTo = 0;
|
|
2051 pFKey->nCol = nCol;
|
|
2052 if( pFromCol==0 ){
|
|
2053 pFKey->aCol[0].iFrom = p->nCol-1;
|
|
2054 }else{
|
|
2055 for(i=0; i<nCol; i++){
|
|
2056 int j;
|
|
2057 for(j=0; j<p->nCol; j++){
|
|
2058 if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
|
|
2059 pFKey->aCol[i].iFrom = j;
|
|
2060 break;
|
|
2061 }
|
|
2062 }
|
|
2063 if( j>=p->nCol ){
|
|
2064 sqlite3ErrorMsg(pParse,
|
|
2065 "unknown column \"%s\" in foreign key definition",
|
|
2066 pFromCol->a[i].zName);
|
|
2067 goto fk_end;
|
|
2068 }
|
|
2069 }
|
|
2070 }
|
|
2071 if( pToCol ){
|
|
2072 for(i=0; i<nCol; i++){
|
|
2073 int n = strlen(pToCol->a[i].zName);
|
|
2074 pFKey->aCol[i].zCol = z;
|
|
2075 memcpy(z, pToCol->a[i].zName, n);
|
|
2076 z[n] = 0;
|
|
2077 z += n+1;
|
|
2078 }
|
|
2079 }
|
|
2080 pFKey->isDeferred = 0;
|
|
2081 pFKey->deleteConf = flags & 0xff;
|
|
2082 pFKey->updateConf = (flags >> 8 ) & 0xff;
|
|
2083 pFKey->insertConf = (flags >> 16 ) & 0xff;
|
|
2084
|
|
2085 /* Link the foreign key to the table as the last step.
|
|
2086 */
|
|
2087 p->pFKey = pFKey;
|
|
2088 pFKey = 0;
|
|
2089
|
|
2090 fk_end:
|
|
2091 sqliteFree(pFKey);
|
|
2092 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
|
|
2093 sqlite3ExprListDelete(pFromCol);
|
|
2094 sqlite3ExprListDelete(pToCol);
|
|
2095 }
|
|
2096
|
|
2097 /*
|
|
2098 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
|
|
2099 ** clause is seen as part of a foreign key definition. The isDeferred
|
|
2100 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
|
|
2101 ** The behavior of the most recently created foreign key is adjusted
|
|
2102 ** accordingly.
|
|
2103 */
|
|
2104 void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
|
|
2105 #ifndef SQLITE_OMIT_FOREIGN_KEY
|
|
2106 Table *pTab;
|
|
2107 FKey *pFKey;
|
|
2108 if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
|
|
2109 pFKey->isDeferred = isDeferred;
|
|
2110 #endif
|
|
2111 }
|
|
2112
|
|
2113 /*
|
|
2114 ** Generate code that will erase and refill index *pIdx. This is
|
|
2115 ** used to initialize a newly created index or to recompute the
|
|
2116 ** content of an index in response to a REINDEX command.
|
|
2117 **
|
|
2118 ** if memRootPage is not negative, it means that the index is newly
|
|
2119 ** created. The memory cell specified by memRootPage contains the
|
|
2120 ** root page number of the index. If memRootPage is negative, then
|
|
2121 ** the index already exists and must be cleared before being refilled and
|
|
2122 ** the root page number of the index is taken from pIndex->tnum.
|
|
2123 */
|
|
2124 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
|
|
2125 Table *pTab = pIndex->pTable; /* The table that is indexed */
|
|
2126 int iTab = pParse->nTab; /* Btree cursor used for pTab */
|
|
2127 int iIdx = pParse->nTab+1; /* Btree cursor used for pIndex */
|
|
2128 int addr1; /* Address of top of loop */
|
|
2129 int tnum; /* Root page of index */
|
|
2130 Vdbe *v; /* Generate code into this virtual machine */
|
|
2131 KeyInfo *pKey; /* KeyInfo for index */
|
|
2132 int iDb = sqlite3SchemaToIndex(pParse->db, pIndex->pSchema);
|
|
2133
|
|
2134 #ifndef SQLITE_OMIT_AUTHORIZATION
|
|
2135 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
|
|
2136 pParse->db->aDb[iDb].zName ) ){
|
|
2137 return;
|
|
2138 }
|
|
2139 #endif
|
|
2140
|
|
2141 /* Require a write-lock on the table to perform this operation */
|
|
2142 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
|
|
2143
|
|
2144 v = sqlite3GetVdbe(pParse);
|
|
2145 if( v==0 ) return;
|
|
2146 if( memRootPage>=0 ){
|
|
2147 sqlite3VdbeAddOp(v, OP_MemLoad, memRootPage, 0);
|
|
2148 tnum = 0;
|
|
2149 }else{
|
|
2150 tnum = pIndex->tnum;
|
|
2151 sqlite3VdbeAddOp(v, OP_Clear, tnum, iDb);
|
|
2152 }
|
|
2153 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
|
|
2154 pKey = sqlite3IndexKeyinfo(pParse, pIndex);
|
|
2155 sqlite3VdbeOp3(v, OP_OpenWrite, iIdx, tnum, (char *)pKey, P3_KEYINFO_HANDOFF);
|
|
2156 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
|
|
2157 addr1 = sqlite3VdbeAddOp(v, OP_Rewind, iTab, 0);
|
|
2158 sqlite3GenerateIndexKey(v, pIndex, iTab);
|
|
2159 if( pIndex->onError!=OE_None ){
|
|
2160 int curaddr = sqlite3VdbeCurrentAddr(v);
|
|
2161 int addr2 = curaddr+4;
|
|
2162 sqlite3VdbeChangeP2(v, curaddr-1, addr2);
|
|
2163 sqlite3VdbeAddOp(v, OP_Rowid, iTab, 0);
|
|
2164 sqlite3VdbeAddOp(v, OP_AddImm, 1, 0);
|
|
2165 sqlite3VdbeAddOp(v, OP_IsUnique, iIdx, addr2);
|
|
2166 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, OE_Abort,
|
|
2167 "indexed columns are not unique", P3_STATIC);
|
|
2168 assert( addr2==sqlite3VdbeCurrentAddr(v) );
|
|
2169 }
|
|
2170 sqlite3VdbeAddOp(v, OP_IdxInsert, iIdx, 0);
|
|
2171 sqlite3VdbeAddOp(v, OP_Next, iTab, addr1+1);
|
|
2172 sqlite3VdbeJumpHere(v, addr1);
|
|
2173 sqlite3VdbeAddOp(v, OP_Close, iTab, 0);
|
|
2174 sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
|
|
2175 }
|
|
2176
|
|
2177 /*
|
|
2178 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
|
|
2179 ** and pTblList is the name of the table that is to be indexed. Both will
|
|
2180 ** be NULL for a primary key or an index that is created to satisfy a
|
|
2181 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
|
|
2182 ** as the table to be indexed. pParse->pNewTable is a table that is
|
|
2183 ** currently being constructed by a CREATE TABLE statement.
|
|
2184 **
|
|
2185 ** pList is a list of columns to be indexed. pList will be NULL if this
|
|
2186 ** is a primary key or unique-constraint on the most recent column added
|
|
2187 ** to the table currently under construction.
|
|
2188 */
|
|
2189 void sqlite3CreateIndex(
|
|
2190 Parse *pParse, /* All information about this parse */
|
|
2191 Token *pName1, /* First part of index name. May be NULL */
|
|
2192 Token *pName2, /* Second part of index name. May be NULL */
|
|
2193 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
|
|
2194 ExprList *pList, /* A list of columns to be indexed */
|
|
2195 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
|
|
2196 Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
|
|
2197 Token *pEnd, /* The ")" that closes the CREATE INDEX statement */
|
|
2198 int sortOrder, /* Sort order of primary key when pList==NULL */
|
|
2199 int ifNotExist /* Omit error if index already exists */
|
|
2200 ){
|
|
2201 Table *pTab = 0; /* Table to be indexed */
|
|
2202 Index *pIndex = 0; /* The index to be created */
|
|
2203 char *zName = 0; /* Name of the index */
|
|
2204 int nName; /* Number of characters in zName */
|
|
2205 int i, j;
|
|
2206 Token nullId; /* Fake token for an empty ID list */
|
|
2207 DbFixer sFix; /* For assigning database names to pTable */
|
|
2208 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
|
|
2209 sqlite3 *db = pParse->db;
|
|
2210 Db *pDb; /* The specific table containing the indexed database */
|
|
2211 int iDb; /* Index of the database that is being written */
|
|
2212 Token *pName = 0; /* Unqualified name of the index to create */
|
|
2213 struct ExprList_item *pListItem; /* For looping over pList */
|
|
2214 int nCol;
|
|
2215 int nExtra = 0;
|
|
2216 char *zExtra;
|
|
2217
|
|
2218 if( pParse->nErr || sqlite3MallocFailed() ){
|
|
2219 goto exit_create_index;
|
|
2220 }
|
|
2221
|
|
2222 /*
|
|
2223 ** Find the table that is to be indexed. Return early if not found.
|
|
2224 */
|
|
2225 if( pTblName!=0 ){
|
|
2226
|
|
2227 /* Use the two-part index name to determine the database
|
|
2228 ** to search for the table. 'Fix' the table name to this db
|
|
2229 ** before looking up the table.
|
|
2230 */
|
|
2231 assert( pName1 && pName2 );
|
|
2232 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
|
|
2233 if( iDb<0 ) goto exit_create_index;
|
|
2234
|
|
2235 #ifndef SQLITE_OMIT_TEMPDB
|
|
2236 /* If the index name was unqualified, check if the the table
|
|
2237 ** is a temp table. If so, set the database to 1.
|
|
2238 */
|
|
2239 pTab = sqlite3SrcListLookup(pParse, pTblName);
|
|
2240 if( pName2 && pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
|
|
2241 iDb = 1;
|
|
2242 }
|
|
2243 #endif
|
|
2244
|
|
2245 if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
|
|
2246 sqlite3FixSrcList(&sFix, pTblName)
|
|
2247 ){
|
|
2248 /* Because the parser constructs pTblName from a single identifier,
|
|
2249 ** sqlite3FixSrcList can never fail. */
|
|
2250 assert(0);
|
|
2251 }
|
|
2252 pTab = sqlite3LocateTable(pParse, pTblName->a[0].zName,
|
|
2253 pTblName->a[0].zDatabase);
|
|
2254 if( !pTab ) goto exit_create_index;
|
|
2255 assert( db->aDb[iDb].pSchema==pTab->pSchema );
|
|
2256 }else{
|
|
2257 assert( pName==0 );
|
|
2258 pTab = pParse->pNewTable;
|
|
2259 if( !pTab ) goto exit_create_index;
|
|
2260 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
|
|
2261 }
|
|
2262 pDb = &db->aDb[iDb];
|
|
2263
|
|
2264 if( pTab==0 || pParse->nErr ) goto exit_create_index;
|
|
2265 if( pTab->readOnly ){
|
|
2266 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
|
|
2267 goto exit_create_index;
|
|
2268 }
|
|
2269 #ifndef SQLITE_OMIT_VIEW
|
|
2270 if( pTab->pSelect ){
|
|
2271 sqlite3ErrorMsg(pParse, "views may not be indexed");
|
|
2272 goto exit_create_index;
|
|
2273 }
|
|
2274 #endif
|
|
2275
|
|
2276 /*
|
|
2277 ** Find the name of the index. Make sure there is not already another
|
|
2278 ** index or table with the same name.
|
|
2279 **
|
|
2280 ** Exception: If we are reading the names of permanent indices from the
|
|
2281 ** sqlite_master table (because some other process changed the schema) and
|
|
2282 ** one of the index names collides with the name of a temporary table or
|
|
2283 ** index, then we will continue to process this index.
|
|
2284 **
|
|
2285 ** If pName==0 it means that we are
|
|
2286 ** dealing with a primary key or UNIQUE constraint. We have to invent our
|
|
2287 ** own name.
|
|
2288 */
|
|
2289 if( pName ){
|
|
2290 zName = sqlite3NameFromToken(pName);
|
|
2291 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
|
|
2292 if( zName==0 ) goto exit_create_index;
|
|
2293 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
|
|
2294 goto exit_create_index;
|
|
2295 }
|
|
2296 if( !db->init.busy ){
|
|
2297 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ) goto exit_create_index;
|
|
2298 if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
|
|
2299 if( !ifNotExist ){
|
|
2300 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
|
|
2301 }
|
|
2302 goto exit_create_index;
|
|
2303 }
|
|
2304 if( sqlite3FindTable(db, zName, 0)!=0 ){
|
|
2305 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
|
|
2306 goto exit_create_index;
|
|
2307 }
|
|
2308 }
|
|
2309 }else{
|
|
2310 char zBuf[30];
|
|
2311 int n;
|
|
2312 Index *pLoop;
|
|
2313 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
|
|
2314 sprintf(zBuf,"_%d",n);
|
|
2315 zName = 0;
|
|
2316 sqlite3SetString(&zName, "sqlite_autoindex_", pTab->zName, zBuf, (char*)0);
|
|
2317 if( zName==0 ) goto exit_create_index;
|
|
2318 }
|
|
2319
|
|
2320 /* Check for authorization to create an index.
|
|
2321 */
|
|
2322 #ifndef SQLITE_OMIT_AUTHORIZATION
|
|
2323 {
|
|
2324 const char *zDb = pDb->zName;
|
|
2325 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
|
|
2326 goto exit_create_index;
|
|
2327 }
|
|
2328 i = SQLITE_CREATE_INDEX;
|
|
2329 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
|
|
2330 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
|
|
2331 goto exit_create_index;
|
|
2332 }
|
|
2333 }
|
|
2334 #endif
|
|
2335
|
|
2336 /* If pList==0, it means this routine was called to make a primary
|
|
2337 ** key out of the last column added to the table under construction.
|
|
2338 ** So create a fake list to simulate this.
|
|
2339 */
|
|
2340 if( pList==0 ){
|
|
2341 nullId.z = (u8*)pTab->aCol[pTab->nCol-1].zName;
|
|
2342 nullId.n = strlen((char*)nullId.z);
|
|
2343 pList = sqlite3ExprListAppend(0, 0, &nullId);
|
|
2344 if( pList==0 ) goto exit_create_index;
|
|
2345 pList->a[0].sortOrder = sortOrder;
|
|
2346 }
|
|
2347
|
|
2348 /* Figure out how many bytes of space are required to store explicitly
|
|
2349 ** specified collation sequence names.
|
|
2350 */
|
|
2351 for(i=0; i<pList->nExpr; i++){
|
|
2352 Expr *pExpr = pList->a[i].pExpr;
|
|
2353 if( pExpr ){
|
|
2354 nExtra += (1 + strlen(pExpr->pColl->zName));
|
|
2355 }
|
|
2356 }
|
|
2357
|
|
2358 /*
|
|
2359 ** Allocate the index structure.
|
|
2360 */
|
|
2361 nName = strlen(zName);
|
|
2362 nCol = pList->nExpr;
|
|
2363 pIndex = sqliteMalloc(
|
|
2364 sizeof(Index) + /* Index structure */
|
|
2365 sizeof(int)*nCol + /* Index.aiColumn */
|
|
2366 sizeof(int)*(nCol+1) + /* Index.aiRowEst */
|
|
2367 sizeof(char *)*nCol + /* Index.azColl */
|
|
2368 sizeof(u8)*nCol + /* Index.aSortOrder */
|
|
2369 nName + 1 + /* Index.zName */
|
|
2370 nExtra /* Collation sequence names */
|
|
2371 );
|
|
2372 if( sqlite3MallocFailed() ) goto exit_create_index;
|
|
2373 pIndex->azColl = (char**)(&pIndex[1]);
|
|
2374 pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
|
|
2375 pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
|
|
2376 pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
|
|
2377 pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
|
|
2378 zExtra = (char *)(&pIndex->zName[nName+1]);
|
|
2379 strcpy(pIndex->zName, zName);
|
|
2380 pIndex->pTable = pTab;
|
|
2381 pIndex->nColumn = pList->nExpr;
|
|
2382 pIndex->onError = onError;
|
|
2383 pIndex->autoIndex = pName==0;
|
|
2384 pIndex->pSchema = db->aDb[iDb].pSchema;
|
|
2385
|
|
2386 /* Check to see if we should honor DESC requests on index columns
|
|
2387 */
|
|
2388 if( pDb->pSchema->file_format>=4 ){
|
|
2389 sortOrderMask = -1; /* Honor DESC */
|
|
2390 }else{
|
|
2391 sortOrderMask = 0; /* Ignore DESC */
|
|
2392 }
|
|
2393
|
|
2394 /* Scan the names of the columns of the table to be indexed and
|
|
2395 ** load the column indices into the Index structure. Report an error
|
|
2396 ** if any column is not found.
|
|
2397 */
|
|
2398 for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
|
|
2399 const char *zColName = pListItem->zName;
|
|
2400 Column *pTabCol;
|
|
2401 int requestedSortOrder;
|
|
2402 char *zColl; /* Collation sequence */
|
|
2403
|
|
2404 for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
|
|
2405 if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
|
|
2406 }
|
|
2407 if( j>=pTab->nCol ){
|
|
2408 sqlite3ErrorMsg(pParse, "table %s has no column named %s",
|
|
2409 pTab->zName, zColName);
|
|
2410 goto exit_create_index;
|
|
2411 }
|
|
2412 pIndex->aiColumn[i] = j;
|
|
2413 if( pListItem->pExpr ){
|
|
2414 assert( pListItem->pExpr->pColl );
|
|
2415 zColl = zExtra;
|
|
2416 strcpy(zExtra, pListItem->pExpr->pColl->zName);
|
|
2417 zExtra += (strlen(zColl) + 1);
|
|
2418 }else{
|
|
2419 zColl = pTab->aCol[j].zColl;
|
|
2420 if( !zColl ){
|
|
2421 zColl = db->pDfltColl->zName;
|
|
2422 }
|
|
2423 }
|
|
2424 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl, -1) ){
|
|
2425 goto exit_create_index;
|
|
2426 }
|
|
2427 pIndex->azColl[i] = zColl;
|
|
2428 requestedSortOrder = pListItem->sortOrder & sortOrderMask;
|
|
2429 pIndex->aSortOrder[i] = requestedSortOrder;
|
|
2430 }
|
|
2431 sqlite3DefaultRowEst(pIndex);
|
|
2432
|
|
2433 if( pTab==pParse->pNewTable ){
|
|
2434 /* This routine has been called to create an automatic index as a
|
|
2435 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
|
|
2436 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
|
|
2437 ** i.e. one of:
|
|
2438 **
|
|
2439 ** CREATE TABLE t(x PRIMARY KEY, y);
|
|
2440 ** CREATE TABLE t(x, y, UNIQUE(x, y));
|
|
2441 **
|
|
2442 ** Either way, check to see if the table already has such an index. If
|
|
2443 ** so, don't bother creating this one. This only applies to
|
|
2444 ** automatically created indices. Users can do as they wish with
|
|
2445 ** explicit indices.
|
|
2446 */
|
|
2447 Index *pIdx;
|
|
2448 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
|
|
2449 int k;
|
|
2450 assert( pIdx->onError!=OE_None );
|
|
2451 assert( pIdx->autoIndex );
|
|
2452 assert( pIndex->onError!=OE_None );
|
|
2453
|
|
2454 if( pIdx->nColumn!=pIndex->nColumn ) continue;
|
|
2455 for(k=0; k<pIdx->nColumn; k++){
|
|
2456 const char *z1 = pIdx->azColl[k];
|
|
2457 const char *z2 = pIndex->azColl[k];
|
|
2458 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
|
|
2459 if( pIdx->aSortOrder[k]!=pIndex->aSortOrder[k] ) break;
|
|
2460 if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
|
|
2461 }
|
|
2462 if( k==pIdx->nColumn ){
|
|
2463 if( pIdx->onError!=pIndex->onError ){
|
|
2464 /* This constraint creates the same index as a previous
|
|
2465 ** constraint specified somewhere in the CREATE TABLE statement.
|
|
2466 ** However the ON CONFLICT clauses are different. If both this
|
|
2467 ** constraint and the previous equivalent constraint have explicit
|
|
2468 ** ON CONFLICT clauses this is an error. Otherwise, use the
|
|
2469 ** explicitly specified behaviour for the index.
|
|
2470 */
|
|
2471 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
|
|
2472 sqlite3ErrorMsg(pParse,
|
|
2473 "conflicting ON CONFLICT clauses specified", 0);
|
|
2474 }
|
|
2475 if( pIdx->onError==OE_Default ){
|
|
2476 pIdx->onError = pIndex->onError;
|
|
2477 }
|
|
2478 }
|
|
2479 goto exit_create_index;
|
|
2480 }
|
|
2481 }
|
|
2482 }
|
|
2483
|
|
2484 /* Link the new Index structure to its table and to the other
|
|
2485 ** in-memory database structures.
|
|
2486 */
|
|
2487 if( db->init.busy ){
|
|
2488 Index *p;
|
|
2489 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
|
|
2490 pIndex->zName, strlen(pIndex->zName)+1, pIndex);
|
|
2491 if( p ){
|
|
2492 assert( p==pIndex ); /* Malloc must have failed */
|
|
2493 goto exit_create_index;
|
|
2494 }
|
|
2495 db->flags |= SQLITE_InternChanges;
|
|
2496 if( pTblName!=0 ){
|
|
2497 pIndex->tnum = db->init.newTnum;
|
|
2498 }
|
|
2499 }
|
|
2500
|
|
2501 /* If the db->init.busy is 0 then create the index on disk. This
|
|
2502 ** involves writing the index into the master table and filling in the
|
|
2503 ** index with the current table contents.
|
|
2504 **
|
|
2505 ** The db->init.busy is 0 when the user first enters a CREATE INDEX
|
|
2506 ** command. db->init.busy is 1 when a database is opened and
|
|
2507 ** CREATE INDEX statements are read out of the master table. In
|
|
2508 ** the latter case the index already exists on disk, which is why
|
|
2509 ** we don't want to recreate it.
|
|
2510 **
|
|
2511 ** If pTblName==0 it means this index is generated as a primary key
|
|
2512 ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
|
|
2513 ** has just been created, it contains no data and the index initialization
|
|
2514 ** step can be skipped.
|
|
2515 */
|
|
2516 else if( db->init.busy==0 ){
|
|
2517 Vdbe *v;
|
|
2518 char *zStmt;
|
|
2519 int iMem = pParse->nMem++;
|
|
2520
|
|
2521 v = sqlite3GetVdbe(pParse);
|
|
2522 if( v==0 ) goto exit_create_index;
|
|
2523
|
|
2524
|
|
2525 /* Create the rootpage for the index
|
|
2526 */
|
|
2527 sqlite3BeginWriteOperation(pParse, 1, iDb);
|
|
2528 sqlite3VdbeAddOp(v, OP_CreateIndex, iDb, 0);
|
|
2529 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
|
|
2530
|
|
2531 /* Gather the complete text of the CREATE INDEX statement into
|
|
2532 ** the zStmt variable
|
|
2533 */
|
|
2534 if( pStart && pEnd ){
|
|
2535 /* A named index with an explicit CREATE INDEX statement */
|
|
2536 zStmt = sqlite3MPrintf("CREATE%s INDEX %.*s",
|
|
2537 onError==OE_None ? "" : " UNIQUE",
|
|
2538 pEnd->z - pName->z + 1,
|
|
2539 pName->z);
|
|
2540 }else{
|
|
2541 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
|
|
2542 /* zStmt = sqlite3MPrintf(""); */
|
|
2543 zStmt = 0;
|
|
2544 }
|
|
2545
|
|
2546 /* Add an entry in sqlite_master for this index
|
|
2547 */
|
|
2548 sqlite3NestedParse(pParse,
|
|
2549 "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#0,%Q);",
|
|
2550 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
|
|
2551 pIndex->zName,
|
|
2552 pTab->zName,
|
|
2553 zStmt
|
|
2554 );
|
|
2555 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
|
|
2556 sqliteFree(zStmt);
|
|
2557
|
|
2558 /* Fill the index with data and reparse the schema. Code an OP_Expire
|
|
2559 ** to invalidate all pre-compiled statements.
|
|
2560 */
|
|
2561 if( pTblName ){
|
|
2562 sqlite3RefillIndex(pParse, pIndex, iMem);
|
|
2563 sqlite3ChangeCookie(db, v, iDb);
|
|
2564 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0,
|
|
2565 sqlite3MPrintf("name='%q'", pIndex->zName), P3_DYNAMIC);
|
|
2566 sqlite3VdbeAddOp(v, OP_Expire, 0, 0);
|
|
2567 }
|
|
2568 }
|
|
2569
|
|
2570 /* When adding an index to the list of indices for a table, make
|
|
2571 ** sure all indices labeled OE_Replace come after all those labeled
|
|
2572 ** OE_Ignore. This is necessary for the correct operation of UPDATE
|
|
2573 ** and INSERT.
|
|
2574 */
|
|
2575 if( db->init.busy || pTblName==0 ){
|
|
2576 if( onError!=OE_Replace || pTab->pIndex==0
|
|
2577 || pTab->pIndex->onError==OE_Replace){
|
|
2578 pIndex->pNext = pTab->pIndex;
|
|
2579 pTab->pIndex = pIndex;
|
|
2580 }else{
|
|
2581 Index *pOther = pTab->pIndex;
|
|
2582 while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
|
|
2583 pOther = pOther->pNext;
|
|
2584 }
|
|
2585 pIndex->pNext = pOther->pNext;
|
|
2586 pOther->pNext = pIndex;
|
|
2587 }
|
|
2588 pIndex = 0;
|
|
2589 }
|
|
2590
|
|
2591 /* Clean up before exiting */
|
|
2592 exit_create_index:
|
|
2593 if( pIndex ){
|
|
2594 freeIndex(pIndex);
|
|
2595 }
|
|
2596 sqlite3ExprListDelete(pList);
|
|
2597 sqlite3SrcListDelete(pTblName);
|
|
2598 sqliteFree(zName);
|
|
2599 return;
|
|
2600 }
|
|
2601
|
|
2602 /*
|
|
2603 ** Generate code to make sure the file format number is at least minFormat.
|
|
2604 ** The generated code will increase the file format number if necessary.
|
|
2605 */
|
|
2606 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
|
|
2607 Vdbe *v;
|
|
2608 v = sqlite3GetVdbe(pParse);
|
|
2609 if( v ){
|
|
2610 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
|
|
2611 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
|
|
2612 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
|
|
2613 sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
|
|
2614 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
|
|
2615 }
|
|
2616 }
|
|
2617
|
|
2618 /*
|
|
2619 ** Fill the Index.aiRowEst[] array with default information - information
|
|
2620 ** to be used when we have not run the ANALYZE command.
|
|
2621 **
|
|
2622 ** aiRowEst[0] is suppose to contain the number of elements in the index.
|
|
2623 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
|
|
2624 ** number of rows in the table that match any particular value of the
|
|
2625 ** first column of the index. aiRowEst[2] is an estimate of the number
|
|
2626 ** of rows that match any particular combiniation of the first 2 columns
|
|
2627 ** of the index. And so forth. It must always be the case that
|
|
2628 *
|
|
2629 ** aiRowEst[N]<=aiRowEst[N-1]
|
|
2630 ** aiRowEst[N]>=1
|
|
2631 **
|
|
2632 ** Apart from that, we have little to go on besides intuition as to
|
|
2633 ** how aiRowEst[] should be initialized. The numbers generated here
|
|
2634 ** are based on typical values found in actual indices.
|
|
2635 */
|
|
2636 void sqlite3DefaultRowEst(Index *pIdx){
|
|
2637 unsigned *a = pIdx->aiRowEst;
|
|
2638 int i;
|
|
2639 assert( a!=0 );
|
|
2640 a[0] = 1000000;
|
|
2641 for(i=pIdx->nColumn; i>=5; i--){
|
|
2642 a[i] = 5;
|
|
2643 }
|
|
2644 while( i>=1 ){
|
|
2645 a[i] = 11 - i;
|
|
2646 i--;
|
|
2647 }
|
|
2648 if( pIdx->onError!=OE_None ){
|
|
2649 a[pIdx->nColumn] = 1;
|
|
2650 }
|
|
2651 }
|
|
2652
|
|
2653 /*
|
|
2654 ** This routine will drop an existing named index. This routine
|
|
2655 ** implements the DROP INDEX statement.
|
|
2656 */
|
|
2657 void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
|
|
2658 Index *pIndex;
|
|
2659 Vdbe *v;
|
|
2660 sqlite3 *db = pParse->db;
|
|
2661 int iDb;
|
|
2662
|
|
2663 if( pParse->nErr || sqlite3MallocFailed() ){
|
|
2664 goto exit_drop_index;
|
|
2665 }
|
|
2666 assert( pName->nSrc==1 );
|
|
2667 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
|
|
2668 goto exit_drop_index;
|
|
2669 }
|
|
2670 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
|
|
2671 if( pIndex==0 ){
|
|
2672 if( !ifExists ){
|
|
2673 sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
|
|
2674 }
|
|
2675 pParse->checkSchema = 1;
|
|
2676 goto exit_drop_index;
|
|
2677 }
|
|
2678 if( pIndex->autoIndex ){
|
|
2679 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
|
|
2680 "or PRIMARY KEY constraint cannot be dropped", 0);
|
|
2681 goto exit_drop_index;
|
|
2682 }
|
|
2683 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
|
|
2684 #ifndef SQLITE_OMIT_AUTHORIZATION
|
|
2685 {
|
|
2686 int code = SQLITE_DROP_INDEX;
|
|
2687 Table *pTab = pIndex->pTable;
|
|
2688 const char *zDb = db->aDb[iDb].zName;
|
|
2689 const char *zTab = SCHEMA_TABLE(iDb);
|
|
2690 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
|
|
2691 goto exit_drop_index;
|
|
2692 }
|
|
2693 if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
|
|
2694 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
|
|
2695 goto exit_drop_index;
|
|
2696 }
|
|
2697 }
|
|
2698 #endif
|
|
2699
|
|
2700 /* Generate code to remove the index and from the master table */
|
|
2701 v = sqlite3GetVdbe(pParse);
|
|
2702 if( v ){
|
|
2703 sqlite3NestedParse(pParse,
|
|
2704 "DELETE FROM %Q.%s WHERE name=%Q",
|
|
2705 db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
|
|
2706 pIndex->zName
|
|
2707 );
|
|
2708 sqlite3ChangeCookie(db, v, iDb);
|
|
2709 destroyRootPage(pParse, pIndex->tnum, iDb);
|
|
2710 sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0);
|
|
2711 }
|
|
2712
|
|
2713 exit_drop_index:
|
|
2714 sqlite3SrcListDelete(pName);
|
|
2715 }
|
|
2716
|
|
2717 /*
|
|
2718 ** ppArray points into a structure where there is an array pointer
|
|
2719 ** followed by two integers. The first integer is the
|
|
2720 ** number of elements in the structure array. The second integer
|
|
2721 ** is the number of allocated slots in the array.
|
|
2722 **
|
|
2723 ** In other words, the structure looks something like this:
|
|
2724 **
|
|
2725 ** struct Example1 {
|
|
2726 ** struct subElem *aEntry;
|
|
2727 ** int nEntry;
|
|
2728 ** int nAlloc;
|
|
2729 ** }
|
|
2730 **
|
|
2731 ** The pnEntry parameter points to the equivalent of Example1.nEntry.
|
|
2732 **
|
|
2733 ** This routine allocates a new slot in the array, zeros it out,
|
|
2734 ** and returns its index. If malloc fails a negative number is returned.
|
|
2735 **
|
|
2736 ** szEntry is the sizeof of a single array entry. initSize is the
|
|
2737 ** number of array entries allocated on the initial allocation.
|
|
2738 */
|
|
2739 int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){
|
|
2740 char *p;
|
|
2741 int *an = (int*)&ppArray[1];
|
|
2742 if( an[0]>=an[1] ){
|
|
2743 void *pNew;
|
|
2744 int newSize;
|
|
2745 newSize = an[1]*2 + initSize;
|
|
2746 pNew = sqliteRealloc(*ppArray, newSize*szEntry);
|
|
2747 if( pNew==0 ){
|
|
2748 return -1;
|
|
2749 }
|
|
2750 an[1] = newSize;
|
|
2751 *ppArray = pNew;
|
|
2752 }
|
|
2753 p = *ppArray;
|
|
2754 memset(&p[an[0]*szEntry], 0, szEntry);
|
|
2755 return an[0]++;
|
|
2756 }
|
|
2757
|
|
2758 /*
|
|
2759 ** Append a new element to the given IdList. Create a new IdList if
|
|
2760 ** need be.
|
|
2761 **
|
|
2762 ** A new IdList is returned, or NULL if malloc() fails.
|
|
2763 */
|
|
2764 IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
|
|
2765 int i;
|
|
2766 if( pList==0 ){
|
|
2767 pList = sqliteMalloc( sizeof(IdList) );
|
|
2768 if( pList==0 ) return 0;
|
|
2769 pList->nAlloc = 0;
|
|
2770 }
|
|
2771 i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5);
|
|
2772 if( i<0 ){
|
|
2773 sqlite3IdListDelete(pList);
|
|
2774 return 0;
|
|
2775 }
|
|
2776 pList->a[i].zName = sqlite3NameFromToken(pToken);
|
|
2777 return pList;
|
|
2778 }
|
|
2779
|
|
2780 /*
|
|
2781 ** Delete an IdList.
|
|
2782 */
|
|
2783 void sqlite3IdListDelete(IdList *pList){
|
|
2784 int i;
|
|
2785 if( pList==0 ) return;
|
|
2786 for(i=0; i<pList->nId; i++){
|
|
2787 sqliteFree(pList->a[i].zName);
|
|
2788 }
|
|
2789 sqliteFree(pList->a);
|
|
2790 sqliteFree(pList);
|
|
2791 }
|
|
2792
|
|
2793 /*
|
|
2794 ** Return the index in pList of the identifier named zId. Return -1
|
|
2795 ** if not found.
|
|
2796 */
|
|
2797 int sqlite3IdListIndex(IdList *pList, const char *zName){
|
|
2798 int i;
|
|
2799 if( pList==0 ) return -1;
|
|
2800 for(i=0; i<pList->nId; i++){
|
|
2801 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
|
|
2802 }
|
|
2803 return -1;
|
|
2804 }
|
|
2805
|
|
2806 /*
|
|
2807 ** Append a new table name to the given SrcList. Create a new SrcList if
|
|
2808 ** need be. A new entry is created in the SrcList even if pToken is NULL.
|
|
2809 **
|
|
2810 ** A new SrcList is returned, or NULL if malloc() fails.
|
|
2811 **
|
|
2812 ** If pDatabase is not null, it means that the table has an optional
|
|
2813 ** database name prefix. Like this: "database.table". The pDatabase
|
|
2814 ** points to the table name and the pTable points to the database name.
|
|
2815 ** The SrcList.a[].zName field is filled with the table name which might
|
|
2816 ** come from pTable (if pDatabase is NULL) or from pDatabase.
|
|
2817 ** SrcList.a[].zDatabase is filled with the database name from pTable,
|
|
2818 ** or with NULL if no database is specified.
|
|
2819 **
|
|
2820 ** In other words, if call like this:
|
|
2821 **
|
|
2822 ** sqlite3SrcListAppend(A,B,0);
|
|
2823 **
|
|
2824 ** Then B is a table name and the database name is unspecified. If called
|
|
2825 ** like this:
|
|
2826 **
|
|
2827 ** sqlite3SrcListAppend(A,B,C);
|
|
2828 **
|
|
2829 ** Then C is the table name and B is the database name.
|
|
2830 */
|
|
2831 SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
|
|
2832 struct SrcList_item *pItem;
|
|
2833 if( pList==0 ){
|
|
2834 pList = sqliteMalloc( sizeof(SrcList) );
|
|
2835 if( pList==0 ) return 0;
|
|
2836 pList->nAlloc = 1;
|
|
2837 }
|
|
2838 if( pList->nSrc>=pList->nAlloc ){
|
|
2839 SrcList *pNew;
|
|
2840 pList->nAlloc *= 2;
|
|
2841 pNew = sqliteRealloc(pList,
|
|
2842 sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
|
|
2843 if( pNew==0 ){
|
|
2844 sqlite3SrcListDelete(pList);
|
|
2845 return 0;
|
|
2846 }
|
|
2847 pList = pNew;
|
|
2848 }
|
|
2849 pItem = &pList->a[pList->nSrc];
|
|
2850 memset(pItem, 0, sizeof(pList->a[0]));
|
|
2851 if( pDatabase && pDatabase->z==0 ){
|
|
2852 pDatabase = 0;
|
|
2853 }
|
|
2854 if( pDatabase && pTable ){
|
|
2855 Token *pTemp = pDatabase;
|
|
2856 pDatabase = pTable;
|
|
2857 pTable = pTemp;
|
|
2858 }
|
|
2859 pItem->zName = sqlite3NameFromToken(pTable);
|
|
2860 pItem->zDatabase = sqlite3NameFromToken(pDatabase);
|
|
2861 pItem->iCursor = -1;
|
|
2862 pItem->isPopulated = 0;
|
|
2863 pList->nSrc++;
|
|
2864 return pList;
|
|
2865 }
|
|
2866
|
|
2867 /*
|
|
2868 ** Assign cursors to all tables in a SrcList
|
|
2869 */
|
|
2870 void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
|
|
2871 int i;
|
|
2872 struct SrcList_item *pItem;
|
|
2873 assert(pList || sqlite3MallocFailed() );
|
|
2874 if( pList ){
|
|
2875 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
|
|
2876 if( pItem->iCursor>=0 ) break;
|
|
2877 pItem->iCursor = pParse->nTab++;
|
|
2878 if( pItem->pSelect ){
|
|
2879 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
|
|
2880 }
|
|
2881 }
|
|
2882 }
|
|
2883 }
|
|
2884
|
|
2885 /*
|
|
2886 ** Add an alias to the last identifier on the given identifier list.
|
|
2887 */
|
|
2888 void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){
|
|
2889 if( pList && pList->nSrc>0 ){
|
|
2890 pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken);
|
|
2891 }
|
|
2892 }
|
|
2893
|
|
2894 /*
|
|
2895 ** Delete an entire SrcList including all its substructure.
|
|
2896 */
|
|
2897 void sqlite3SrcListDelete(SrcList *pList){
|
|
2898 int i;
|
|
2899 struct SrcList_item *pItem;
|
|
2900 if( pList==0 ) return;
|
|
2901 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
|
|
2902 sqliteFree(pItem->zDatabase);
|
|
2903 sqliteFree(pItem->zName);
|
|
2904 sqliteFree(pItem->zAlias);
|
|
2905 sqlite3DeleteTable(0, pItem->pTab);
|
|
2906 sqlite3SelectDelete(pItem->pSelect);
|
|
2907 sqlite3ExprDelete(pItem->pOn);
|
|
2908 sqlite3IdListDelete(pItem->pUsing);
|
|
2909 }
|
|
2910 sqliteFree(pList);
|
|
2911 }
|
|
2912
|
|
2913 /*
|
|
2914 ** Begin a transaction
|
|
2915 */
|
|
2916 void sqlite3BeginTransaction(Parse *pParse, int type){
|
|
2917 sqlite3 *db;
|
|
2918 Vdbe *v;
|
|
2919 int i;
|
|
2920
|
|
2921 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
|
|
2922 if( pParse->nErr || sqlite3MallocFailed() ) return;
|
|
2923 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
|
|
2924
|
|
2925 v = sqlite3GetVdbe(pParse);
|
|
2926 if( !v ) return;
|
|
2927 if( type!=TK_DEFERRED ){
|
|
2928 for(i=0; i<db->nDb; i++){
|
|
2929 sqlite3VdbeAddOp(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
|
|
2930 }
|
|
2931 }
|
|
2932 sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
|
|
2933 }
|
|
2934
|
|
2935 /*
|
|
2936 ** Commit a transaction
|
|
2937 */
|
|
2938 void sqlite3CommitTransaction(Parse *pParse){
|
|
2939 sqlite3 *db;
|
|
2940 Vdbe *v;
|
|
2941
|
|
2942 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
|
|
2943 if( pParse->nErr || sqlite3MallocFailed() ) return;
|
|
2944 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
|
|
2945
|
|
2946 v = sqlite3GetVdbe(pParse);
|
|
2947 if( v ){
|
|
2948 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
|
|
2949 }
|
|
2950 }
|
|
2951
|
|
2952 /*
|
|
2953 ** Rollback a transaction
|
|
2954 */
|
|
2955 void sqlite3RollbackTransaction(Parse *pParse){
|
|
2956 sqlite3 *db;
|
|
2957 Vdbe *v;
|
|
2958
|
|
2959 if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
|
|
2960 if( pParse->nErr || sqlite3MallocFailed() ) return;
|
|
2961 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
|
|
2962
|
|
2963 v = sqlite3GetVdbe(pParse);
|
|
2964 if( v ){
|
|
2965 sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
|
|
2966 }
|
|
2967 }
|
|
2968
|
|
2969 /*
|
|
2970 ** Make sure the TEMP database is open and available for use. Return
|
|
2971 ** the number of errors. Leave any error messages in the pParse structure.
|
|
2972 */
|
|
2973 int sqlite3OpenTempDatabase(Parse *pParse){
|
|
2974 sqlite3 *db = pParse->db;
|
|
2975 if( db->aDb[1].pBt==0 && !pParse->explain ){
|
|
2976 int rc = sqlite3BtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
|
|
2977 if( rc!=SQLITE_OK ){
|
|
2978 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
|
|
2979 "file for storing temporary tables");
|
|
2980 pParse->rc = rc;
|
|
2981 return 1;
|
|
2982 }
|
|
2983 if( db->flags & !db->autoCommit ){
|
|
2984 rc = sqlite3BtreeBeginTrans(db->aDb[1].pBt, 1);
|
|
2985 if( rc!=SQLITE_OK ){
|
|
2986 sqlite3ErrorMsg(pParse, "unable to get a write lock on "
|
|
2987 "the temporary database file");
|
|
2988 pParse->rc = rc;
|
|
2989 return 1;
|
|
2990 }
|
|
2991 }
|
|
2992 assert( db->aDb[1].pSchema );
|
|
2993 }
|
|
2994 return 0;
|
|
2995 }
|
|
2996
|
|
2997 /*
|
|
2998 ** Generate VDBE code that will verify the schema cookie and start
|
|
2999 ** a read-transaction for all named database files.
|
|
3000 **
|
|
3001 ** It is important that all schema cookies be verified and all
|
|
3002 ** read transactions be started before anything else happens in
|
|
3003 ** the VDBE program. But this routine can be called after much other
|
|
3004 ** code has been generated. So here is what we do:
|
|
3005 **
|
|
3006 ** The first time this routine is called, we code an OP_Goto that
|
|
3007 ** will jump to a subroutine at the end of the program. Then we
|
|
3008 ** record every database that needs its schema verified in the
|
|
3009 ** pParse->cookieMask field. Later, after all other code has been
|
|
3010 ** generated, the subroutine that does the cookie verifications and
|
|
3011 ** starts the transactions will be coded and the OP_Goto P2 value
|
|
3012 ** will be made to point to that subroutine. The generation of the
|
|
3013 ** cookie verification subroutine code happens in sqlite3FinishCoding().
|
|
3014 **
|
|
3015 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
|
|
3016 ** schema on any databases. This can be used to position the OP_Goto
|
|
3017 ** early in the code, before we know if any database tables will be used.
|
|
3018 */
|
|
3019 void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
|
|
3020 sqlite3 *db;
|
|
3021 Vdbe *v;
|
|
3022 int mask;
|
|
3023
|
|
3024 v = sqlite3GetVdbe(pParse);
|
|
3025 if( v==0 ) return; /* This only happens if there was a prior error */
|
|
3026 db = pParse->db;
|
|
3027 if( pParse->cookieGoto==0 ){
|
|
3028 pParse->cookieGoto = sqlite3VdbeAddOp(v, OP_Goto, 0, 0)+1;
|
|
3029 }
|
|
3030 if( iDb>=0 ){
|
|
3031 assert( iDb<db->nDb );
|
|
3032 assert( db->aDb[iDb].pBt!=0 || iDb==1 );
|
|
3033 assert( iDb<MAX_ATTACHED+2 );
|
|
3034 mask = 1<<iDb;
|
|
3035 if( (pParse->cookieMask & mask)==0 ){
|
|
3036 pParse->cookieMask |= mask;
|
|
3037 pParse->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
|
|
3038 if( !OMIT_TEMPDB && iDb==1 ){
|
|
3039 sqlite3OpenTempDatabase(pParse);
|
|
3040 }
|
|
3041 }
|
|
3042 }
|
|
3043 }
|
|
3044
|
|
3045 /*
|
|
3046 ** Generate VDBE code that prepares for doing an operation that
|
|
3047 ** might change the database.
|
|
3048 **
|
|
3049 ** This routine starts a new transaction if we are not already within
|
|
3050 ** a transaction. If we are already within a transaction, then a checkpoint
|
|
3051 ** is set if the setStatement parameter is true. A checkpoint should
|
|
3052 ** be set for operations that might fail (due to a constraint) part of
|
|
3053 ** the way through and which will need to undo some writes without having to
|
|
3054 ** rollback the whole transaction. For operations where all constraints
|
|
3055 ** can be checked before any changes are made to the database, it is never
|
|
3056 ** necessary to undo a write and the checkpoint should not be set.
|
|
3057 **
|
|
3058 ** Only database iDb and the temp database are made writable by this call.
|
|
3059 ** If iDb==0, then the main and temp databases are made writable. If
|
|
3060 ** iDb==1 then only the temp database is made writable. If iDb>1 then the
|
|
3061 ** specified auxiliary database and the temp database are made writable.
|
|
3062 */
|
|
3063 void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
|
|
3064 Vdbe *v = sqlite3GetVdbe(pParse);
|
|
3065 if( v==0 ) return;
|
|
3066 sqlite3CodeVerifySchema(pParse, iDb);
|
|
3067 pParse->writeMask |= 1<<iDb;
|
|
3068 if( setStatement && pParse->nested==0 ){
|
|
3069 sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
|
|
3070 }
|
|
3071 if( (OMIT_TEMPDB || iDb!=1) && pParse->db->aDb[1].pBt!=0 ){
|
|
3072 sqlite3BeginWriteOperation(pParse, setStatement, 1);
|
|
3073 }
|
|
3074 }
|
|
3075
|
|
3076 /*
|
|
3077 ** Check to see if pIndex uses the collating sequence pColl. Return
|
|
3078 ** true if it does and false if it does not.
|
|
3079 */
|
|
3080 #ifndef SQLITE_OMIT_REINDEX
|
|
3081 static int collationMatch(const char *zColl, Index *pIndex){
|
|
3082 int i;
|
|
3083 for(i=0; i<pIndex->nColumn; i++){
|
|
3084 const char *z = pIndex->azColl[i];
|
|
3085 if( z==zColl || (z && zColl && 0==sqlite3StrICmp(z, zColl)) ){
|
|
3086 return 1;
|
|
3087 }
|
|
3088 }
|
|
3089 return 0;
|
|
3090 }
|
|
3091 #endif
|
|
3092
|
|
3093 /*
|
|
3094 ** Recompute all indices of pTab that use the collating sequence pColl.
|
|
3095 ** If pColl==0 then recompute all indices of pTab.
|
|
3096 */
|
|
3097 #ifndef SQLITE_OMIT_REINDEX
|
|
3098 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
|
|
3099 Index *pIndex; /* An index associated with pTab */
|
|
3100
|
|
3101 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
|
|
3102 if( zColl==0 || collationMatch(zColl, pIndex) ){
|
|
3103 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
|
|
3104 sqlite3BeginWriteOperation(pParse, 0, iDb);
|
|
3105 sqlite3RefillIndex(pParse, pIndex, -1);
|
|
3106 }
|
|
3107 }
|
|
3108 }
|
|
3109 #endif
|
|
3110
|
|
3111 /*
|
|
3112 ** Recompute all indices of all tables in all databases where the
|
|
3113 ** indices use the collating sequence pColl. If pColl==0 then recompute
|
|
3114 ** all indices everywhere.
|
|
3115 */
|
|
3116 #ifndef SQLITE_OMIT_REINDEX
|
|
3117 static void reindexDatabases(Parse *pParse, char const *zColl){
|
|
3118 Db *pDb; /* A single database */
|
|
3119 int iDb; /* The database index number */
|
|
3120 sqlite3 *db = pParse->db; /* The database connection */
|
|
3121 HashElem *k; /* For looping over tables in pDb */
|
|
3122 Table *pTab; /* A table in the database */
|
|
3123
|
|
3124 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
|
|
3125 assert( pDb!=0 );
|
|
3126 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
|
|
3127 pTab = (Table*)sqliteHashData(k);
|
|
3128 reindexTable(pParse, pTab, zColl);
|
|
3129 }
|
|
3130 }
|
|
3131 }
|
|
3132 #endif
|
|
3133
|
|
3134 /*
|
|
3135 ** Generate code for the REINDEX command.
|
|
3136 **
|
|
3137 ** REINDEX -- 1
|
|
3138 ** REINDEX <collation> -- 2
|
|
3139 ** REINDEX ?<database>.?<tablename> -- 3
|
|
3140 ** REINDEX ?<database>.?<indexname> -- 4
|
|
3141 **
|
|
3142 ** Form 1 causes all indices in all attached databases to be rebuilt.
|
|
3143 ** Form 2 rebuilds all indices in all databases that use the named
|
|
3144 ** collating function. Forms 3 and 4 rebuild the named index or all
|
|
3145 ** indices associated with the named table.
|
|
3146 */
|
|
3147 #ifndef SQLITE_OMIT_REINDEX
|
|
3148 void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
|
|
3149 CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
|
|
3150 char *z; /* Name of a table or index */
|
|
3151 const char *zDb; /* Name of the database */
|
|
3152 Table *pTab; /* A table in the database */
|
|
3153 Index *pIndex; /* An index associated with pTab */
|
|
3154 int iDb; /* The database index number */
|
|
3155 sqlite3 *db = pParse->db; /* The database connection */
|
|
3156 Token *pObjName; /* Name of the table or index to be reindexed */
|
|
3157
|
|
3158 /* Read the database schema. If an error occurs, leave an error message
|
|
3159 ** and code in pParse and return NULL. */
|
|
3160 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
|
|
3161 return;
|
|
3162 }
|
|
3163
|
|
3164 if( pName1==0 || pName1->z==0 ){
|
|
3165 reindexDatabases(pParse, 0);
|
|
3166 return;
|
|
3167 }else if( pName2==0 || pName2->z==0 ){
|
|
3168 assert( pName1->z );
|
|
3169 pColl = sqlite3FindCollSeq(db, ENC(db), (char*)pName1->z, pName1->n, 0);
|
|
3170 if( pColl ){
|
|
3171 char *zColl = sqliteStrNDup((const char *)pName1->z, pName1->n);
|
|
3172 if( zColl ){
|
|
3173 reindexDatabases(pParse, zColl);
|
|
3174 sqliteFree(zColl);
|
|
3175 }
|
|
3176 return;
|
|
3177 }
|
|
3178 }
|
|
3179 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
|
|
3180 if( iDb<0 ) return;
|
|
3181 z = sqlite3NameFromToken(pObjName);
|
|
3182 zDb = db->aDb[iDb].zName;
|
|
3183 pTab = sqlite3FindTable(db, z, zDb);
|
|
3184 if( pTab ){
|
|
3185 reindexTable(pParse, pTab, 0);
|
|
3186 sqliteFree(z);
|
|
3187 return;
|
|
3188 }
|
|
3189 pIndex = sqlite3FindIndex(db, z, zDb);
|
|
3190 sqliteFree(z);
|
|
3191 if( pIndex ){
|
|
3192 sqlite3BeginWriteOperation(pParse, 0, iDb);
|
|
3193 sqlite3RefillIndex(pParse, pIndex, -1);
|
|
3194 return;
|
|
3195 }
|
|
3196 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
|
|
3197 }
|
|
3198 #endif
|
|
3199
|
|
3200 /*
|
|
3201 ** Return a dynamicly allocated KeyInfo structure that can be used
|
|
3202 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
|
|
3203 **
|
|
3204 ** If successful, a pointer to the new structure is returned. In this case
|
|
3205 ** the caller is responsible for calling sqliteFree() on the returned
|
|
3206 ** pointer. If an error occurs (out of memory or missing collation
|
|
3207 ** sequence), NULL is returned and the state of pParse updated to reflect
|
|
3208 ** the error.
|
|
3209 */
|
|
3210 KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
|
|
3211 int i;
|
|
3212 int nCol = pIdx->nColumn;
|
|
3213 int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
|
|
3214 KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);
|
|
3215
|
|
3216 if( pKey ){
|
|
3217 pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
|
|
3218 assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
|
|
3219 for(i=0; i<nCol; i++){
|
|
3220 char *zColl = pIdx->azColl[i];
|
|
3221 assert( zColl );
|
|
3222 pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl, -1);
|
|
3223 pKey->aSortOrder[i] = pIdx->aSortOrder[i];
|
|
3224 }
|
|
3225 pKey->nField = nCol;
|
|
3226 }
|
|
3227
|
|
3228 if( pParse->nErr ){
|
|
3229 sqliteFree(pKey);
|
|
3230 pKey = 0;
|
|
3231 }
|
|
3232 return pKey;
|
|
3233 }
|