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