interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / build.c

5940 lines · 200272 bytes Raw Blame History
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#include "sqliteInt.h"
26
27#ifndef SQLITE_OMIT_SHARED_CACHE
28/*
29** The TableLock structure is only used by the sqlite3TableLock() and
30** codeTableLocks() functions.
31*/
32struct TableLock {
33 int iDb; /* The database containing the table to be locked */
34 Pgno iTab; /* The root page of the table to be locked */
35 u8 isWriteLock; /* True for write lock. False for a read lock */
36 const char *zLockName; /* Name of the table */
37};
38
39/*
40** Record the fact that we want to lock a table at run-time.
41**
42** The table to be locked has root page iTab and is found in database iDb.
43** A read or a write lock can be taken depending on isWritelock.
44**
45** This routine just records the fact that the lock is desired. The
46** code to make the lock occur is generated by a later call to
47** codeTableLocks() which occurs during sqlite3FinishCoding().
48*/
49static SQLITE_NOINLINE void lockTable(
50 Parse *pParse, /* Parsing context */
51 int iDb, /* Index of the database containing the table to lock */
52 Pgno iTab, /* Root page number of the table to be locked */
53 u8 isWriteLock, /* True for a write lock */
54 const char *zName /* Name of the table to be locked */
55){
56 Parse *pToplevel;
57 int i;
58 int nBytes;
59 TableLock *p;
60 assert( iDb>=0 );
61
62 pToplevel = sqlite3ParseToplevel(pParse);
63 for(i=0; i<pToplevel->nTableLock; i++){
64 p = &pToplevel->aTableLock[i];
65 if( p->iDb==iDb && p->iTab==iTab ){
66 p->isWriteLock = (p->isWriteLock || isWriteLock);
67 return;
68 }
69 }
70
71 assert( pToplevel->nTableLock < 0x7fff0000 );
72 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
73 if( pToplevel->nTableLock==0 ) pToplevel->aTableLock = 0;
74 pToplevel->aTableLock =
75 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
76 if( pToplevel->aTableLock ){
77 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
78 p->iDb = iDb;
79 p->iTab = iTab;
80 p->isWriteLock = isWriteLock;
81 p->zLockName = zName;
82 }else{
83 pToplevel->nTableLock = 0;
84 sqlite3OomFault(pToplevel->db);
85 }
86}
87void sqlite3TableLock(
88 Parse *pParse, /* Parsing context */
89 int iDb, /* Index of the database containing the table to lock */
90 Pgno iTab, /* Root page number of the table to be locked */
91 u8 isWriteLock, /* True for a write lock */
92 const char *zName /* Name of the table to be locked */
93){
94 if( iDb==1 ) return;
95 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
96 lockTable(pParse, iDb, iTab, isWriteLock, zName);
97}
98
99/*
100** Code an OP_TableLock instruction for each table locked by the
101** statement (configured by calls to sqlite3TableLock()).
102*/
103static void codeTableLocks(Parse *pParse){
104 int i;
105 Vdbe *pVdbe = pParse->pVdbe;
106 assert( pVdbe!=0 );
107
108 for(i=0; i<pParse->nTableLock; i++){
109 TableLock *p = &pParse->aTableLock[i];
110 int p1 = p->iDb;
111 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
112 p->zLockName, P4_STATIC);
113 }
114}
115#else
116 #define codeTableLocks(x)
117#endif
118
119/*
120** Return TRUE if the given yDbMask object is empty - if it contains no
121** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
122** macros when SQLITE_MAX_ATTACHED is greater than 30.
123*/
124#if SQLITE_MAX_ATTACHED>30
125int sqlite3DbMaskAllZero(yDbMask m){
126 int i;
127 for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
128 return 1;
129}
130#endif
131
132/*
133** Do the union all two yDbMask objects into the first.
134*/
135#if SQLITE_MAX_ATTACHED>30
136void sqlite3DbMaskUnion(yDbMask m, yDbMask x){
137 int i;
138 for(i=0; i<sizeof(yDbMask); i++){ m[i] |= x[i]; }
139}
140#endif
141
142/*
143** This routine is called after a single SQL statement has been
144** parsed and a VDBE program to execute that statement has been
145** prepared. This routine puts the finishing touches on the
146** VDBE program and resets the pParse structure for the next
147** parse.
148**
149** Note that if an error occurred, it might be the case that
150** no VDBE code was generated.
151*/
152void sqlite3FinishCoding(Parse *pParse){
153 sqlite3 *db;
154 Vdbe *v;
155 int iDb, i;
156
157 assert( pParse->pToplevel==0 );
158 db = pParse->db;
159 assert( db->pParse==pParse );
160 if( pParse->nested ) return;
161 if( pParse->nErr ){
162 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
163 return;
164 }
165 assert( db->mallocFailed==0 );
166
167 /* Begin by generating some termination code at the end of the
168 ** vdbe program
169 */
170 v = pParse->pVdbe;
171 if( v==0 ){
172 if( db->init.busy ){
173 pParse->rc = SQLITE_DONE;
174 return;
175 }
176 v = sqlite3GetVdbe(pParse);
177 if( v==0 ) pParse->rc = SQLITE_ERROR;
178 }
179 assert( !pParse->isMultiWrite
180 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
181 if( v ){
182 if( pParse->bReturning ){
183 Returning *pReturning;
184 int addrRewind;
185 int reg;
186
187 assert( !pParse->isCreate );
188 pReturning = pParse->u1.d.pReturning;
189 if( pReturning->nRetCol ){
190 sqlite3VdbeAddOp0(v, OP_FkCheck);
191 addrRewind =
192 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
193 VdbeCoverage(v);
194 reg = pReturning->iRetReg;
195 for(i=0; i<pReturning->nRetCol; i++){
196 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
197 }
198 sqlite3VdbeAddOp2(v, OP_ResultRow, reg, i);
199 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
200 VdbeCoverage(v);
201 sqlite3VdbeJumpHere(v, addrRewind);
202 }
203 }
204 sqlite3VdbeAddOp0(v, OP_Halt);
205
206 /* The cookie mask contains one bit for each database file open.
207 ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
208 ** set for each database that is used. Generate code to start a
209 ** transaction on each used database and to verify the schema cookie
210 ** on each used database.
211 */
212 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
213 sqlite3VdbeJumpHere(v, 0);
214 assert( db->nDb>0 );
215 iDb = 0;
216 do{
217 Schema *pSchema;
218 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
219 sqlite3VdbeUsesBtree(v, iDb);
220 pSchema = db->aDb[iDb].pSchema;
221 sqlite3VdbeAddOp4Int(v,
222 OP_Transaction, /* Opcode */
223 iDb, /* P1 */
224 DbMaskTest(pParse->writeMask,iDb), /* P2 */
225 pSchema->schema_cookie, /* P3 */
226 pSchema->iGeneration /* P4 */
227 );
228 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
229 VdbeComment((v,
230 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
231 }while( ++iDb<db->nDb );
232#ifndef SQLITE_OMIT_VIRTUALTABLE
233 for(i=0; i<pParse->nVtabLock; i++){
234 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
235 sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
236 }
237 pParse->nVtabLock = 0;
238#endif
239
240#ifndef SQLITE_OMIT_SHARED_CACHE
241 /* Once all the cookies have been verified and transactions opened,
242 ** obtain the required table-locks. This is a no-op unless the
243 ** shared-cache feature is enabled.
244 */
245 if( pParse->nTableLock ) codeTableLocks(pParse);
246#endif
247
248 /* Initialize any AUTOINCREMENT data structures required.
249 */
250 if( pParse->usesAinc ) sqlite3AutoincrementBegin(pParse);
251
252 /* Code constant expressions that were factored out of inner loops.
253 */
254 if( pParse->pConstExpr ){
255 ExprList *pEL = pParse->pConstExpr;
256 pParse->okConstFactor = 0;
257 for(i=0; i<pEL->nExpr; i++){
258 assert( pEL->a[i].u.iConstExprReg>0 );
259 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
260 }
261 }
262
263 if( pParse->bReturning ){
264 Returning *pRet;
265 assert( !pParse->isCreate );
266 pRet = pParse->u1.d.pReturning;
267 if( pRet->nRetCol ){
268 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
269 }
270 }
271
272 /* Finally, jump back to the beginning of the executable code. */
273 sqlite3VdbeGoto(v, 1);
274 }
275
276 /* Get the VDBE program ready for execution
277 */
278 assert( v!=0 || pParse->nErr );
279 assert( db->mallocFailed==0 || pParse->nErr );
280 if( pParse->nErr==0 ){
281 /* A minimum of one cursor is required if autoincrement is used
282 * See ticket [a696379c1f08866] */
283 assert( pParse->usesAinc==0 || pParse->nTab>0 );
284 sqlite3VdbeMakeReady(v, pParse);
285 pParse->rc = SQLITE_DONE;
286 }else{
287 pParse->rc = SQLITE_ERROR;
288 }
289}
290
291/*
292** Run the parser and code generator recursively in order to generate
293** code for the SQL statement given onto the end of the pParse context
294** currently under construction. Notes:
295**
296** * The final OP_Halt is not appended and other initialization
297** and finalization steps are omitted because those are handling by the
298** outermost parser.
299**
300** * Built-in SQL functions always take precedence over application-defined
301** SQL functions. In other words, it is not possible to override a
302** built-in function.
303*/
304void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
305 va_list ap;
306 char *zSql;
307 sqlite3 *db = pParse->db;
308 u32 savedDbFlags = db->mDbFlags;
309 char saveBuf[PARSE_TAIL_SZ];
310
311 if( pParse->nErr ) return;
312 if( pParse->eParseMode ) return;
313 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
314 va_start(ap, zFormat);
315 zSql = sqlite3VMPrintf(db, zFormat, ap);
316 va_end(ap);
317 if( zSql==0 ){
318 /* This can result either from an OOM or because the formatted string
319 ** exceeds SQLITE_LIMIT_LENGTH. In the latter case, we need to set
320 ** an error */
321 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
322 pParse->nErr++;
323 return;
324 }
325 pParse->nested++;
326 memcpy(saveBuf, PARSE_TAIL(pParse), PARSE_TAIL_SZ);
327 memset(PARSE_TAIL(pParse), 0, PARSE_TAIL_SZ);
328 db->mDbFlags |= DBFLAG_PreferBuiltin;
329 sqlite3RunParser(pParse, zSql);
330 db->mDbFlags = savedDbFlags;
331 sqlite3DbFree(db, zSql);
332 memcpy(PARSE_TAIL(pParse), saveBuf, PARSE_TAIL_SZ);
333 pParse->nested--;
334}
335
336/*
337** Locate the in-memory structure that describes a particular database
338** table given the name of that table and (optionally) the name of the
339** database containing the table. Return NULL if not found.
340**
341** If zDatabase is 0, all databases are searched for the table and the
342** first matching table is returned. (No checking for duplicate table
343** names is done.) The search order is TEMP first, then MAIN, then any
344** auxiliary databases added using the ATTACH command.
345**
346** See also sqlite3LocateTable().
347*/
348Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
349 Table *p = 0;
350 int i;
351
352 /* All mutexes are required for schema access. Make sure we hold them. */
353 assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
354 if( zDatabase ){
355 for(i=0; i<db->nDb; i++){
356 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
357 }
358 if( i>=db->nDb ){
359 /* No match against the official names. But always match "main"
360 ** to schema 0 as a legacy fallback. */
361 if( sqlite3StrICmp(zDatabase,"main")==0 ){
362 i = 0;
363 }else{
364 return 0;
365 }
366 }
367 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
368 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
369 if( i==1 ){
370 if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0
371 || sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0
372 || sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0
373 ){
374 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
375 LEGACY_TEMP_SCHEMA_TABLE);
376 }
377 }else{
378 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
379 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
380 LEGACY_SCHEMA_TABLE);
381 }
382 }
383 }
384 }else{
385 /* Match against TEMP first */
386 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
387 if( p ) return p;
388 /* The main database is second */
389 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
390 if( p ) return p;
391 /* Attached databases are in order of attachment */
392 for(i=2; i<db->nDb; i++){
393 assert( sqlite3SchemaMutexHeld(db, i, 0) );
394 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
395 if( p ) break;
396 }
397 if( p==0 && sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
398 if( sqlite3StrICmp(zName+7, &PREFERRED_SCHEMA_TABLE[7])==0 ){
399 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
400 }else if( sqlite3StrICmp(zName+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
401 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
402 LEGACY_TEMP_SCHEMA_TABLE);
403 }
404 }
405 }
406 return p;
407}
408
409/*
410** Locate the in-memory structure that describes a particular database
411** table given the name of that table and (optionally) the name of the
412** database containing the table. Return NULL if not found. Also leave an
413** error message in pParse->zErrMsg.
414**
415** The difference between this routine and sqlite3FindTable() is that this
416** routine leaves an error message in pParse->zErrMsg where
417** sqlite3FindTable() does not.
418*/
419Table *sqlite3LocateTable(
420 Parse *pParse, /* context in which to report errors */
421 u32 flags, /* LOCATE_VIEW or LOCATE_NOERR */
422 const char *zName, /* Name of the table we are looking for */
423 const char *zDbase /* Name of the database. Might be NULL */
424){
425 Table *p;
426 sqlite3 *db = pParse->db;
427
428 /* Read the database schema. If an error occurs, leave an error message
429 ** and code in pParse and return NULL. */
430 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
431 && SQLITE_OK!=sqlite3ReadSchema(pParse)
432 ){
433 return 0;
434 }
435
436 p = sqlite3FindTable(db, zName, zDbase);
437 if( p==0 ){
438#ifndef SQLITE_OMIT_VIRTUALTABLE
439 /* If zName is the not the name of a table in the schema created using
440 ** CREATE, then check to see if it is the name of an virtual table that
441 ** can be an eponymous virtual table. */
442 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
443 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
444 if( pMod==0 && sqlite3_strnicmp(zName, "pragma_", 7)==0 ){
445 pMod = sqlite3PragmaVtabRegister(db, zName);
446 }
447#ifndef SQLITE_OMIT_JSON
448 if( pMod==0 && sqlite3_strnicmp(zName, "json", 4)==0 ){
449 pMod = sqlite3JsonVtabRegister(db, zName);
450 }
451#endif
452#ifdef SQLITE_ENABLE_CARRAY
453 if( pMod==0 && sqlite3_stricmp(zName, "carray")==0 ){
454 pMod = sqlite3CarrayRegister(db);
455 }
456#endif
457 if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
458 testcase( pMod->pEpoTab==0 );
459 return pMod->pEpoTab;
460 }
461 }
462#endif
463 if( flags & LOCATE_NOERR ) return 0;
464 pParse->checkSchema = 1;
465 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
466 p = 0;
467 }
468
469 if( p==0 ){
470 const char *zMsg = flags & LOCATE_VIEW ? "no such view" : "no such table";
471 if( zDbase ){
472 sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
473 }else{
474 sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
475 }
476 }else{
477 assert( HasRowid(p) || p->iPKey<0 );
478 }
479
480 return p;
481}
482
483/*
484** Locate the table identified by *p.
485**
486** This is a wrapper around sqlite3LocateTable(). The difference between
487** sqlite3LocateTable() and this function is that this function restricts
488** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
489** non-NULL if it is part of a view or trigger program definition. See
490** sqlite3FixSrcList() for details.
491*/
492Table *sqlite3LocateTableItem(
493 Parse *pParse,
494 u32 flags,
495 SrcItem *p
496){
497 const char *zDb;
498 if( p->fg.fixedSchema ){
499 int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema);
500 assert( iDb>=0 && iDb<pParse->db->nDb );
501 zDb = pParse->db->aDb[iDb].zDbSName;
502 }else{
503 assert( !p->fg.isSubquery );
504 zDb = p->u4.zDatabase;
505 }
506 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
507}
508
509/*
510** Return the preferred table name for system tables. Translate legacy
511** names into the new preferred names, as appropriate.
512*/
513const char *sqlite3PreferredTableName(const char *zName){
514 if( sqlite3StrNICmp(zName, "sqlite_", 7)==0 ){
515 if( sqlite3StrICmp(zName+7, &LEGACY_SCHEMA_TABLE[7])==0 ){
516 return PREFERRED_SCHEMA_TABLE;
517 }
518 if( sqlite3StrICmp(zName+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
519 return PREFERRED_TEMP_SCHEMA_TABLE;
520 }
521 }
522 return zName;
523}
524
525/*
526** Locate the in-memory structure that describes
527** a particular index given the name of that index
528** and the name of the database that contains the index.
529** Return NULL if not found.
530**
531** If zDatabase is 0, all databases are searched for the
532** table and the first matching index is returned. (No checking
533** for duplicate index names is done.) The search order is
534** TEMP first, then MAIN, then any auxiliary databases added
535** using the ATTACH command.
536*/
537Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
538 Index *p = 0;
539 int i;
540 /* All mutexes are required for schema access. Make sure we hold them. */
541 assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
542 for(i=OMIT_TEMPDB; i<db->nDb; i++){
543 int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
544 Schema *pSchema = db->aDb[j].pSchema;
545 assert( pSchema );
546 if( zDb && sqlite3DbIsNamed(db, j, zDb)==0 ) continue;
547 assert( sqlite3SchemaMutexHeld(db, j, 0) );
548 p = sqlite3HashFind(&pSchema->idxHash, zName);
549 if( p ) break;
550 }
551 return p;
552}
553
554/*
555** Reclaim the memory used by an index
556*/
557void sqlite3FreeIndex(sqlite3 *db, Index *p){
558#ifndef SQLITE_OMIT_ANALYZE
559 sqlite3DeleteIndexSamples(db, p);
560#endif
561 sqlite3ExprDelete(db, p->pPartIdxWhere);
562 sqlite3ExprListDelete(db, p->aColExpr);
563 sqlite3DbFree(db, p->zColAff);
564 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
565#ifdef SQLITE_ENABLE_STAT4
566 sqlite3_free(p->aiRowEst);
567#endif
568 sqlite3DbFree(db, p);
569}
570
571/*
572** For the index called zIdxName which is found in the database iDb,
573** unlike that index from its Table then remove the index from
574** the index hash table and free all memory structures associated
575** with the index.
576*/
577void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
578 Index *pIndex;
579 Hash *pHash;
580
581 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
582 pHash = &db->aDb[iDb].pSchema->idxHash;
583 pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
584 if( ALWAYS(pIndex) ){
585 if( pIndex->pTable->pIndex==pIndex ){
586 pIndex->pTable->pIndex = pIndex->pNext;
587 }else{
588 Index *p;
589 /* Justification of ALWAYS(); The index must be on the list of
590 ** indices. */
591 p = pIndex->pTable->pIndex;
592 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
593 if( ALWAYS(p && p->pNext==pIndex) ){
594 p->pNext = pIndex->pNext;
595 }
596 }
597 sqlite3FreeIndex(db, pIndex);
598 }
599 db->mDbFlags |= DBFLAG_SchemaChange;
600}
601
602/*
603** Look through the list of open database files in db->aDb[] and if
604** any have been closed, remove them from the list. Reallocate the
605** db->aDb[] structure to a smaller size, if possible.
606**
607** Entry 0 (the "main" database) and entry 1 (the "temp" database)
608** are never candidates for being collapsed.
609*/
610void sqlite3CollapseDatabaseArray(sqlite3 *db){
611 int i, j;
612 for(i=j=2; i<db->nDb; i++){
613 struct Db *pDb = &db->aDb[i];
614 if( pDb->pBt==0 ){
615 sqlite3DbFree(db, pDb->zDbSName);
616 pDb->zDbSName = 0;
617 continue;
618 }
619 if( j<i ){
620 db->aDb[j] = db->aDb[i];
621 }
622 j++;
623 }
624 db->nDb = j;
625 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
626 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
627 sqlite3DbFree(db, db->aDb);
628 db->aDb = db->aDbStatic;
629 }
630}
631
632/*
633** Reset the schema for the database at index iDb. Also reset the
634** TEMP schema. The reset is deferred if db->nSchemaLock is not zero
635** or if an active VDBE other than pSafe is using iDb
636**
637** Deferred schema resets may be retried by calling with iDb<0.
638*/
639void sqlite3ResetOneSchema(sqlite3 *db, int iDb, Vdbe *pSafe){
640 int i;
641 assert( iDb<db->nDb );
642
643 if( iDb>=0 ){
644 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
645 DbSetProperty(db, iDb, DB_ResetWanted);
646 DbSetProperty(db, 1, DB_ResetWanted);
647 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
648 db->bPendingSchemaReset = 1;
649 }
650
651 if( db->nSchemaLock==0 ){
652 yDbMask m;
653 sqlite3VdbeSchemaInUse(db, pSafe, &m);
654 db->bPendingSchemaReset = 0;
655 for(i=0; i<db->nDb; i++){
656 if( !DbHasProperty(db, i, DB_ResetWanted) ){
657 /* no-op */
658 }else if( DbMaskTest(m,i) ){
659 db->bPendingSchemaReset = 1;
660 }else{
661 sqlite3SchemaClear(db->aDb[i].pSchema);
662 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
663 }
664 }
665 }
666}
667
668/*
669** Erase all schema information from all attached databases (including
670** "main" and "temp") for a single database connection.
671*/
672void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
673 int i;
674 sqlite3BtreeEnterAll(db);
675 for(i=0; i<db->nDb; i++){
676 Db *pDb = &db->aDb[i];
677 if( pDb->pSchema ){
678 if( db->nSchemaLock==0 ){
679 sqlite3SchemaClear(pDb->pSchema);
680 }else{
681 DbSetProperty(db, i, DB_ResetWanted);
682 }
683 }
684 }
685 sqlite3ExpirePreparedStatements(db, 0);
686 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
687 sqlite3VtabUnlockList(db);
688 sqlite3BtreeLeaveAll(db);
689 if( db->nSchemaLock==0 ){
690 sqlite3CollapseDatabaseArray(db);
691 }
692}
693
694/*
695** This routine is called when a commit occurs.
696*/
697void sqlite3CommitInternalChanges(sqlite3 *db){
698 db->mDbFlags &= ~DBFLAG_SchemaChange;
699}
700
701/*
702** Set the expression associated with a column. This is usually
703** the DEFAULT value, but might also be the expression that computes
704** the value for a generated column.
705*/
706void sqlite3ColumnSetExpr(
707 Parse *pParse, /* Parsing context */
708 Table *pTab, /* The table containing the column */
709 Column *pCol, /* The column to receive the new DEFAULT expression */
710 Expr *pExpr /* The new default expression */
711){
712 ExprList *pList;
713 assert( IsOrdinaryTable(pTab) );
714 pList = pTab->u.tab.pDfltList;
715 if( pCol->iDflt==0
716 || NEVER(pList==0)
717 || NEVER(pList->nExpr<pCol->iDflt)
718 ){
719 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
720 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
721 }else{
722 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
723 pList->a[pCol->iDflt-1].pExpr = pExpr;
724 }
725}
726
727#ifndef SQLITE_OMIT_AUTHORIZATION
728/*
729** If the expression contains any TK_FUNCTION, send it to the authorizer
730** and if the authorization fails then raise an error.
731*/
732static int authFunctions(Walker *pWalker, Expr *p){
733 if( p->op==TK_FUNCTION ){
734 Parse *pParse = pWalker->pParse;
735 int rc = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, p->u.zToken, 0);
736 if( rc ){
737 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T", p);
738 return WRC_Abort;
739 }
740 }
741 return WRC_Continue;
742}
743static void sqlite3FuncAuth(Parse *pParse, Expr *pExpr){
744 Walker w;
745 memset(&w, 0, sizeof(w));
746 w.xExprCallback = authFunctions;
747 w.pParse = pParse;
748 sqlite3WalkExpr(&w,pExpr);
749}
750#endif /* SQLITE_OMIT_AUTHORIZATION */
751
752/*
753** Return the expression associated with a column. The expression might be
754** the DEFAULT clause or the AS clause of a generated column.
755** Return NULL if the column has no associated expression.
756**
757** There are two variants of this routine. sqlite3ColumnExpr() just
758** returns the expression with no side effects. sqlite3ColumnExprAuth()
759** takes the extra step of invoking the authorizer (if one is defined)
760** and raising an error if the returned expression uses any unauthorized
761** SQL function.
762*/
763Expr *sqlite3ColumnExpr(Table *pTab, Column *pCol){
764 if( pCol->iDflt==0 ) return 0;
765 if( !IsOrdinaryTable(pTab) ) return 0;
766 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
767 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
768 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
769}
770Expr *sqlite3ColumnExprAuth(Table *pTab, Column *pCol, Parse *pParse){
771 Expr *pExpr = sqlite3ColumnExpr(pTab,pCol);
772#ifndef SQLITE_OMIT_AUTHORIZATION
773 if( pParse->db->xAuth!=0 ){
774 sqlite3FuncAuth(pParse, pExpr);
775 }
776#endif
777 return pExpr;
778}
779
780/*
781** Suppress false-positive warning message generated with -O3 in GCC
782** on the second call to sqlite3Strlen30() in the sqlite3ColumnSetColl()
783** function below. See the forum thread beginning on 2026-05-10T01:11:22Z.
784**
785** See also the "pop" pragma to undo this warning suppression immediately
786** after the function.
787*/
788#if defined(__GNUC__) && __GNUC__>=11
789# pragma GCC diagnostic push
790# pragma GCC diagnostic ignored "-Wstringop-overread"
791#endif
792
793/*
794** Set the collating sequence name for a column.
795*/
796void sqlite3ColumnSetColl(
797 sqlite3 *db,
798 Column *pCol,
799 const char *zColl
800){
801 i64 nColl;
802 i64 n;
803 char *zNew;
804 assert( zColl!=0 );
805 n = sqlite3Strlen30(pCol->zCnName) + 1;
806 if( pCol->colFlags & COLFLAG_HASTYPE ){
807 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
808 }
809 nColl = sqlite3Strlen30(zColl) + 1;
810 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
811 if( zNew ){
812 pCol->zCnName = zNew;
813 memcpy(pCol->zCnName + n, zColl, nColl);
814 pCol->colFlags |= COLFLAG_HASCOLL;
815 }
816}
817
818/* Undo the false-positive warning suppression above. */
819#if defined(__GNUC__) && __GNUC__>=11
820# pragma GCC diagnostic pop
821#endif
822
823/*
824** Return the collating sequence name for a column
825*/
826const char *sqlite3ColumnColl(Column *pCol){
827 const char *z;
828 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
829 z = pCol->zCnName;
830 while( *z ){ z++; }
831 if( pCol->colFlags & COLFLAG_HASTYPE ){
832 do{ z++; }while( *z );
833 }
834 return z+1;
835}
836
837/*
838** Delete memory allocated for the column names of a table or view (the
839** Table.aCol[] array).
840*/
841void sqlite3DeleteColumnNames(sqlite3 *db, Table *pTable){
842 int i;
843 Column *pCol;
844 assert( pTable!=0 );
845 assert( db!=0 );
846 if( (pCol = pTable->aCol)!=0 ){
847 for(i=0; i<pTable->nCol; i++, pCol++){
848 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
849 sqlite3DbFree(db, pCol->zCnName);
850 }
851 sqlite3DbNNFreeNN(db, pTable->aCol);
852 if( IsOrdinaryTable(pTable) ){
853 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
854 }
855 if( db->pnBytesFreed==0 ){
856 pTable->aCol = 0;
857 pTable->nCol = 0;
858 if( IsOrdinaryTable(pTable) ){
859 pTable->u.tab.pDfltList = 0;
860 }
861 }
862 }
863}
864
865/*
866** Remove the memory data structures associated with the given
867** Table. No changes are made to disk by this routine.
868**
869** This routine just deletes the data structure. It does not unlink
870** the table data structure from the hash table. But it does destroy
871** memory structures of the indices and foreign keys associated with
872** the table.
873**
874** The db parameter is optional. It is needed if the Table object
875** contains lookaside memory. (Table objects in the schema do not use
876** lookaside memory, but some ephemeral Table objects do.) Or the
877** db parameter can be used with db->pnBytesFreed to measure the memory
878** used by the Table object.
879*/
880static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
881 Index *pIndex, *pNext;
882
883#ifdef SQLITE_DEBUG
884 /* Record the number of outstanding lookaside allocations in schema Tables
885 ** prior to doing any free() operations. Since schema Tables do not use
886 ** lookaside, this number should not change.
887 **
888 ** If malloc has already failed, it may be that it failed while allocating
889 ** a Table object that was going to be marked ephemeral. So do not check
890 ** that no lookaside memory is used in this case either. */
891 int nLookaside = 0;
892 assert( db!=0 );
893 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
894 nLookaside = sqlite3LookasideUsed(db, 0);
895 }
896#endif
897
898 /* Delete all indices associated with this table. */
899 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
900 pNext = pIndex->pNext;
901 assert( pIndex->pSchema==pTable->pSchema
902 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
903 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
904 char *zName = pIndex->zName;
905 TESTONLY ( Index *pOld = ) sqlite3HashInsert(
906 &pIndex->pSchema->idxHash, zName, 0
907 );
908 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
909 assert( pOld==pIndex || pOld==0 );
910 }
911 sqlite3FreeIndex(db, pIndex);
912 }
913
914 if( IsOrdinaryTable(pTable) ){
915 sqlite3FkDelete(db, pTable);
916 }
917#ifndef SQLITE_OMIT_VIRTUALTABLE
918 else if( IsVirtual(pTable) ){
919 sqlite3VtabClear(db, pTable);
920 }
921#endif
922 else{
923 assert( IsView(pTable) );
924 sqlite3SelectDelete(db, pTable->u.view.pSelect);
925 }
926
927 /* Delete the Table structure itself.
928 */
929 sqlite3DeleteColumnNames(db, pTable);
930 sqlite3DbFree(db, pTable->zName);
931 sqlite3DbFree(db, pTable->zColAff);
932 sqlite3ExprListDelete(db, pTable->pCheck);
933 sqlite3DbFree(db, pTable);
934
935 /* Verify that no lookaside memory was used by schema tables */
936 assert( nLookaside==0 || nLookaside==sqlite3LookasideUsed(db,0) );
937}
938void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
939 /* Do not delete the table until the reference count reaches zero. */
940 assert( db!=0 );
941 if( !pTable ) return;
942 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
943 deleteTable(db, pTable);
944}
945void sqlite3DeleteTableGeneric(sqlite3 *db, void *pTable){
946 sqlite3DeleteTable(db, (Table*)pTable);
947}
948
949
950/*
951** Unlink the given table from the hash tables and the delete the
952** table structure with all its indices and foreign keys.
953*/
954void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
955 Table *p;
956 Db *pDb;
957
958 assert( db!=0 );
959 assert( iDb>=0 && iDb<db->nDb );
960 assert( zTabName );
961 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
962 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
963 pDb = &db->aDb[iDb];
964 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
965 sqlite3DeleteTable(db, p);
966 db->mDbFlags |= DBFLAG_SchemaChange;
967}
968
969/*
970** Given a token, return a string that consists of the text of that
971** token. Space to hold the returned string
972** is obtained from sqliteMalloc() and must be freed by the calling
973** function.
974**
975** Any quotation marks (ex: "name", 'name', [name], or `name`) that
976** surround the body of the token are removed.
977**
978** Tokens are often just pointers into the original SQL text and so
979** are not \000 terminated and are not persistent. The returned string
980** is \000 terminated and is persistent.
981*/
982char *sqlite3NameFromToken(sqlite3 *db, const Token *pName){
983 char *zName;
984 if( pName ){
985 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
986 sqlite3Dequote(zName);
987 }else{
988 zName = 0;
989 }
990 return zName;
991}
992
993/*
994** Open the sqlite_schema table stored in database number iDb for
995** writing. The table is opened using cursor 0.
996*/
997void sqlite3OpenSchemaTable(Parse *p, int iDb){
998 Vdbe *v = sqlite3GetVdbe(p);
999 sqlite3TableLock(p, iDb, SCHEMA_ROOT, 1, LEGACY_SCHEMA_TABLE);
1000 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, SCHEMA_ROOT, iDb, 5);
1001 if( p->nTab==0 ){
1002 p->nTab = 1;
1003 }
1004}
1005
1006/*
1007** Parameter zName points to a nul-terminated buffer containing the name
1008** of a database ("main", "temp" or the name of an attached db). This
1009** function returns the index of the named database in db->aDb[], or
1010** -1 if the named db cannot be found.
1011*/
1012int sqlite3FindDbName(sqlite3 *db, const char *zName){
1013 int i = -1; /* Database number */
1014 if( zName ){
1015 Db *pDb;
1016 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
1017 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
1018 /* "main" is always an acceptable alias for the primary database
1019 ** even if it has been renamed using SQLITE_DBCONFIG_MAINDBNAME. */
1020 if( i==0 && 0==sqlite3_stricmp("main", zName) ) break;
1021 }
1022 }
1023 return i;
1024}
1025
1026/*
1027** The token *pName contains the name of a database (either "main" or
1028** "temp" or the name of an attached db). This routine returns the
1029** index of the named database in db->aDb[], or -1 if the named db
1030** does not exist.
1031*/
1032int sqlite3FindDb(sqlite3 *db, Token *pName){
1033 int i; /* Database number */
1034 char *zName; /* Name we are searching for */
1035 zName = sqlite3NameFromToken(db, pName);
1036 i = sqlite3FindDbName(db, zName);
1037 sqlite3DbFree(db, zName);
1038 return i;
1039}
1040
1041/* The table or view or trigger name is passed to this routine via tokens
1042** pName1 and pName2. If the table name was fully qualified, for example:
1043**
1044** CREATE TABLE xxx.yyy (...);
1045**
1046** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
1047** the table name is not fully qualified, i.e.:
1048**
1049** CREATE TABLE yyy(...);
1050**
1051** Then pName1 is set to "yyy" and pName2 is "".
1052**
1053** This routine sets the *ppUnqual pointer to point at the token (pName1 or
1054** pName2) that stores the unqualified table name. The index of the
1055** database "xxx" is returned.
1056*/
1057int sqlite3TwoPartName(
1058 Parse *pParse, /* Parsing and code generating context */
1059 Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
1060 Token *pName2, /* The "yyy" in the name "xxx.yyy" */
1061 Token **pUnqual /* Write the unqualified object name here */
1062){
1063 int iDb; /* Database holding the object */
1064 sqlite3 *db = pParse->db;
1065
1066 assert( pName2!=0 );
1067 if( pName2->n>0 ){
1068 if( db->init.busy ) {
1069 sqlite3ErrorMsg(pParse, "corrupt database");
1070 return -1;
1071 }
1072 *pUnqual = pName2;
1073 iDb = sqlite3FindDb(db, pName1);
1074 if( iDb<0 ){
1075 sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
1076 return -1;
1077 }
1078 }else{
1079 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
1080 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
1081 iDb = db->init.iDb;
1082 *pUnqual = pName1;
1083 }
1084 return iDb;
1085}
1086
1087/*
1088** True if PRAGMA writable_schema is ON
1089*/
1090int sqlite3WritableSchema(sqlite3 *db){
1091 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
1092 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1093 SQLITE_WriteSchema );
1094 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1095 SQLITE_Defensive );
1096 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
1097 (SQLITE_WriteSchema|SQLITE_Defensive) );
1098 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
1099}
1100
1101/*
1102** This routine is used to check if the UTF-8 string zName is a legal
1103** unqualified name for a new schema object (table, index, view or
1104** trigger). All names are legal except those that begin with the string
1105** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
1106** is reserved for internal use.
1107**
1108** When parsing the sqlite_schema table, this routine also checks to
1109** make sure the "type", "name", and "tbl_name" columns are consistent
1110** with the SQL.
1111**
1112** If shadow tables are read-only, names that are shadow table names
1113** of a virtual table in schema zDb are also reserved.
1114*/
1115int sqlite3CheckObjectName(
1116 Parse *pParse, /* Parsing context */
1117 const char *zName, /* Name of the object to check */
1118 const char *zType, /* Type of this object */
1119 const char *zTblName, /* Parent table name for triggers and indexes */
1120 const char *zDb /* Schema in which the object will be created */
1121){
1122 sqlite3 *db = pParse->db;
1123 if( sqlite3WritableSchema(db)
1124 || db->init.imposterTable
1125 || !sqlite3Config.bExtraSchemaChecks
1126 ){
1127 /* Skip these error checks for writable_schema=ON */
1128 return SQLITE_OK;
1129 }
1130 if( db->init.busy ){
1131 if( sqlite3_stricmp(zType, db->init.azInit[0])
1132 || sqlite3_stricmp(zName, db->init.azInit[1])
1133 || sqlite3_stricmp(zTblName, db->init.azInit[2])
1134 ){
1135 sqlite3ErrorMsg(pParse, ""); /* corruptSchema() will supply the error */
1136 return SQLITE_ERROR;
1137 }
1138 }else{
1139 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
1140 || (sqlite3ReadOnlyShadowTables(db)
1141 && sqlite3ShadowTableName(db, zName, zDb))
1142 ){
1143 sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s",
1144 zName);
1145 return SQLITE_ERROR;
1146 }
1147
1148 }
1149 return SQLITE_OK;
1150}
1151
1152/*
1153** Return the PRIMARY KEY index of a table
1154*/
1155Index *sqlite3PrimaryKeyIndex(Table *pTab){
1156 Index *p;
1157 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
1158 return p;
1159}
1160
1161/*
1162** Convert an table column number into a index column number. That is,
1163** for the column iCol in the table (as defined by the CREATE TABLE statement)
1164** find the (first) offset of that column in index pIdx. Or return -1
1165** if column iCol is not used in index pIdx.
1166*/
1167int sqlite3TableColumnToIndex(Index *pIdx, int iCol){
1168 int i;
1169 i16 iCol16;
1170 assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN );
1171 assert( pIdx->nColumn<=SQLITE_MAX_COLUMN*2 );
1172 iCol16 = iCol;
1173 for(i=0; i<pIdx->nColumn; i++){
1174 if( iCol16==pIdx->aiColumn[i] ){
1175 return i;
1176 }
1177 }
1178 return -1;
1179}
1180
1181#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1182/* Convert a storage column number into a table column number.
1183**
1184** The storage column number (0,1,2,....) is the index of the value
1185** as it appears in the record on disk. The true column number
1186** is the index (0,1,2,...) of the column in the CREATE TABLE statement.
1187**
1188** The storage column number is less than the table column number if
1189** and only there are VIRTUAL columns to the left.
1190**
1191** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
1192*/
1193i16 sqlite3StorageColumnToTable(Table *pTab, i16 iCol){
1194 if( pTab->tabFlags & TF_HasVirtual ){
1195 int i;
1196 for(i=0; i<=iCol; i++){
1197 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
1198 }
1199 }
1200 return iCol;
1201}
1202#endif
1203
1204#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1205/* Convert a table column number into a storage column number.
1206**
1207** The storage column number (0,1,2,....) is the index of the value
1208** as it appears in the record on disk. Or, if the input column is
1209** the N-th virtual column (zero-based) then the storage number is
1210** the number of non-virtual columns in the table plus N.
1211**
1212** The true column number is the index (0,1,2,...) of the column in
1213** the CREATE TABLE statement.
1214**
1215** If the input column is a VIRTUAL column, then it should not appear
1216** in storage. But the value sometimes is cached in registers that
1217** follow the range of registers used to construct storage. This
1218** avoids computing the same VIRTUAL column multiple times, and provides
1219** values for use by OP_Param opcodes in triggers. Hence, if the
1220** input column is a VIRTUAL table, put it after all the other columns.
1221**
1222** In the following, N means "normal column", S means STORED, and
1223** V means VIRTUAL. Suppose the CREATE TABLE has columns like this:
1224**
1225** CREATE TABLE ex(N,S,V,N,S,V,N,S,V);
1226** -- 0 1 2 3 4 5 6 7 8
1227**
1228** Then the mapping from this function is as follows:
1229**
1230** INPUTS: 0 1 2 3 4 5 6 7 8
1231** OUTPUTS: 0 1 6 2 3 7 4 5 8
1232**
1233** So, in other words, this routine shifts all the virtual columns to
1234** the end.
1235**
1236** If SQLITE_OMIT_GENERATED_COLUMNS then there are no virtual columns and
1237** this routine is a no-op macro. If the pTab does not have any virtual
1238** columns, then this routine is no-op that always return iCol. If iCol
1239** is negative (indicating the ROWID column) then this routine return iCol.
1240*/
1241i16 sqlite3TableColumnToStorage(Table *pTab, i16 iCol){
1242 int i;
1243 i16 n;
1244 assert( iCol<pTab->nCol );
1245 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
1246 for(i=0, n=0; i<iCol; i++){
1247 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
1248 }
1249 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
1250 /* iCol is a virtual column itself */
1251 return pTab->nNVCol + i - n;
1252 }else{
1253 /* iCol is a normal or stored column */
1254 return n;
1255 }
1256}
1257#endif
1258
1259/*
1260** Insert a single OP_JournalMode query opcode in order to force the
1261** prepared statement to return false for sqlite3_stmt_readonly(). This
1262** is used by CREATE TABLE IF NOT EXISTS and similar if the table already
1263** exists, so that the prepared statement for CREATE TABLE IF NOT EXISTS
1264** will return false for sqlite3_stmt_readonly() even if that statement
1265** is a read-only no-op.
1266*/
1267static void sqlite3ForceNotReadOnly(Parse *pParse){
1268 int iReg = ++pParse->nMem;
1269 Vdbe *v = sqlite3GetVdbe(pParse);
1270 if( v ){
1271 sqlite3VdbeAddOp3(v, OP_JournalMode, 0, iReg, PAGER_JOURNALMODE_QUERY);
1272 sqlite3VdbeUsesBtree(v, 0);
1273 }
1274}
1275
1276/*
1277** Begin constructing a new table representation in memory. This is
1278** the first of several action routines that get called in response
1279** to a CREATE TABLE statement. In particular, this routine is called
1280** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
1281** flag is true if the table should be stored in the auxiliary database
1282** file instead of in the main database file. This is normally the case
1283** when the "TEMP" or "TEMPORARY" keyword occurs in between
1284** CREATE and TABLE.
1285**
1286** The new table record is initialized and put in pParse->pNewTable.
1287** As more of the CREATE TABLE statement is parsed, additional action
1288** routines will be called to add more information to this record.
1289** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
1290** is called to complete the construction of the new table record.
1291*/
1292void sqlite3StartTable(
1293 Parse *pParse, /* Parser context */
1294 Token *pName1, /* First part of the name of the table or view */
1295 Token *pName2, /* Second part of the name of the table or view */
1296 int isTemp, /* True if this is a TEMP table */
1297 int isView, /* True if this is a VIEW */
1298 int isVirtual, /* True if this is a VIRTUAL table */
1299 int noErr /* Do nothing if table already exists */
1300){
1301 Table *pTable;
1302 char *zName = 0; /* The name of the new table */
1303 sqlite3 *db = pParse->db;
1304 Vdbe *v;
1305 int iDb; /* Database number to create the table in */
1306 Token *pName; /* Unqualified name of the table to create */
1307
1308 if( db->init.busy && db->init.newTnum==1 ){
1309 /* Special case: Parsing the sqlite_schema or sqlite_temp_schema schema */
1310 iDb = db->init.iDb;
1311 zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
1312 pName = pName1;
1313 }else{
1314 /* The common case */
1315 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
1316 if( iDb<0 ) return;
1317 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
1318 /* If creating a temp table, the name may not be qualified. Unless
1319 ** the database name is "temp" anyway. */
1320 sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
1321 return;
1322 }
1323 if( !OMIT_TEMPDB && isTemp ) iDb = 1;
1324 zName = sqlite3NameFromToken(db, pName);
1325 if( IN_RENAME_OBJECT ){
1326 sqlite3RenameTokenMap(pParse, (void*)zName, pName);
1327 }
1328 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1329 goto begin_table_error;
1330 }
1331 }
1332 pParse->sNameToken = *pName;
1333 if( zName==0 ) return;
1334 if( sqlite3CheckObjectName(pParse, zName, isView?"view":"table", zName,
1335 db->aDb[iDb].zDbSName) ){
1336 goto begin_table_error;
1337 }
1338 if( db->init.iDb==1 ) isTemp = 1;
1339#ifndef SQLITE_OMIT_AUTHORIZATION
1340 assert( isTemp==0 || isTemp==1 );
1341 assert( isView==0 || isView==1 );
1342 {
1343 static const u8 aCode[] = {
1344 SQLITE_CREATE_TABLE,
1345 SQLITE_CREATE_TEMP_TABLE,
1346 SQLITE_CREATE_VIEW,
1347 SQLITE_CREATE_TEMP_VIEW
1348 };
1349 char *zDb = db->aDb[iDb].zDbSName;
1350 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
1351 goto begin_table_error;
1352 }
1353 if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
1354 zName, 0, zDb) ){
1355 goto begin_table_error;
1356 }
1357 }
1358#endif
1359
1360 /* Make sure the new table name does not collide with an existing
1361 ** index or table name in the same database. Issue an error message if
1362 ** it does. The exception is if the statement being parsed was passed
1363 ** to an sqlite3_declare_vtab() call. In that case only the column names
1364 ** and types will be used, so there is no need to test for namespace
1365 ** collisions.
1366 */
1367 if( !IN_SPECIAL_PARSE ){
1368 char *zDb = db->aDb[iDb].zDbSName;
1369 pTable = sqlite3FindTable(db, zName, zDb);
1370 if( pTable ){
1371 if( !noErr ){
1372 sqlite3ErrorMsg(pParse, "%s %T already exists",
1373 (IsView(pTable)? "view" : "table"), pName);
1374 }else{
1375 assert( !db->init.busy || CORRUPT_DB );
1376 sqlite3CodeVerifySchema(pParse, iDb);
1377 sqlite3ForceNotReadOnly(pParse);
1378 }
1379 goto begin_table_error;
1380 }
1381 if( sqlite3FindIndex(db, zName, zDb)!=0 ){
1382 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
1383 goto begin_table_error;
1384 }
1385 }
1386
1387 pTable = sqlite3DbMallocZero(db, sizeof(Table));
1388 if( pTable==0 ){
1389 assert( db->mallocFailed );
1390 pParse->rc = SQLITE_NOMEM_BKPT;
1391 pParse->nErr++;
1392 goto begin_table_error;
1393 }
1394 pTable->zName = zName;
1395 pTable->iPKey = -1;
1396 pTable->pSchema = db->aDb[iDb].pSchema;
1397 pTable->nTabRef = 1;
1398#ifdef SQLITE_DEFAULT_ROWEST
1399 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
1400#else
1401 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
1402#endif
1403 assert( pParse->pNewTable==0 );
1404 pParse->pNewTable = pTable;
1405
1406 /* Begin generating the code that will insert the table record into
1407 ** the schema table. Note in particular that we must go ahead
1408 ** and allocate the record number for the table entry now. Before any
1409 ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
1410 ** indices to be created and the table record must come before the
1411 ** indices. Hence, the record number for the table must be allocated
1412 ** now.
1413 */
1414 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
1415 int addr1;
1416 int fileFormat;
1417 int reg1, reg2, reg3;
1418 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
1419 static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
1420 sqlite3BeginWriteOperation(pParse, 1, iDb);
1421
1422#ifndef SQLITE_OMIT_VIRTUALTABLE
1423 if( isVirtual ){
1424 sqlite3VdbeAddOp0(v, OP_VBegin);
1425 }
1426#endif
1427
1428 /* If the file format and encoding in the database have not been set,
1429 ** set them now.
1430 */
1431 assert( pParse->isCreate );
1432 reg1 = pParse->u1.cr.regRowid = ++pParse->nMem;
1433 reg2 = pParse->u1.cr.regRoot = ++pParse->nMem;
1434 reg3 = ++pParse->nMem;
1435 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
1436 sqlite3VdbeUsesBtree(v, iDb);
1437 addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
1438 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
1439 1 : SQLITE_MAX_FILE_FORMAT;
1440 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
1441 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, ENC(db));
1442 sqlite3VdbeJumpHere(v, addr1);
1443
1444 /* This just creates a place-holder record in the sqlite_schema table.
1445 ** The record created does not contain anything yet. It will be replaced
1446 ** by the real entry in code generated at sqlite3EndTable().
1447 **
1448 ** The rowid for the new entry is left in register pParse->u1.cr.regRowid.
1449 ** The root page of the new table is left in reg pParse->u1.cr.regRoot.
1450 ** The rowid and root page number values are needed by the code that
1451 ** sqlite3EndTable will generate.
1452 */
1453#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
1454 if( isView || isVirtual ){
1455 sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
1456 }else
1457#endif
1458 {
1459 assert( !pParse->bReturning );
1460 pParse->u1.cr.addrCrTab =
1461 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, reg2, BTREE_INTKEY);
1462 }
1463 sqlite3OpenSchemaTable(pParse, iDb);
1464 sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
1465 sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
1466 sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
1467 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1468 sqlite3VdbeAddOp0(v, OP_Close);
1469 }else if( db->init.imposterTable ){
1470 pTable->tabFlags |= TF_Imposter;
1471 if( db->init.imposterTable>=2 ) pTable->tabFlags |= TF_Readonly;
1472 }
1473
1474 /* Normal (non-error) return. */
1475 return;
1476
1477 /* If an error occurs, we jump here */
1478begin_table_error:
1479 pParse->checkSchema = 1;
1480 sqlite3DbFree(db, zName);
1481 return;
1482}
1483
1484/* Set properties of a table column based on the (magical)
1485** name of the column.
1486*/
1487#if SQLITE_ENABLE_HIDDEN_COLUMNS
1488void sqlite3ColumnPropertiesFromName(Table *pTab, Column *pCol){
1489 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
1490 pCol->colFlags |= COLFLAG_HIDDEN;
1491 if( pTab ) pTab->tabFlags |= TF_HasHidden;
1492 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
1493 pTab->tabFlags |= TF_OOOHidden;
1494 }
1495}
1496#endif
1497
1498/*
1499** Clean up the data structures associated with the RETURNING clause.
1500*/
1501static void sqlite3DeleteReturning(sqlite3 *db, void *pArg){
1502 Returning *pRet = (Returning*)pArg;
1503 Hash *pHash;
1504 pHash = &(db->aDb[1].pSchema->trigHash);
1505 sqlite3HashInsert(pHash, pRet->zName, 0);
1506 sqlite3ExprListDelete(db, pRet->pReturnEL);
1507 sqlite3DbFree(db, pRet);
1508}
1509
1510/*
1511** Add the RETURNING clause to the parse currently underway.
1512**
1513** This routine creates a special TEMP trigger that will fire for each row
1514** of the DML statement. That TEMP trigger contains a single SELECT
1515** statement with a result set that is the argument of the RETURNING clause.
1516** The trigger has the Trigger.bReturning flag and an opcode of
1517** TK_RETURNING instead of TK_SELECT, so that the trigger code generator
1518** knows to handle it specially. The TEMP trigger is automatically
1519** removed at the end of the parse.
1520**
1521** When this routine is called, we do not yet know if the RETURNING clause
1522** is attached to a DELETE, INSERT, or UPDATE, so construct it as a
1523** RETURNING trigger instead. It will then be converted into the appropriate
1524** type on the first call to sqlite3TriggersExist().
1525*/
1526void sqlite3AddReturning(Parse *pParse, ExprList *pList){
1527 Returning *pRet;
1528 Hash *pHash;
1529 sqlite3 *db = pParse->db;
1530 if( pParse->pNewTrigger ){
1531 sqlite3ErrorMsg(pParse, "cannot use RETURNING in a trigger");
1532 }else{
1533 assert( pParse->bReturning==0 || pParse->ifNotExists );
1534 }
1535 pParse->bReturning = 1;
1536 pRet = sqlite3DbMallocZero(db, sizeof(*pRet));
1537 if( pRet==0 ){
1538 sqlite3ExprListDelete(db, pList);
1539 return;
1540 }
1541 assert( !pParse->isCreate );
1542 pParse->u1.d.pReturning = pRet;
1543 pRet->pParse = pParse;
1544 pRet->pReturnEL = pList;
1545 sqlite3ParserAddCleanup(pParse, sqlite3DeleteReturning, pRet);
1546 testcase( pParse->earlyCleanup );
1547 if( db->mallocFailed ) return;
1548 sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
1549 "sqlite_returning_%p", pParse);
1550 pRet->retTrig.zName = pRet->zName;
1551 pRet->retTrig.op = TK_RETURNING;
1552 pRet->retTrig.tr_tm = TRIGGER_AFTER;
1553 pRet->retTrig.bReturning = 1;
1554 pRet->retTrig.pSchema = db->aDb[1].pSchema;
1555 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
1556 pRet->retTrig.step_list = &pRet->retTStep;
1557 pRet->retTStep.op = TK_RETURNING;
1558 pRet->retTStep.pTrig = &pRet->retTrig;
1559 pRet->retTStep.pExprList = pList;
1560 pHash = &(db->aDb[1].pSchema->trigHash);
1561 assert( sqlite3HashFind(pHash, pRet->zName)==0
1562 || pParse->nErr || pParse->ifNotExists );
1563 if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
1564 ==&pRet->retTrig ){
1565 sqlite3OomFault(db);
1566 }
1567}
1568
1569/*
1570** Add a new column to the table currently being constructed.
1571**
1572** The parser calls this routine once for each column declaration
1573** in a CREATE TABLE statement. sqlite3StartTable() gets called
1574** first to get things going. Then this routine is called for each
1575** column.
1576*/
1577void sqlite3AddColumn(Parse *pParse, Token sName, Token sType){
1578 Table *p;
1579 int i;
1580 char *z;
1581 char *zType;
1582 Column *pCol;
1583 sqlite3 *db = pParse->db;
1584 Column *aNew;
1585 u8 eType = COLTYPE_CUSTOM;
1586 u8 szEst = 1;
1587 char affinity = SQLITE_AFF_BLOB;
1588
1589 if( (p = pParse->pNewTable)==0 ) return;
1590 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1591 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
1592 return;
1593 }
1594 if( !IN_RENAME_OBJECT ) sqlite3DequoteToken(&sName);
1595
1596 /* Because keywords GENERATE ALWAYS can be converted into identifiers
1597 ** by the parser, we can sometimes end up with a typename that ends
1598 ** with "generated always". Check for this case and omit the surplus
1599 ** text. */
1600 if( sType.n>=16 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0 ){
1601 u32 nType = sType.n - 6;
1602 while( ALWAYS(nType>0) && sqlite3Isspace(sType.z[nType-1]) ) nType--;
1603 if( nType>=9 && nType<(sType.n - 6)
1604 && sqlite3_strnicmp(sType.z+(nType-9),"generated",9)==0
1605 && (nType==9 || sqlite3Isspace(sType.z[nType-10]))
1606 ){
1607 sType.n = nType - 9;
1608 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
1609 }
1610 }
1611
1612 /* Check for standard typenames. For standard typenames we will
1613 ** set the Column.eType field rather than storing the typename after
1614 ** the column name, in order to save space. */
1615 if( sType.n>=3 ){
1616 sqlite3DequoteToken(&sType);
1617 for(i=0; i<SQLITE_N_STDTYPE; i++){
1618 if( sType.n==sqlite3StdTypeLen[i]
1619 && sqlite3_strnicmp(sType.z, sqlite3StdType[i], sType.n)==0
1620 ){
1621 sType.n = 0;
1622 eType = i+1;
1623 affinity = sqlite3StdTypeAffinity[i];
1624 if( affinity<=SQLITE_AFF_TEXT ) szEst = 5;
1625 break;
1626 }
1627 }
1628 }
1629
1630 z = sqlite3DbMallocRaw(db, (i64)sName.n + 1 + (i64)sType.n + (sType.n>0) );
1631 if( z==0 ) return;
1632 if( IN_RENAME_OBJECT ) sqlite3RenameTokenMap(pParse, (void*)z, &sName);
1633 memcpy(z, sName.z, sName.n);
1634 z[sName.n] = 0;
1635 sqlite3Dequote(z);
1636 if( p->nCol && sqlite3ColumnIndex(p, z)>=0 ){
1637 sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
1638 sqlite3DbFree(db, z);
1639 return;
1640 }
1641 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
1642 if( aNew==0 ){
1643 sqlite3DbFree(db, z);
1644 return;
1645 }
1646 p->aCol = aNew;
1647 pCol = &p->aCol[p->nCol];
1648 memset(pCol, 0, sizeof(p->aCol[0]));
1649 pCol->zCnName = z;
1650 pCol->hName = sqlite3StrIHash(z);
1651 sqlite3ColumnPropertiesFromName(p, pCol);
1652
1653 if( sType.n==0 ){
1654 /* If there is no type specified, columns have the default affinity
1655 ** 'BLOB' with a default size of 4 bytes. */
1656 pCol->affinity = affinity;
1657 pCol->eCType = eType;
1658 pCol->szEst = szEst;
1659#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1660 if( affinity==SQLITE_AFF_BLOB ){
1661 if( 4>=sqlite3GlobalConfig.szSorterRef ){
1662 pCol->colFlags |= COLFLAG_SORTERREF;
1663 }
1664 }
1665#endif
1666 }else{
1667 zType = z + sqlite3Strlen30(z) + 1;
1668 memcpy(zType, sType.z, sType.n);
1669 zType[sType.n] = 0;
1670 sqlite3Dequote(zType);
1671 pCol->affinity = sqlite3AffinityType(zType, pCol);
1672 pCol->colFlags |= COLFLAG_HASTYPE;
1673 }
1674 if( p->nCol<=0xff ){
1675 u8 h = pCol->hName % sizeof(p->aHx);
1676 p->aHx[h] = p->nCol;
1677 }
1678 p->nCol++;
1679 p->nNVCol++;
1680 assert( pParse->isCreate );
1681 pParse->u1.cr.constraintName.n = 0;
1682}
1683
1684/*
1685** This routine is called by the parser while in the middle of
1686** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
1687** been seen on a column. This routine sets the notNull flag on
1688** the column currently under construction.
1689*/
1690void sqlite3AddNotNull(Parse *pParse, int onError){
1691 Table *p;
1692 Column *pCol;
1693 p = pParse->pNewTable;
1694 if( p==0 || NEVER(p->nCol<1) ) return;
1695 pCol = &p->aCol[p->nCol-1];
1696 pCol->notNull = (u8)onError;
1697 p->tabFlags |= TF_HasNotNull;
1698
1699 /* Set the uniqNotNull flag on any UNIQUE or PK indexes already created
1700 ** on this column. */
1701 if( pCol->colFlags & COLFLAG_UNIQUE ){
1702 Index *pIdx;
1703 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
1704 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
1705 if( pIdx->aiColumn[0]==p->nCol-1 ){
1706 pIdx->uniqNotNull = 1;
1707 }
1708 }
1709 }
1710}
1711
1712/*
1713** Scan the column type name zType (length nType) and return the
1714** associated affinity type.
1715**
1716** This routine does a case-independent search of zType for the
1717** substrings in the following table. If one of the substrings is
1718** found, the corresponding affinity is returned. If zType contains
1719** more than one of the substrings, entries toward the top of
1720** the table take priority. For example, if zType is 'BLOBINT',
1721** SQLITE_AFF_INTEGER is returned.
1722**
1723** Substring | Affinity
1724** --------------------------------
1725** 'INT' | SQLITE_AFF_INTEGER
1726** 'CHAR' | SQLITE_AFF_TEXT
1727** 'CLOB' | SQLITE_AFF_TEXT
1728** 'TEXT' | SQLITE_AFF_TEXT
1729** 'BLOB' | SQLITE_AFF_BLOB
1730** 'REAL' | SQLITE_AFF_REAL
1731** 'FLOA' | SQLITE_AFF_REAL
1732** 'DOUB' | SQLITE_AFF_REAL
1733**
1734** If none of the substrings in the above table are found,
1735** SQLITE_AFF_NUMERIC is returned.
1736*/
1737char sqlite3AffinityType(const char *zIn, Column *pCol){
1738 u32 h = 0;
1739 char aff = SQLITE_AFF_NUMERIC;
1740 const char *zChar = 0;
1741
1742 assert( zIn!=0 );
1743 while( zIn[0] ){
1744 u8 x = *(u8*)zIn;
1745 h = (h<<8) + sqlite3UpperToLower[x];
1746 zIn++;
1747 if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
1748 aff = SQLITE_AFF_TEXT;
1749 zChar = zIn;
1750 }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
1751 aff = SQLITE_AFF_TEXT;
1752 }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
1753 aff = SQLITE_AFF_TEXT;
1754 }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
1755 && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
1756 aff = SQLITE_AFF_BLOB;
1757 if( zIn[0]=='(' ) zChar = zIn;
1758#ifndef SQLITE_OMIT_FLOATING_POINT
1759 }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
1760 && aff==SQLITE_AFF_NUMERIC ){
1761 aff = SQLITE_AFF_REAL;
1762 }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
1763 && aff==SQLITE_AFF_NUMERIC ){
1764 aff = SQLITE_AFF_REAL;
1765 }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
1766 && aff==SQLITE_AFF_NUMERIC ){
1767 aff = SQLITE_AFF_REAL;
1768#endif
1769 }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
1770 aff = SQLITE_AFF_INTEGER;
1771 break;
1772 }
1773 }
1774
1775 /* If pCol is not NULL, store an estimate of the field size. The
1776 ** estimate is scaled so that the size of an integer is 1. */
1777 if( pCol ){
1778 int v = 0; /* default size is approx 4 bytes */
1779 if( aff<SQLITE_AFF_NUMERIC ){
1780 if( zChar ){
1781 while( zChar[0] ){
1782 if( sqlite3Isdigit(zChar[0]) ){
1783 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
1784 sqlite3GetInt32(zChar, &v);
1785 break;
1786 }
1787 zChar++;
1788 }
1789 }else{
1790 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
1791 }
1792 }
1793#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1794 if( v>=sqlite3GlobalConfig.szSorterRef ){
1795 pCol->colFlags |= COLFLAG_SORTERREF;
1796 }
1797#endif
1798 v = v/4 + 1;
1799 if( v>255 ) v = 255;
1800 pCol->szEst = v;
1801 }
1802 return aff;
1803}
1804
1805/*
1806** The expression is the default value for the most recently added column
1807** of the table currently under construction.
1808**
1809** Default value expressions must be constant. Raise an exception if this
1810** is not the case.
1811**
1812** This routine is called by the parser while in the middle of
1813** parsing a CREATE TABLE statement.
1814*/
1815void sqlite3AddDefaultValue(
1816 Parse *pParse, /* Parsing context */
1817 Expr *pExpr, /* The parsed expression of the default value */
1818 const char *zStart, /* Start of the default value text */
1819 const char *zEnd /* First character past end of default value text */
1820){
1821 Table *p;
1822 Column *pCol;
1823 sqlite3 *db = pParse->db;
1824 p = pParse->pNewTable;
1825 if( p!=0 ){
1826 int isInit = db->init.busy && db->init.iDb!=1;
1827 pCol = &(p->aCol[p->nCol-1]);
1828 if( !sqlite3ExprIsConstantOrFunction(pExpr, isInit) ){
1829 sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
1830 pCol->zCnName);
1831#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1832 }else if( pCol->colFlags & COLFLAG_GENERATED ){
1833 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1834 testcase( pCol->colFlags & COLFLAG_STORED );
1835 sqlite3ErrorMsg(pParse, "cannot use DEFAULT on a generated column");
1836#endif
1837 }else{
1838 /* A copy of pExpr is used instead of the original, as pExpr contains
1839 ** tokens that point to volatile memory.
1840 */
1841 Expr x, *pDfltExpr;
1842 memset(&x, 0, sizeof(x));
1843 x.op = TK_SPAN;
1844 x.u.zToken = sqlite3DbSpanDup(db, zStart, zEnd);
1845 x.pLeft = pExpr;
1846 x.flags = EP_Skip;
1847 pDfltExpr = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
1848 sqlite3DbFree(db, x.u.zToken);
1849 sqlite3ColumnSetExpr(pParse, p, pCol, pDfltExpr);
1850#ifndef SQLITE_OMIT_AUTHORIZATION
1851 /* Reject unauthorized functions from DEFAULT clauses */
1852 if( db->init.busy==0 && db->xAuth!=0 ){
1853 sqlite3FuncAuth(pParse, pExpr);
1854 }
1855#endif /* SQLITE_OMIT_AUTHORIZER */
1856
1857 }
1858 }
1859 if( IN_RENAME_OBJECT ){
1860 sqlite3RenameExprUnmap(pParse, pExpr);
1861 }
1862 sqlite3ExprDelete(db, pExpr);
1863}
1864
1865/*
1866** Backwards Compatibility Hack:
1867**
1868** Historical versions of SQLite accepted strings as column names in
1869** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
1870**
1871** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
1872** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
1873**
1874** This is goofy. But to preserve backwards compatibility we continue to
1875** accept it. This routine does the necessary conversion. It converts
1876** the expression given in its argument from a TK_STRING into a TK_ID
1877** if the expression is just a TK_STRING with an optional COLLATE clause.
1878** If the expression is anything other than TK_STRING, the expression is
1879** unchanged.
1880*/
1881static void sqlite3StringToId(Expr *p){
1882 if( p->op==TK_STRING ){
1883 p->op = TK_ID;
1884 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
1885 p->pLeft->op = TK_ID;
1886 }
1887}
1888
1889/*
1890** Tag the given column as being part of the PRIMARY KEY
1891*/
1892static void makeColumnPartOfPrimaryKey(Parse *pParse, Column *pCol){
1893 pCol->colFlags |= COLFLAG_PRIMKEY;
1894#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1895 if( pCol->colFlags & COLFLAG_GENERATED ){
1896 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
1897 testcase( pCol->colFlags & COLFLAG_STORED );
1898 sqlite3ErrorMsg(pParse,
1899 "generated columns cannot be part of the PRIMARY KEY");
1900 }
1901#endif
1902}
1903
1904/*
1905** Designate the PRIMARY KEY for the table. pList is a list of names
1906** of columns that form the primary key. If pList is NULL, then the
1907** most recently added column of the table is the primary key.
1908**
1909** A table can have at most one primary key. If the table already has
1910** a primary key (and this is the second primary key) then create an
1911** error.
1912**
1913** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
1914** then we will try to use that column as the rowid. Set the Table.iPKey
1915** field of the table under construction to be the index of the
1916** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
1917** no INTEGER PRIMARY KEY.
1918**
1919** If the key is not an INTEGER PRIMARY KEY, then create a unique
1920** index for the key. No index is created for INTEGER PRIMARY KEYs.
1921*/
1922void sqlite3AddPrimaryKey(
1923 Parse *pParse, /* Parsing context */
1924 ExprList *pList, /* List of field names to be indexed */
1925 int onError, /* What to do with a uniqueness conflict */
1926 int autoInc, /* True if the AUTOINCREMENT keyword is present */
1927 int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
1928){
1929 Table *pTab = pParse->pNewTable;
1930 Column *pCol = 0;
1931 int iCol = -1, i;
1932 int nTerm;
1933 if( pTab==0 ) goto primary_key_exit;
1934 if( pTab->tabFlags & TF_HasPrimaryKey ){
1935 sqlite3ErrorMsg(pParse,
1936 "table \"%s\" has more than one primary key", pTab->zName);
1937 goto primary_key_exit;
1938 }
1939 pTab->tabFlags |= TF_HasPrimaryKey;
1940 if( pList==0 ){
1941 iCol = pTab->nCol - 1;
1942 pCol = &pTab->aCol[iCol];
1943 makeColumnPartOfPrimaryKey(pParse, pCol);
1944 nTerm = 1;
1945 }else{
1946 nTerm = pList->nExpr;
1947 for(i=0; i<nTerm; i++){
1948 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
1949 assert( pCExpr!=0 );
1950 sqlite3StringToId(pCExpr);
1951 if( pCExpr->op==TK_ID ){
1952 assert( !ExprHasProperty(pCExpr, EP_IntValue) );
1953 iCol = sqlite3ColumnIndex(pTab, pCExpr->u.zToken);
1954 if( iCol>=0 ){
1955 pCol = &pTab->aCol[iCol];
1956 makeColumnPartOfPrimaryKey(pParse, pCol);
1957 }
1958 }
1959 }
1960 }
1961 if( nTerm==1
1962 && pCol
1963 && pCol->eCType==COLTYPE_INTEGER
1964 && sortOrder!=SQLITE_SO_DESC
1965 ){
1966 if( IN_RENAME_OBJECT && pList ){
1967 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
1968 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
1969 }
1970 pTab->iPKey = iCol;
1971 pTab->keyConf = (u8)onError;
1972 assert( autoInc==0 || autoInc==1 );
1973 pTab->tabFlags |= autoInc*TF_Autoincrement;
1974 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
1975 (void)sqlite3HasExplicitNulls(pParse, pList);
1976 }else if( autoInc ){
1977#ifndef SQLITE_OMIT_AUTOINCREMENT
1978 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
1979 "INTEGER PRIMARY KEY");
1980#endif
1981 }else{
1982 sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
1983 0, sortOrder, 0, SQLITE_IDXTYPE_PRIMARYKEY);
1984 pList = 0;
1985 }
1986
1987primary_key_exit:
1988 sqlite3ExprListDelete(pParse->db, pList);
1989 return;
1990}
1991
1992/*
1993** Add a new CHECK constraint to the table currently under construction.
1994*/
1995void sqlite3AddCheckConstraint(
1996 Parse *pParse, /* Parsing context */
1997 Expr *pCheckExpr, /* The check expression */
1998 const char *zStart, /* Opening "(" */
1999 const char *zEnd /* Closing ")" */
2000){
2001#ifndef SQLITE_OMIT_CHECK
2002 Table *pTab = pParse->pNewTable;
2003 sqlite3 *db = pParse->db;
2004 if( pTab && !IN_DECLARE_VTAB
2005 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
2006 ){
2007 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
2008 assert( pParse->isCreate );
2009 if( pParse->u1.cr.constraintName.n ){
2010 sqlite3ExprListSetName(pParse, pTab->pCheck,
2011 &pParse->u1.cr.constraintName, 1);
2012 }else{
2013 Token t;
2014 for(zStart++; sqlite3Isspace(zStart[0]); zStart++){}
2015 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
2016 t.z = zStart;
2017 t.n = (int)(zEnd - t.z);
2018 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
2019 }
2020 }else
2021#endif
2022 {
2023 sqlite3ExprDelete(pParse->db, pCheckExpr);
2024 }
2025}
2026
2027/*
2028** Set the collation function of the most recently parsed table column
2029** to the CollSeq given.
2030*/
2031void sqlite3AddCollateType(Parse *pParse, Token *pToken){
2032 Table *p;
2033 int i;
2034 char *zColl; /* Dequoted name of collation sequence */
2035 sqlite3 *db;
2036
2037 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
2038 i = p->nCol-1;
2039 db = pParse->db;
2040 zColl = sqlite3NameFromToken(db, pToken);
2041 if( !zColl ) return;
2042
2043 if( sqlite3LocateCollSeq(pParse, zColl) ){
2044 Index *pIdx;
2045 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
2046
2047 /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
2048 ** then an index may have been created on this column before the
2049 ** collation type was added. Correct this if it is the case.
2050 */
2051 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2052 assert( pIdx->nKeyCol==1 );
2053 if( pIdx->aiColumn[0]==i ){
2054 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
2055 }
2056 }
2057 }
2058 sqlite3DbFree(db, zColl);
2059}
2060
2061/* Change the most recently parsed column to be a GENERATED ALWAYS AS
2062** column.
2063*/
2064void sqlite3AddGenerated(Parse *pParse, Expr *pExpr, Token *pType){
2065#ifndef SQLITE_OMIT_GENERATED_COLUMNS
2066 u8 eType = COLFLAG_VIRTUAL;
2067 Table *pTab = pParse->pNewTable;
2068 Column *pCol;
2069 if( pTab==0 ){
2070 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
2071 goto generated_done;
2072 }
2073 pCol = &(pTab->aCol[pTab->nCol-1]);
2074 if( IN_DECLARE_VTAB ){
2075 sqlite3ErrorMsg(pParse, "virtual tables cannot use computed columns");
2076 goto generated_done;
2077 }
2078 if( pCol->iDflt>0 ) goto generated_error;
2079 if( pType ){
2080 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
2081 /* no-op */
2082 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
2083 eType = COLFLAG_STORED;
2084 }else{
2085 goto generated_error;
2086 }
2087 }
2088 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
2089 pCol->colFlags |= eType;
2090 assert( TF_HasVirtual==COLFLAG_VIRTUAL );
2091 assert( TF_HasStored==COLFLAG_STORED );
2092 pTab->tabFlags |= eType;
2093 if( pCol->colFlags & COLFLAG_PRIMKEY ){
2094 makeColumnPartOfPrimaryKey(pParse, pCol); /* For the error message */
2095 }
2096 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
2097 /* The value of a generated column needs to be a real expression, not
2098 ** just a reference to another column, in order for covering index
2099 ** optimizations to work correctly. So if the value is not an expression,
2100 ** turn it into one by adding a unary "+" operator. */
2101 pExpr = sqlite3PExpr(pParse, TK_UPLUS, pExpr, 0);
2102 }
2103 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
2104 sqlite3ColumnSetExpr(pParse, pTab, pCol, pExpr);
2105 pExpr = 0;
2106 goto generated_done;
2107
2108generated_error:
2109 sqlite3ErrorMsg(pParse, "error in generated column \"%s\"",
2110 pCol->zCnName);
2111generated_done:
2112 sqlite3ExprDelete(pParse->db, pExpr);
2113#else
2114 /* Throw and error for the GENERATED ALWAYS AS clause if the
2115 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
2116 sqlite3ErrorMsg(pParse, "generated columns not supported");
2117 sqlite3ExprDelete(pParse->db, pExpr);
2118#endif
2119}
2120
2121/*
2122** Generate code that will increment the schema cookie.
2123**
2124** The schema cookie is used to determine when the schema for the
2125** database changes. After each schema change, the cookie value
2126** changes. When a process first reads the schema it records the
2127** cookie. Thereafter, whenever it goes to access the database,
2128** it checks the cookie to make sure the schema has not changed
2129** since it was last read.
2130**
2131** This plan is not completely bullet-proof. It is possible for
2132** the schema to change multiple times and for the cookie to be
2133** set back to prior value. But schema changes are infrequent
2134** and the probability of hitting the same cookie value is only
2135** 1 chance in 2^32. So we're safe enough.
2136**
2137** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
2138** the schema-version whenever the schema changes.
2139*/
2140void sqlite3ChangeCookie(Parse *pParse, int iDb){
2141 sqlite3 *db = pParse->db;
2142 Vdbe *v = pParse->pVdbe;
2143 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
2144 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION,
2145 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
2146}
2147
2148/*
2149** Measure the number of characters needed to output the given
2150** identifier. The number returned includes any quotes used
2151** but does not include the null terminator.
2152**
2153** The estimate is conservative. It might be larger that what is
2154** really needed.
2155*/
2156static i64 identLength(const char *z){
2157 i64 n;
2158 for(n=0; *z; n++, z++){
2159 if( *z=='"' ){ n++; }
2160 }
2161 return n + 2;
2162}
2163
2164/*
2165** The first parameter is a pointer to an output buffer. The second
2166** parameter is a pointer to an integer that contains the offset at
2167** which to write into the output buffer. This function copies the
2168** nul-terminated string pointed to by the third parameter, zSignedIdent,
2169** to the specified offset in the buffer and updates *pIdx to refer
2170** to the first byte after the last byte written before returning.
2171**
2172** If the string zSignedIdent consists entirely of alphanumeric
2173** characters, does not begin with a digit and is not an SQL keyword,
2174** then it is copied to the output buffer exactly as it is. Otherwise,
2175** it is quoted using double-quotes.
2176*/
2177static void identPut(char *z, int *pIdx, char *zSignedIdent){
2178 unsigned char *zIdent = (unsigned char*)zSignedIdent;
2179 int i, j, needQuote;
2180 i = *pIdx;
2181
2182 for(j=0; zIdent[j]; j++){
2183 if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
2184 }
2185 needQuote = sqlite3Isdigit(zIdent[0])
2186 || sqlite3KeywordCode(zIdent, j)!=TK_ID
2187 || zIdent[j]!=0
2188 || j==0;
2189
2190 if( needQuote ) z[i++] = '"';
2191 for(j=0; zIdent[j]; j++){
2192 z[i++] = zIdent[j];
2193 if( zIdent[j]=='"' ) z[i++] = '"';
2194 }
2195 if( needQuote ) z[i++] = '"';
2196 z[i] = 0;
2197 *pIdx = i;
2198}
2199
2200/*
2201** Generate a CREATE TABLE statement appropriate for the given
2202** table. Memory to hold the text of the statement is obtained
2203** from sqliteMalloc() and must be freed by the calling function.
2204*/
2205static char *createTableStmt(sqlite3 *db, Table *p){
2206 int i, k, len;
2207 i64 n;
2208 char *zStmt;
2209 char *zSep, *zSep2, *zEnd;
2210 Column *pCol;
2211 n = 0;
2212 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
2213 n += identLength(pCol->zCnName) + 5;
2214 }
2215 n += identLength(p->zName);
2216 if( n<50 ){
2217 zSep = "";
2218 zSep2 = ",";
2219 zEnd = ")";
2220 }else{
2221 zSep = "\n ";
2222 zSep2 = ",\n ";
2223 zEnd = "\n)";
2224 }
2225 n += 35 + 6*p->nCol;
2226 zStmt = sqlite3DbMallocRaw(0, n);
2227 if( zStmt==0 ){
2228 sqlite3OomFault(db);
2229 return 0;
2230 }
2231 assert( n>14 && n<=0x7fffffff );
2232 memcpy(zStmt, "CREATE TABLE ", 13);
2233 k = 13;
2234 identPut(zStmt, &k, p->zName);
2235 zStmt[k++] = '(';
2236 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
2237 static const char * const azType[] = {
2238 /* SQLITE_AFF_BLOB */ "",
2239 /* SQLITE_AFF_TEXT */ " TEXT",
2240 /* SQLITE_AFF_NUMERIC */ " NUM",
2241 /* SQLITE_AFF_INTEGER */ " INT",
2242 /* SQLITE_AFF_REAL */ " REAL",
2243 /* SQLITE_AFF_FLEXNUM */ " NUM",
2244 };
2245 const char *zType;
2246
2247 len = sqlite3Strlen30(zSep);
2248 assert( k+len<n );
2249 memcpy(&zStmt[k], zSep, len);
2250 k += len;
2251 zSep = zSep2;
2252 identPut(zStmt, &k, pCol->zCnName);
2253 assert( k<n );
2254 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
2255 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
2256 testcase( pCol->affinity==SQLITE_AFF_BLOB );
2257 testcase( pCol->affinity==SQLITE_AFF_TEXT );
2258 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
2259 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
2260 testcase( pCol->affinity==SQLITE_AFF_REAL );
2261 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
2262
2263 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
2264 len = sqlite3Strlen30(zType);
2265 assert( pCol->affinity==SQLITE_AFF_BLOB
2266 || pCol->affinity==SQLITE_AFF_FLEXNUM
2267 || pCol->affinity==sqlite3AffinityType(zType, 0) );
2268 assert( k+len<n );
2269 memcpy(&zStmt[k], zType, len);
2270 k += len;
2271 assert( k<=n );
2272 }
2273 len = sqlite3Strlen30(zEnd);
2274 assert( k+len<n );
2275 memcpy(&zStmt[k], zEnd, len+1);
2276 return zStmt;
2277}
2278
2279/*
2280** Resize an Index object to hold N columns total. Return SQLITE_OK
2281** on success and SQLITE_NOMEM on an OOM error.
2282*/
2283static int resizeIndexObject(Parse *pParse, Index *pIdx, int N){
2284 char *zExtra;
2285 u64 nByte;
2286 sqlite3 *db;
2287 if( pIdx->nColumn>=N ) return SQLITE_OK;
2288 db = pParse->db;
2289 assert( N>0 );
2290 assert( N <= SQLITE_MAX_COLUMN*2 /* tag-20250221-1 */ );
2291 testcase( N==2*pParse->db->aLimit[SQLITE_LIMIT_COLUMN] );
2292 assert( pIdx->isResized==0 );
2293 nByte = (sizeof(char*) + sizeof(LogEst) + sizeof(i16) + 1)*(u64)N;
2294 zExtra = sqlite3DbMallocZero(db, nByte);
2295 if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
2296 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
2297 pIdx->azColl = (const char**)zExtra;
2298 zExtra += sizeof(char*)*N;
2299 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
2300 pIdx->aiRowLogEst = (LogEst*)zExtra;
2301 zExtra += sizeof(LogEst)*N;
2302 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
2303 pIdx->aiColumn = (i16*)zExtra;
2304 zExtra += sizeof(i16)*N;
2305 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
2306 pIdx->aSortOrder = (u8*)zExtra;
2307 pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */
2308 pIdx->isResized = 1;
2309 return SQLITE_OK;
2310}
2311
2312/*
2313** Return true if the index pIdx can support a Bloom filter on its
2314** first N columns. Specifically, return true if all of the first N
2315** columns have the BINARY collating sequence or no collating sequence
2316** at all, and return false if there are any non-BINARY collating
2317** seqeuences on any of the first N columns. tag-202607231411
2318*/
2319int sqlite3IndexBloomable(const Index *pIdx, int N){
2320 int i;
2321 assert( pIdx!=0 );
2322 assert( N <= pIdx->nColumn );
2323 for(i=0; i<N; i++){
2324 if( sqlite3StrICmp(pIdx->azColl[i],"BINARY")!=0 ) return 0;
2325 }
2326 return 1;
2327}
2328
2329/*
2330** Estimate the total row width for a table.
2331*/
2332static void estimateTableWidth(Table *pTab){
2333 unsigned wTable = 0;
2334 const Column *pTabCol;
2335 int i;
2336 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
2337 wTable += pTabCol->szEst;
2338 }
2339 if( pTab->iPKey<0 ) wTable++;
2340 pTab->szTabRow = sqlite3LogEst(wTable*4);
2341}
2342
2343/*
2344** Estimate the average size of a row for an index.
2345*/
2346static void estimateIndexWidth(Index *pIdx){
2347 unsigned wIndex = 0;
2348 int i;
2349 const Column *aCol = pIdx->pTable->aCol;
2350 for(i=0; i<pIdx->nColumn; i++){
2351 i16 x = pIdx->aiColumn[i];
2352 assert( x<pIdx->pTable->nCol );
2353 wIndex += x<0 ? 1 : aCol[x].szEst;
2354 }
2355 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
2356}
2357
2358/* Return true if column number x is any of the first nCol entries of aiCol[].
2359** This is used to determine if the column number x appears in any of the
2360** first nCol entries of an index.
2361*/
2362static int hasColumn(const i16 *aiCol, int nCol, int x){
2363 while( nCol-- > 0 ){
2364 if( x==*(aiCol++) ){
2365 return 1;
2366 }
2367 }
2368 return 0;
2369}
2370
2371/*
2372** Return true if any of the first nKey entries of index pIdx exactly
2373** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
2374** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
2375** or may not be the same index as pPk.
2376**
2377** The first nKey entries of pIdx are guaranteed to be ordinary columns,
2378** not a rowid or expression.
2379**
2380** This routine differs from hasColumn() in that both the column and the
2381** collating sequence must match for this routine, but for hasColumn() only
2382** the column name must match.
2383*/
2384static int isDupColumn(Index *pIdx, int nKey, Index *pPk, int iCol){
2385 int i, j;
2386 assert( nKey<=pIdx->nColumn );
2387 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
2388 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
2389 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
2390 assert( pPk->pTable==pIdx->pTable );
2391 testcase( pPk==pIdx );
2392 j = pPk->aiColumn[iCol];
2393 assert( j!=XN_ROWID && j!=XN_EXPR );
2394 for(i=0; i<nKey; i++){
2395 assert( pIdx->aiColumn[i]>=0 || j>=0 );
2396 if( pIdx->aiColumn[i]==j
2397 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
2398 ){
2399 return 1;
2400 }
2401 }
2402 return 0;
2403}
2404
2405/* Recompute the colNotIdxed field of the Index.
2406**
2407** colNotIdxed is a bitmask that has a 0 bit representing each indexed
2408** columns that are within the first 63 columns of the table and a 1 for
2409** all other bits (all columns that are not in the index). The
2410** high-order bit of colNotIdxed is always 1. All unindexed columns
2411** of the table have a 1.
2412**
2413** 2019-10-24: For the purpose of this computation, virtual columns are
2414** not considered to be covered by the index, even if they are in the
2415** index, because we do not trust the logic in whereIndexExprTrans() to be
2416** able to find all instances of a reference to the indexed table column
2417** and convert them into references to the index. Hence we always want
2418** the actual table at hand in order to recompute the virtual column, if
2419** necessary.
2420**
2421** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
2422** to determine if the index is covering index.
2423*/
2424static void recomputeColumnsNotIndexed(Index *pIdx){
2425 Bitmask m = 0;
2426 int j;
2427 Table *pTab = pIdx->pTable;
2428 for(j=pIdx->nColumn-1; j>=0; j--){
2429 int x = pIdx->aiColumn[j];
2430 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
2431 testcase( x==BMS-1 );
2432 testcase( x==BMS-2 );
2433 if( x<BMS-1 ) m |= MASKBIT(x);
2434 }
2435 }
2436 pIdx->colNotIdxed = ~m;
2437 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
2438}
2439
2440/*
2441** This routine runs at the end of parsing a CREATE TABLE statement that
2442** has a WITHOUT ROWID clause. The job of this routine is to convert both
2443** internal schema data structures and the generated VDBE code so that they
2444** are appropriate for a WITHOUT ROWID table instead of a rowid table.
2445** Changes include:
2446**
2447** (1) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
2448** (2) Convert P3 parameter of the OP_CreateBtree from BTREE_INTKEY
2449** into BTREE_BLOBKEY.
2450** (3) Bypass the creation of the sqlite_schema table entry
2451** for the PRIMARY KEY as the primary key index is now
2452** identified by the sqlite_schema table entry of the table itself.
2453** (4) Set the Index.tnum of the PRIMARY KEY Index object in the
2454** schema to the rootpage from the main table.
2455** (5) Add all table columns to the PRIMARY KEY Index object
2456** so that the PRIMARY KEY is a covering index. The surplus
2457** columns are part of KeyInfo.nAllField and are not used for
2458** sorting or lookup or uniqueness checks.
2459** (6) Replace the rowid tail on all automatically generated UNIQUE
2460** indices with the PRIMARY KEY columns.
2461**
2462** For virtual tables, only (1) is performed.
2463*/
2464static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
2465 Index *pIdx;
2466 Index *pPk;
2467 int nPk;
2468 int nExtra;
2469 int i, j;
2470 sqlite3 *db = pParse->db;
2471 Vdbe *v = pParse->pVdbe;
2472
2473 /* Mark every PRIMARY KEY column as NOT NULL (except for imposter tables)
2474 */
2475 if( !db->init.imposterTable ){
2476 for(i=0; i<pTab->nCol; i++){
2477 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
2478 && (pTab->aCol[i].notNull==OE_None)
2479 ){
2480 pTab->aCol[i].notNull = OE_Abort;
2481 }
2482 }
2483 pTab->tabFlags |= TF_HasNotNull;
2484 }
2485
2486 /* Convert the P3 operand of the OP_CreateBtree opcode from BTREE_INTKEY
2487 ** into BTREE_BLOBKEY.
2488 */
2489 assert( !pParse->bReturning );
2490 if( pParse->u1.cr.addrCrTab ){
2491 assert( v );
2492 sqlite3VdbeChangeP3(v, pParse->u1.cr.addrCrTab, BTREE_BLOBKEY);
2493 }
2494
2495 /* Locate the PRIMARY KEY index. Or, if this table was originally
2496 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
2497 */
2498 if( pTab->iPKey>=0 ){
2499 ExprList *pList;
2500 Token ipkToken;
2501 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
2502 pList = sqlite3ExprListAppend(pParse, 0,
2503 sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
2504 if( pList==0 ){
2505 pTab->tabFlags &= ~TF_WithoutRowid;
2506 return;
2507 }
2508 if( IN_RENAME_OBJECT ){
2509 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
2510 }
2511 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
2512 assert( pParse->pNewTable==pTab );
2513 pTab->iPKey = -1;
2514 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
2515 SQLITE_IDXTYPE_PRIMARYKEY);
2516 if( pParse->nErr ){
2517 pTab->tabFlags &= ~TF_WithoutRowid;
2518 return;
2519 }
2520 assert( db->mallocFailed==0 );
2521 pPk = sqlite3PrimaryKeyIndex(pTab);
2522 assert( pPk->nKeyCol==1 );
2523 }else{
2524 pPk = sqlite3PrimaryKeyIndex(pTab);
2525 assert( pPk!=0 );
2526
2527 /*
2528 ** Remove all redundant columns from the PRIMARY KEY. For example, change
2529 ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
2530 ** code assumes the PRIMARY KEY contains no repeated columns.
2531 */
2532 for(i=j=1; i<pPk->nKeyCol; i++){
2533 if( isDupColumn(pPk, j, pPk, i) ){
2534 pPk->nColumn--;
2535 }else{
2536 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
2537 pPk->azColl[j] = pPk->azColl[i];
2538 pPk->aSortOrder[j] = pPk->aSortOrder[i];
2539 pPk->aiColumn[j++] = pPk->aiColumn[i];
2540 }
2541 }
2542 pPk->nKeyCol = j;
2543 }
2544 assert( pPk!=0 );
2545 pPk->isCovering = 1;
2546 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
2547 nPk = pPk->nColumn = pPk->nKeyCol;
2548
2549 /* Bypass the creation of the PRIMARY KEY btree and the sqlite_schema
2550 ** table entry. This is only required if currently generating VDBE
2551 ** code for a CREATE TABLE (not when parsing one as part of reading
2552 ** a database schema). */
2553 if( v && pPk->tnum>0 ){
2554 assert( db->init.busy==0 );
2555 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
2556 }
2557
2558 /* The root page of the PRIMARY KEY is the table root page */
2559 pPk->tnum = pTab->tnum;
2560
2561 /* Update the in-memory representation of all UNIQUE indices by converting
2562 ** the final rowid column into one or more columns of the PRIMARY KEY.
2563 */
2564 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
2565 int n;
2566 if( IsPrimaryKeyIndex(pIdx) ) continue;
2567 for(i=n=0; i<nPk; i++){
2568 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2569 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2570 n++;
2571 }
2572 }
2573 if( n==0 ){
2574 /* This index is a superset of the primary key */
2575 pIdx->nColumn = pIdx->nKeyCol;
2576 continue;
2577 }
2578 if( resizeIndexObject(pParse, pIdx, pIdx->nKeyCol+n) ) return;
2579 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
2580 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
2581 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
2582 pIdx->aiColumn[j] = pPk->aiColumn[i];
2583 pIdx->azColl[j] = pPk->azColl[i];
2584 if( pPk->aSortOrder[i] ){
2585 /* See ticket https://sqlite.org/src/info/bba7b69f9849b5bf */
2586 pIdx->bAscKeyBug = 1;
2587 }
2588 j++;
2589 }
2590 }
2591 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
2592 assert( pIdx->nColumn>=j );
2593 }
2594
2595 /* Add all table columns to the PRIMARY KEY index
2596 */
2597 nExtra = 0;
2598 for(i=0; i<pTab->nCol; i++){
2599 if( !hasColumn(pPk->aiColumn, nPk, i)
2600 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
2601 }
2602 if( resizeIndexObject(pParse, pPk, nPk+nExtra) ) return;
2603 for(i=0, j=nPk; i<pTab->nCol; i++){
2604 if( !hasColumn(pPk->aiColumn, j, i)
2605 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
2606 ){
2607 const char *zColl = sqlite3ColumnColl(&pTab->aCol[i]);
2608 assert( j<pPk->nColumn );
2609 pPk->aiColumn[j] = i;
2610 pPk->azColl[j] = zColl ? zColl : sqlite3StrBINARY;
2611 j++;
2612 }
2613 }
2614 assert( pPk->nColumn==j );
2615 assert( pTab->nNVCol<=j );
2616 recomputeColumnsNotIndexed(pPk);
2617}
2618
2619
2620#ifndef SQLITE_OMIT_VIRTUALTABLE
2621/*
2622** Return true if pTab is a virtual table and zName is a shadow table name
2623** for that virtual table.
2624*/
2625int sqlite3IsShadowTableOf(sqlite3 *db, Table *pTab, const char *zName){
2626 int nName; /* Length of zName */
2627 Module *pMod; /* Module for the virtual table */
2628
2629 if( !IsVirtual(pTab) ) return 0;
2630 nName = sqlite3Strlen30(pTab->zName);
2631 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
2632 if( zName[nName]!='_' ) return 0;
2633 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2634 if( pMod==0 ) return 0;
2635 if( pMod->pModule->iVersion<3 ) return 0;
2636 if( pMod->pModule->xShadowName==0 ) return 0;
2637 return pMod->pModule->xShadowName(zName+nName+1);
2638}
2639#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2640
2641#ifndef SQLITE_OMIT_VIRTUALTABLE
2642/*
2643** Table pTab is a virtual table. If it the virtual table implementation
2644** exists and has an xShadowName method, then loop over all other ordinary
2645** tables within the same schema looking for shadow tables of pTab, and mark
2646** any shadow tables seen using the TF_Shadow flag.
2647*/
2648void sqlite3MarkAllShadowTablesOf(sqlite3 *db, Table *pTab){
2649 int nName; /* Length of pTab->zName */
2650 Module *pMod; /* Module for the virtual table */
2651 HashElem *k; /* For looping through the symbol table */
2652
2653 assert( IsVirtual(pTab) );
2654 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
2655 if( pMod==0 ) return;
2656 if( NEVER(pMod->pModule==0) ) return;
2657 if( pMod->pModule->iVersion<3 ) return;
2658 if( pMod->pModule->xShadowName==0 ) return;
2659 assert( pTab->zName!=0 );
2660 nName = sqlite3Strlen30(pTab->zName);
2661 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
2662 Table *pOther = sqliteHashData(k);
2663 assert( pOther->zName!=0 );
2664 if( !IsOrdinaryTable(pOther) ) continue;
2665 if( pOther->tabFlags & TF_Shadow ) continue;
2666 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
2667 && pOther->zName[nName]=='_'
2668 && pMod->pModule->xShadowName(pOther->zName+nName+1)
2669 ){
2670 pOther->tabFlags |= TF_Shadow;
2671 }
2672 }
2673}
2674#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2675
2676#ifndef SQLITE_OMIT_VIRTUALTABLE
2677/*
2678** Return true if zName is the name of a shadow table of a virtual table
2679** in schema zDb. If zDb is NULL, return true if zName is a shadow table
2680** name of a virtual table in any schema of the database connection.
2681**
2682** Each schema is checked separately. An ordinary table in one schema
2683** (for example, a TEMP table) must not hide a same-named virtual table
2684** in another schema.
2685*/
2686int sqlite3ShadowTableName(sqlite3 *db, const char *zName, const char *zDb){
2687 const char *zTail; /* Pointer to the last "_" in zName */
2688 Table *pTab; /* Table that zName is a shadow of */
2689 char *zCopy; /* Transient copy of zName after last "_" */
2690 int i; /* Loop counter over schemas */
2691 int bRet = 0; /* Return value */
2692 zTail = strrchr(zName, '_');
2693 if( zTail==0 ) return 0;
2694 zCopy = sqlite3DbStrNDup(db, zName, (int)(zTail-zName));
2695 if( zCopy==0 ) return 0;
2696 for(i=0; i<db->nDb && bRet==0; i++){
2697 const char *zSchema = db->aDb[i].zDbSName;
2698 if( zDb && sqlite3DbIsNamed(db, i, zDb)==0 ) continue;
2699 pTab = sqlite3FindTable(db, zCopy, zSchema);
2700 if( pTab && IsVirtual(pTab) ){
2701 bRet = sqlite3IsShadowTableOf(db, pTab, zName);
2702 }
2703 }
2704 sqlite3DbFree(db, zCopy);
2705 return bRet;
2706}
2707#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */
2708
2709
2710#ifdef SQLITE_DEBUG
2711/*
2712** Mark all nodes of an expression as EP_Immutable, indicating that
2713** they should not be changed. Expressions attached to a table or
2714** index definition are tagged this way to help ensure that we do
2715** not pass them into code generator routines by mistake.
2716*/
2717static int markImmutableExprStep(Walker *pWalker, Expr *pExpr){
2718 (void)pWalker;
2719 ExprSetVVAProperty(pExpr, EP_Immutable);
2720 return WRC_Continue;
2721}
2722static void markExprListImmutable(ExprList *pList){
2723 if( pList ){
2724 Walker w;
2725 memset(&w, 0, sizeof(w));
2726 w.xExprCallback = markImmutableExprStep;
2727 w.xSelectCallback = sqlite3SelectWalkNoop;
2728 w.xSelectCallback2 = 0;
2729 sqlite3WalkExprList(&w, pList);
2730 }
2731}
2732#else
2733#define markExprListImmutable(X) /* no-op */
2734#endif /* SQLITE_DEBUG */
2735
2736/*
2737** This routine is called to report the final ")" that terminates
2738** a CREATE TABLE statement.
2739**
2740** The table structure that other action routines have been building
2741** is added to the internal hash tables, assuming no errors have
2742** occurred.
2743**
2744** An entry for the table is made in the schema table on disk, unless
2745** this is a temporary table or db->init.busy==1. When db->init.busy==1
2746** it means we are reading the sqlite_schema table because we just
2747** connected to the database or because the sqlite_schema table has
2748** recently changed, so the entry for this table already exists in
2749** the sqlite_schema table. We do not want to create it again.
2750**
2751** If the pSelect argument is not NULL, it means that this routine
2752** was called to create a table generated from a
2753** "CREATE TABLE ... AS SELECT ..." statement. The column names of
2754** the new table will match the result set of the SELECT.
2755*/
2756void sqlite3EndTable(
2757 Parse *pParse, /* Parse context */
2758 Token *pCons, /* The ',' token after the last column defn. */
2759 Token *pEnd, /* The ')' before options in the CREATE TABLE */
2760 u32 tabOpts, /* Extra table options. Usually 0. */
2761 Select *pSelect /* Select from a "CREATE ... AS SELECT" */
2762){
2763 Table *p; /* The new table */
2764 sqlite3 *db = pParse->db; /* The database connection */
2765 int iDb; /* Database in which the table lives */
2766 Index *pIdx; /* An implied index of the table */
2767
2768 if( pEnd==0 && pSelect==0 ){
2769 return;
2770 }
2771 p = pParse->pNewTable;
2772 if( p==0 ) return;
2773
2774 if( pSelect==0
2775 && sqlite3ShadowTableName(db, p->zName,
2776 db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].zDbSName)
2777 ){
2778 p->tabFlags |= TF_Shadow;
2779 }
2780
2781 /* If the db->init.busy is 1 it means we are reading the SQL off the
2782 ** "sqlite_schema" or "sqlite_temp_schema" table on the disk.
2783 ** So do not write to the disk again. Extract the root page number
2784 ** for the table from the db->init.newTnum field. (The page number
2785 ** should have been put there by the sqliteOpenCb routine.)
2786 **
2787 ** If the root page number is 1, that means this is the sqlite_schema
2788 ** table itself. So mark it read-only.
2789 */
2790 if( db->init.busy ){
2791 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
2792 sqlite3ErrorMsg(pParse, "");
2793 return;
2794 }
2795 p->tnum = db->init.newTnum;
2796 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
2797 }
2798
2799 /* Special processing for tables that include the STRICT keyword:
2800 **
2801 ** * Do not allow custom column datatypes. Every column must have
2802 ** a datatype that is one of INT, INTEGER, REAL, TEXT, or BLOB.
2803 **
2804 ** * If a PRIMARY KEY is defined, other than the INTEGER PRIMARY KEY,
2805 ** then all columns of the PRIMARY KEY must have a NOT NULL
2806 ** constraint.
2807 */
2808 if( tabOpts & TF_Strict ){
2809 int ii;
2810 p->tabFlags |= TF_Strict;
2811 for(ii=0; ii<p->nCol; ii++){
2812 Column *pCol = &p->aCol[ii];
2813 if( pCol->eCType==COLTYPE_CUSTOM ){
2814 if( pCol->colFlags & COLFLAG_HASTYPE ){
2815 sqlite3ErrorMsg(pParse,
2816 "unknown datatype for %s.%s: \"%s\"",
2817 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
2818 );
2819 }else{
2820 sqlite3ErrorMsg(pParse, "missing datatype for %s.%s",
2821 p->zName, pCol->zCnName);
2822 }
2823 return;
2824 }else if( pCol->eCType==COLTYPE_ANY ){
2825 pCol->affinity = SQLITE_AFF_BLOB;
2826 }
2827 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
2828 && p->iPKey!=ii
2829 && pCol->notNull == OE_None
2830 ){
2831 pCol->notNull = OE_Abort;
2832 p->tabFlags |= TF_HasNotNull;
2833 }
2834 }
2835 }
2836
2837 assert( (p->tabFlags & TF_HasPrimaryKey)==0
2838 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
2839 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
2840 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
2841
2842 /* Special processing for WITHOUT ROWID Tables */
2843 if( tabOpts & TF_WithoutRowid ){
2844 if( (p->tabFlags & TF_Autoincrement) ){
2845 sqlite3ErrorMsg(pParse,
2846 "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
2847 return;
2848 }
2849 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
2850 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
2851 return;
2852 }
2853 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
2854 convertToWithoutRowidTable(pParse, p);
2855 }
2856 iDb = sqlite3SchemaToIndex(db, p->pSchema);
2857 assert( iDb>=0 && iDb<=db->nDb );
2858
2859#ifndef SQLITE_OMIT_CHECK
2860 /* Resolve names in all CHECK constraint expressions.
2861 */
2862 if( p->pCheck ){
2863 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
2864 if( pParse->nErr ){
2865 /* If errors are seen, delete the CHECK constraints now, else they might
2866 ** actually be used if PRAGMA writable_schema=ON is set. */
2867 sqlite3ExprListDelete(db, p->pCheck);
2868 p->pCheck = 0;
2869 }else{
2870 markExprListImmutable(p->pCheck);
2871 }
2872 }
2873#endif /* !defined(SQLITE_OMIT_CHECK) */
2874#ifndef SQLITE_OMIT_GENERATED_COLUMNS
2875 if( p->tabFlags & TF_HasGenerated ){
2876 int ii, nNG = 0;
2877 testcase( p->tabFlags & TF_HasVirtual );
2878 testcase( p->tabFlags & TF_HasStored );
2879 for(ii=0; ii<p->nCol; ii++){
2880 u32 colFlags = p->aCol[ii].colFlags;
2881 if( (colFlags & COLFLAG_GENERATED)!=0 ){
2882 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
2883 testcase( colFlags & COLFLAG_VIRTUAL );
2884 testcase( colFlags & COLFLAG_STORED );
2885 if( sqlite3ResolveSelfReference(pParse, p, NC_GenCol, pX, 0) ){
2886 /* If there are errors in resolving the expression, change the
2887 ** expression to a NULL. This prevents code generators that operate
2888 ** on the expression from inserting extra parts into the expression
2889 ** tree that have been allocated from lookaside memory, which is
2890 ** illegal in a schema and will lead to errors or heap corruption
2891 ** when the database connection closes. */
2892 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
2893 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
2894 }
2895 }else{
2896 nNG++;
2897 }
2898 }
2899 if( nNG==0 ){
2900 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
2901 return;
2902 }
2903 }
2904#endif
2905
2906 /* Estimate the average row size for the table and for all implied indices */
2907 estimateTableWidth(p);
2908 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
2909 estimateIndexWidth(pIdx);
2910 }
2911
2912 /* If not initializing, then create a record for the new table
2913 ** in the schema table of the database.
2914 **
2915 ** If this is a TEMPORARY table, write the entry into the auxiliary
2916 ** file instead of into the main database file.
2917 */
2918 if( !db->init.busy ){
2919 int n;
2920 Vdbe *v;
2921 char *zType; /* "view" or "table" */
2922 char *zType2; /* "VIEW" or "TABLE" */
2923 char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
2924
2925 v = sqlite3GetVdbe(pParse);
2926 if( NEVER(v==0) ) return;
2927
2928 sqlite3VdbeAddOp1(v, OP_Close, 0);
2929
2930 /*
2931 ** Initialize zType for the new view or table.
2932 */
2933 if( IsOrdinaryTable(p) ){
2934 /* A regular table */
2935 zType = "table";
2936 zType2 = "TABLE";
2937#ifndef SQLITE_OMIT_VIEW
2938 }else{
2939 /* A view */
2940 zType = "view";
2941 zType2 = "VIEW";
2942#endif
2943 }
2944
2945 /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
2946 ** statement to populate the new table. The root-page number for the
2947 ** new table is in register pParse->u1.cr.regRoot.
2948 **
2949 ** Once the SELECT has been coded by sqlite3Select(), it is in a
2950 ** suitable state to query for the column names and types to be used
2951 ** by the new table.
2952 **
2953 ** A shared-cache write-lock is not required to write to the new table,
2954 ** as a schema-lock must have already been obtained to create it. Since
2955 ** a schema-lock excludes all other database users, the write-lock would
2956 ** be redundant.
2957 */
2958 if( pSelect ){
2959 SelectDest dest; /* Where the SELECT should store results */
2960 int regYield; /* Register holding co-routine entry-point */
2961 int addrTop; /* Top of the co-routine */
2962 int regRec; /* A record to be insert into the new table */
2963 int regRowid; /* Rowid of the next row to insert */
2964 int addrInsLoop; /* Top of the loop for inserting rows */
2965 Table *pSelTab; /* A table that describes the SELECT results */
2966 int iCsr; /* Write cursor on the new table */
2967
2968 if( IN_SPECIAL_PARSE ){
2969 pParse->rc = SQLITE_ERROR;
2970 pParse->nErr++;
2971 return;
2972 }
2973 iCsr = pParse->nTab++;
2974 regYield = ++pParse->nMem;
2975 regRec = ++pParse->nMem;
2976 regRowid = ++pParse->nMem;
2977 sqlite3MayAbort(pParse);
2978 assert( pParse->isCreate );
2979 sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->u1.cr.regRoot, iDb);
2980 sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
2981 addrTop = sqlite3VdbeCurrentAddr(v) + 1;
2982 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
2983 if( pParse->nErr ) return;
2984 pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect, SQLITE_AFF_BLOB);
2985 if( pSelTab==0 ) return;
2986 assert( p->aCol==0 );
2987 p->nCol = p->nNVCol = pSelTab->nCol;
2988 p->aCol = pSelTab->aCol;
2989 pSelTab->nCol = 0;
2990 pSelTab->aCol = 0;
2991 sqlite3DeleteTable(db, pSelTab);
2992 sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
2993 sqlite3Select(pParse, pSelect, &dest);
2994 if( pParse->nErr ) return;
2995 sqlite3VdbeEndCoroutine(v, regYield);
2996 sqlite3VdbeJumpHere(v, addrTop - 1);
2997 addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
2998 VdbeCoverage(v);
2999 sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
3000 sqlite3TableAffinity(v, p, 0);
3001 sqlite3VdbeAddOp2(v, OP_NewRowid, iCsr, regRowid);
3002 sqlite3VdbeAddOp3(v, OP_Insert, iCsr, regRec, regRowid);
3003 sqlite3VdbeGoto(v, addrInsLoop);
3004 sqlite3VdbeJumpHere(v, addrInsLoop);
3005 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
3006 }
3007
3008 /* Compute the complete text of the CREATE statement */
3009 if( pSelect ){
3010 zStmt = createTableStmt(db, p);
3011 }else{
3012 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
3013 n = (int)(pEnd2->z - pParse->sNameToken.z);
3014 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
3015 zStmt = sqlite3MPrintf(db,
3016 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
3017 );
3018 }
3019
3020 /* A slot for the record has already been allocated in the
3021 ** schema table. We just need to update that slot with all
3022 ** the information we've collected.
3023 */
3024 assert( pParse->isCreate );
3025 sqlite3NestedParse(pParse,
3026 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3027 " SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q"
3028 " WHERE rowid=#%d",
3029 db->aDb[iDb].zDbSName,
3030 zType,
3031 p->zName,
3032 p->zName,
3033 pParse->u1.cr.regRoot,
3034 zStmt,
3035 pParse->u1.cr.regRowid
3036 );
3037 sqlite3DbFree(db, zStmt);
3038 sqlite3ChangeCookie(pParse, iDb);
3039
3040#ifndef SQLITE_OMIT_AUTOINCREMENT
3041 /* Check to see if we need to create an sqlite_sequence table for
3042 ** keeping track of autoincrement keys.
3043 */
3044 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
3045 Db *pDb = &db->aDb[iDb];
3046 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3047 if( pDb->pSchema->pSeqTab==0 ){
3048 sqlite3NestedParse(pParse,
3049 "CREATE TABLE %Q.sqlite_sequence(name,seq)",
3050 pDb->zDbSName
3051 );
3052 }
3053 }
3054#endif
3055
3056 /* Reparse everything to update our internal data structures */
3057 sqlite3VdbeAddParseSchemaOp(v, iDb,
3058 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
3059
3060 /* Test for cycles in generated columns and illegal expressions
3061 ** in CHECK constraints and in DEFAULT clauses. */
3062 if( p->tabFlags & TF_HasGenerated ){
3063 sqlite3VdbeAddOp4(v, OP_SqlExec, 0x0001, 0, 0,
3064 sqlite3MPrintf(db, "SELECT*FROM\"%w\".\"%w\"",
3065 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
3066 }
3067 }
3068
3069 /* Add the table to the in-memory representation of the database.
3070 */
3071 if( db->init.busy ){
3072 Table *pOld;
3073 Schema *pSchema = p->pSchema;
3074 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3075 assert( HasRowid(p) || p->iPKey<0 );
3076 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
3077 if( pOld ){
3078 assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
3079 sqlite3OomFault(db);
3080 return;
3081 }
3082 pParse->pNewTable = 0;
3083 db->mDbFlags |= DBFLAG_SchemaChange;
3084
3085 /* If this is the magic sqlite_sequence table used by autoincrement,
3086 ** then record a pointer to this table in the main database structure
3087 ** so that INSERT can find the table easily. */
3088 assert( !pParse->nested );
3089#ifndef SQLITE_OMIT_AUTOINCREMENT
3090 if( strcmp(p->zName, "sqlite_sequence")==0 ){
3091 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3092 p->pSchema->pSeqTab = p;
3093 }
3094#endif
3095 }
3096
3097#ifndef SQLITE_OMIT_ALTERTABLE
3098 if( !pSelect && IsOrdinaryTable(p) ){
3099 assert( pCons && pEnd );
3100 if( pCons->z==0 ){
3101 pCons = pEnd;
3102 }
3103 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
3104 }
3105#endif
3106}
3107
3108#ifndef SQLITE_OMIT_VIEW
3109/*
3110** The parser calls this routine in order to create a new VIEW
3111*/
3112void sqlite3CreateView(
3113 Parse *pParse, /* The parsing context */
3114 Token *pBegin, /* The CREATE token that begins the statement */
3115 Token *pName1, /* The token that holds the name of the view */
3116 Token *pName2, /* The token that holds the name of the view */
3117 ExprList *pCNames, /* Optional list of view column names */
3118 Select *pSelect, /* A SELECT statement that will become the new view */
3119 int isTemp, /* TRUE for a TEMPORARY view */
3120 int noErr /* Suppress error messages if VIEW already exists */
3121){
3122 Table *p;
3123 int n;
3124 const char *z;
3125 Token sEnd;
3126 DbFixer sFix;
3127 Token *pName = 0;
3128 int iDb;
3129 sqlite3 *db = pParse->db;
3130
3131 if( pParse->nVar>0 ){
3132 sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
3133 goto create_view_fail;
3134 }
3135 sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
3136 p = pParse->pNewTable;
3137 if( p==0 || pParse->nErr ) goto create_view_fail;
3138
3139 /* Legacy versions of SQLite allowed the use of the magic "rowid" column
3140 ** on a view, even though views do not have rowids. The following flag
3141 ** setting fixes this problem. But the fix can be disabled by compiling
3142 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
3143 ** depend upon the old buggy behavior. The ability can also be toggled
3144 ** using sqlite3_config(SQLITE_CONFIG_ROWID_IN_VIEW,...) */
3145#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3146 p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
3147#else
3148 p->tabFlags |= TF_NoVisibleRowid; /* Never allow rowid in view */
3149#endif
3150
3151 sqlite3TwoPartName(pParse, pName1, pName2, &pName);
3152 iDb = sqlite3SchemaToIndex(db, p->pSchema);
3153 assert( iDb>=0 && iDb<db->nDb );
3154 sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
3155 if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
3156
3157 /* Make a copy of the entire SELECT statement that defines the view.
3158 ** This will force all the Expr.token.z values to be dynamically
3159 ** allocated rather than point to the input string - which means that
3160 ** they will persist after the current sqlite3_exec() call returns.
3161 */
3162 pSelect->selFlags |= SF_View;
3163 if( IN_RENAME_OBJECT ){
3164 p->u.view.pSelect = pSelect;
3165 pSelect = 0;
3166 }else{
3167 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
3168 }
3169 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
3170 p->eTabType = TABTYP_VIEW;
3171 if( db->mallocFailed ) goto create_view_fail;
3172
3173 /* Locate the end of the CREATE VIEW statement. Make sEnd point to
3174 ** the end.
3175 */
3176 sEnd = pParse->sLastToken;
3177 assert( sEnd.z[0]!=0 || sEnd.n==0 );
3178 if( sEnd.z[0]!=';' ){
3179 sEnd.z += sEnd.n;
3180 }
3181 sEnd.n = 0;
3182 n = (int)(sEnd.z - pBegin->z);
3183 assert( n>0 );
3184 z = pBegin->z;
3185 while( sqlite3Isspace(z[n-1]) ){ n--; }
3186 sEnd.z = &z[n-1];
3187 sEnd.n = 1;
3188
3189 /* Use sqlite3EndTable() to add the view to the schema table */
3190 sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
3191
3192create_view_fail:
3193 sqlite3SelectDelete(db, pSelect);
3194 if( IN_RENAME_OBJECT ){
3195 sqlite3RenameExprlistUnmap(pParse, pCNames);
3196 }
3197 sqlite3ExprListDelete(db, pCNames);
3198 return;
3199}
3200#endif /* SQLITE_OMIT_VIEW */
3201
3202#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
3203/*
3204** The Table structure pTable is really a VIEW. Fill in the names of
3205** the columns of the view in the pTable structure. Return non-zero if
3206** there are errors. If an error is seen an error message is left
3207** in pParse->zErrMsg.
3208*/
3209static SQLITE_NOINLINE int viewGetColumnNames(Parse *pParse, Table *pTable){
3210 Table *pSelTab; /* A fake table from which we get the result set */
3211 Select *pSel; /* Copy of the SELECT that implements the view */
3212 int nErr = 0; /* Number of errors encountered */
3213 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
3214#ifndef SQLITE_OMIT_VIRTUALTABLE
3215 int rc;
3216#endif
3217#ifndef SQLITE_OMIT_AUTHORIZATION
3218 sqlite3_xauth xAuth; /* Saved xAuth pointer */
3219#endif
3220
3221 assert( pTable );
3222
3223#ifndef SQLITE_OMIT_VIRTUALTABLE
3224 if( IsVirtual(pTable) ){
3225 db->nSchemaLock++;
3226 rc = sqlite3VtabCallConnect(pParse, pTable);
3227 db->nSchemaLock--;
3228 return rc;
3229 }
3230#endif
3231
3232#ifndef SQLITE_OMIT_VIEW
3233 /* A positive nCol means the columns names for this view are
3234 ** already known. This routine is not called unless either the
3235 ** table is virtual or nCol is zero.
3236 */
3237 assert( pTable->nCol<=0 );
3238
3239 /* A negative nCol is a special marker meaning that we are currently
3240 ** trying to compute the column names. If we enter this routine with
3241 ** a negative nCol, it means two or more views form a loop, like this:
3242 **
3243 ** CREATE VIEW one AS SELECT * FROM two;
3244 ** CREATE VIEW two AS SELECT * FROM one;
3245 **
3246 ** Actually, the error above is now caught prior to reaching this point.
3247 ** But the following test is still important as it does come up
3248 ** in the following:
3249 **
3250 ** CREATE TABLE main.ex1(a);
3251 ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
3252 ** SELECT * FROM temp.ex1;
3253 */
3254 if( pTable->nCol<0 ){
3255 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
3256 return 1;
3257 }
3258 assert( pTable->nCol>=0 );
3259
3260 /* If we get this far, it means we need to compute the table names.
3261 ** Note that the call to sqlite3ResultSetOfSelect() will expand any
3262 ** "*" elements in the results set of the view and will assign cursors
3263 ** to the elements of the FROM clause. But we do not want these changes
3264 ** to be permanent. So the computation is done on a copy of the SELECT
3265 ** statement that defines the view.
3266 */
3267 assert( IsView(pTable) );
3268 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
3269 if( pSel ){
3270 u8 eParseMode = pParse->eParseMode;
3271 int nTab = pParse->nTab;
3272 int nSelect = pParse->nSelect;
3273 pParse->eParseMode = PARSE_MODE_NORMAL;
3274 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
3275 pTable->nCol = -1;
3276 DisableLookaside;
3277#ifndef SQLITE_OMIT_AUTHORIZATION
3278 xAuth = db->xAuth;
3279 db->xAuth = 0;
3280 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3281 db->xAuth = xAuth;
3282#else
3283 pSelTab = sqlite3ResultSetOfSelect(pParse, pSel, SQLITE_AFF_NONE);
3284#endif
3285 pParse->nTab = nTab;
3286 pParse->nSelect = nSelect;
3287 if( pSelTab==0 ){
3288 pTable->nCol = 0;
3289 nErr++;
3290 }else if( pTable->pCheck ){
3291 /* CREATE VIEW name(arglist) AS ...
3292 ** The names of the columns in the table are taken from
3293 ** arglist which is stored in pTable->pCheck. The pCheck field
3294 ** normally holds CHECK constraints on an ordinary table, but for
3295 ** a VIEW it holds the list of column names.
3296 */
3297 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
3298 &pTable->nCol, &pTable->aCol);
3299 if( pParse->nErr==0
3300 && pTable->nCol==pSel->pEList->nExpr
3301 ){
3302 assert( db->mallocFailed==0 );
3303 sqlite3SubqueryColumnTypes(pParse, pTable, pSel, SQLITE_AFF_NONE);
3304 }
3305 }else{
3306 /* CREATE VIEW name AS... without an argument list. Construct
3307 ** the column names from the SELECT statement that defines the view.
3308 */
3309 assert( pTable->aCol==0 );
3310 pTable->nCol = pSelTab->nCol;
3311 pTable->aCol = pSelTab->aCol;
3312 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
3313 pSelTab->nCol = 0;
3314 pSelTab->aCol = 0;
3315 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
3316 }
3317 pTable->nNVCol = pTable->nCol;
3318 sqlite3DeleteTable(db, pSelTab);
3319 sqlite3SelectDelete(db, pSel);
3320 EnableLookaside;
3321 pParse->eParseMode = eParseMode;
3322 } else {
3323 nErr++;
3324 }
3325 pTable->pSchema->schemaFlags |= DB_UnresetViews;
3326 if( db->mallocFailed ){
3327 sqlite3DeleteColumnNames(db, pTable);
3328 }
3329#endif /* SQLITE_OMIT_VIEW */
3330 return nErr + pParse->nErr;
3331}
3332int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
3333 assert( pTable!=0 );
3334 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
3335 return viewGetColumnNames(pParse, pTable);
3336}
3337#endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
3338
3339#ifndef SQLITE_OMIT_VIEW
3340/*
3341** Clear the column names from every VIEW in database idx.
3342*/
3343static void sqliteViewResetAll(sqlite3 *db, int idx){
3344 HashElem *i;
3345 assert( sqlite3SchemaMutexHeld(db, idx, 0) );
3346 if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
3347 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
3348 Table *pTab = sqliteHashData(i);
3349 if( IsView(pTab) ){
3350 sqlite3DeleteColumnNames(db, pTab);
3351 }
3352 }
3353 DbClearProperty(db, idx, DB_UnresetViews);
3354}
3355#else
3356# define sqliteViewResetAll(A,B)
3357#endif /* SQLITE_OMIT_VIEW */
3358
3359/*
3360** This function is called by the VDBE to adjust the internal schema
3361** used by SQLite when the btree layer moves a table root page. The
3362** root-page of a table or index in database iDb has changed from iFrom
3363** to iTo.
3364**
3365** Ticket #1728: The symbol table might still contain information
3366** on tables and/or indices that are the process of being deleted.
3367** If you are unlucky, one of those deleted indices or tables might
3368** have the same rootpage number as the real table or index that is
3369** being moved. So we cannot stop searching after the first match
3370** because the first match might be for one of the deleted indices
3371** or tables and not the table/index that is actually being moved.
3372** We must continue looping until all tables and indices with
3373** rootpage==iFrom have been converted to have a rootpage of iTo
3374** in order to be certain that we got the right one.
3375*/
3376#ifndef SQLITE_OMIT_AUTOVACUUM
3377void sqlite3RootPageMoved(sqlite3 *db, int iDb, Pgno iFrom, Pgno iTo){
3378 HashElem *pElem;
3379 Hash *pHash;
3380 Db *pDb;
3381
3382 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
3383 pDb = &db->aDb[iDb];
3384 pHash = &pDb->pSchema->tblHash;
3385 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3386 Table *pTab = sqliteHashData(pElem);
3387 if( pTab->tnum==iFrom ){
3388 pTab->tnum = iTo;
3389 }
3390 }
3391 pHash = &pDb->pSchema->idxHash;
3392 for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
3393 Index *pIdx = sqliteHashData(pElem);
3394 if( pIdx->tnum==iFrom ){
3395 pIdx->tnum = iTo;
3396 }
3397 }
3398}
3399#endif
3400
3401/*
3402** Write code to erase the table with root-page iTable from database iDb.
3403** Also write code to modify the sqlite_schema table and internal schema
3404** if a root-page of another table is moved by the btree-layer whilst
3405** erasing iTable (this can happen with an auto-vacuum database).
3406*/
3407static void destroyRootPage(Parse *pParse, int iTable, int iDb){
3408 Vdbe *v = sqlite3GetVdbe(pParse);
3409 int r1 = sqlite3GetTempReg(pParse);
3410 if( iTable<2 ) sqlite3ErrorMsg(pParse, "corrupt schema");
3411 sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
3412 sqlite3MayAbort(pParse);
3413#ifndef SQLITE_OMIT_AUTOVACUUM
3414 /* OP_Destroy stores an in integer r1. If this integer
3415 ** is non-zero, then it is the root page number of a table moved to
3416 ** location iTable. The following code modifies the sqlite_schema table to
3417 ** reflect this.
3418 **
3419 ** The "#NNN" in the SQL is a special constant that means whatever value
3420 ** is in register NNN. See grammar rules associated with the TK_REGISTER
3421 ** token for additional information.
3422 */
3423 sqlite3NestedParse(pParse,
3424 "UPDATE %Q." LEGACY_SCHEMA_TABLE
3425 " SET rootpage=%d WHERE #%d AND rootpage=#%d",
3426 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
3427#endif
3428 sqlite3ReleaseTempReg(pParse, r1);
3429}
3430
3431/*
3432** Write VDBE code to erase table pTab and all associated indices on disk.
3433** Code to update the sqlite_schema tables and internal schema definitions
3434** in case a root-page belonging to another table is moved by the btree layer
3435** is also added (this can happen with an auto-vacuum database).
3436*/
3437static void destroyTable(Parse *pParse, Table *pTab){
3438 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
3439 ** is not defined), then it is important to call OP_Destroy on the
3440 ** table and index root-pages in order, starting with the numerically
3441 ** largest root-page number. This guarantees that none of the root-pages
3442 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
3443 ** following were coded:
3444 **
3445 ** OP_Destroy 4 0
3446 ** ...
3447 ** OP_Destroy 5 0
3448 **
3449 ** and root page 5 happened to be the largest root-page number in the
3450 ** database, then root page 5 would be moved to page 4 by the
3451 ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
3452 ** a free-list page.
3453 */
3454 Pgno iTab = pTab->tnum;
3455 Pgno iDestroyed = 0;
3456
3457 while( 1 ){
3458 Index *pIdx;
3459 Pgno iLargest = 0;
3460
3461 if( iDestroyed==0 || iTab<iDestroyed ){
3462 iLargest = iTab;
3463 }
3464 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
3465 Pgno iIdx = pIdx->tnum;
3466 assert( pIdx->pSchema==pTab->pSchema );
3467 if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
3468 iLargest = iIdx;
3469 }
3470 }
3471 if( iLargest==0 ){
3472 return;
3473 }else{
3474 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
3475 assert( iDb>=0 && iDb<pParse->db->nDb );
3476 destroyRootPage(pParse, iLargest, iDb);
3477 iDestroyed = iLargest;
3478 }
3479 }
3480}
3481
3482/*
3483** Remove entries from the sqlite_statN tables (for N in (1,2,3))
3484** after a DROP INDEX or DROP TABLE command.
3485*/
3486static void sqlite3ClearStatTables(
3487 Parse *pParse, /* The parsing context */
3488 int iDb, /* The database number */
3489 const char *zType, /* "idx" or "tbl" */
3490 const char *zName /* Name of index or table */
3491){
3492 int i;
3493 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
3494 for(i=1; i<=4; i++){
3495 char zTab[24];
3496 sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
3497 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
3498 sqlite3NestedParse(pParse,
3499 "DELETE FROM %Q.%s WHERE %s=%Q",
3500 zDbName, zTab, zType, zName
3501 );
3502 }
3503 }
3504}
3505
3506/*
3507** Generate code to drop a table.
3508*/
3509void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
3510 Vdbe *v;
3511 sqlite3 *db = pParse->db;
3512 Trigger *pTrigger;
3513 Db *pDb = &db->aDb[iDb];
3514
3515 v = sqlite3GetVdbe(pParse);
3516 assert( v!=0 );
3517 sqlite3BeginWriteOperation(pParse, 1, iDb);
3518
3519#ifndef SQLITE_OMIT_VIRTUALTABLE
3520 if( IsVirtual(pTab) ){
3521 sqlite3VdbeAddOp0(v, OP_VBegin);
3522 }
3523#endif
3524
3525 /* Drop all triggers associated with the table being dropped. Code
3526 ** is generated to remove entries from sqlite_schema and/or
3527 ** sqlite_temp_schema if required.
3528 */
3529 pTrigger = sqlite3TriggerList(pParse, pTab);
3530 while( pTrigger ){
3531 assert( pTrigger->pSchema==pTab->pSchema ||
3532 pTrigger->pSchema==db->aDb[1].pSchema );
3533 sqlite3DropTriggerPtr(pParse, pTrigger);
3534 pTrigger = pTrigger->pNext;
3535 }
3536
3537#ifndef SQLITE_OMIT_AUTOINCREMENT
3538 /* Remove any entries of the sqlite_sequence table associated with
3539 ** the table being dropped. This is done before the table is dropped
3540 ** at the btree level, in case the sqlite_sequence table needs to
3541 ** move as a result of the drop (can happen in auto-vacuum mode).
3542 */
3543 if( pTab->tabFlags & TF_Autoincrement ){
3544 sqlite3NestedParse(pParse,
3545 "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
3546 pDb->zDbSName, pTab->zName
3547 );
3548 }
3549#endif
3550
3551 /* Drop all entries in the schema table that refer to the
3552 ** table. The program name loops through the schema table and deletes
3553 ** every row that refers to a table of the same name as the one being
3554 ** dropped. Triggers are handled separately because a trigger can be
3555 ** created in the temp database that refers to a table in another
3556 ** database.
3557 */
3558 sqlite3NestedParse(pParse,
3559 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE
3560 " WHERE tbl_name=%Q and type!='trigger'",
3561 pDb->zDbSName, pTab->zName);
3562 if( !isView && !IsVirtual(pTab) ){
3563 destroyTable(pParse, pTab);
3564 }
3565
3566 /* Remove the table entry from SQLite's internal schema and modify
3567 ** the schema cookie.
3568 */
3569 if( IsVirtual(pTab) ){
3570 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
3571 sqlite3MayAbort(pParse);
3572 }
3573 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
3574 sqlite3ChangeCookie(pParse, iDb);
3575 sqliteViewResetAll(db, iDb);
3576}
3577
3578/*
3579** Return TRUE if shadow tables should be read-only in the current
3580** context.
3581*/
3582int sqlite3ReadOnlyShadowTables(sqlite3 *db){
3583#ifndef SQLITE_OMIT_VIRTUALTABLE
3584 if( (db->flags & SQLITE_Defensive)!=0
3585 && db->pVtabCtx==0
3586 && db->nVdbeExec==0
3587 && !sqlite3VtabInSync(db)
3588 ){
3589 return 1;
3590 }
3591#endif
3592 return 0;
3593}
3594
3595/*
3596** Return true if it is not allowed to drop the given table
3597*/
3598static int tableMayNotBeDropped(sqlite3 *db, Table *pTab){
3599 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
3600 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
3601 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
3602 return 1;
3603 }
3604 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
3605 return 1;
3606 }
3607 if( pTab->tabFlags & TF_Eponymous ){
3608 return 1;
3609 }
3610 return 0;
3611}
3612
3613/*
3614** This routine is called to do the work of a DROP TABLE statement.
3615** pName is the name of the table to be dropped.
3616*/
3617void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
3618 Table *pTab;
3619 Vdbe *v;
3620 sqlite3 *db = pParse->db;
3621 int iDb;
3622
3623 if( db->mallocFailed ){
3624 goto exit_drop_table;
3625 }
3626 assert( pParse->nErr==0 );
3627 assert( pName->nSrc==1 );
3628 assert( pName->a[0].fg.fixedSchema==0 );
3629 assert( pName->a[0].fg.isSubquery==0 );
3630 if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
3631 if( noErr ) db->suppressErr++;
3632 assert( isView==0 || isView==LOCATE_VIEW );
3633 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
3634 if( noErr ) db->suppressErr--;
3635
3636 if( pTab==0 ){
3637 if( noErr ){
3638 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
3639 sqlite3ForceNotReadOnly(pParse);
3640 }
3641 goto exit_drop_table;
3642 }
3643 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
3644 assert( iDb>=0 && iDb<db->nDb );
3645
3646 /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
3647 ** it is initialized.
3648 */
3649 if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
3650 goto exit_drop_table;
3651 }
3652#ifndef SQLITE_OMIT_AUTHORIZATION
3653 {
3654 int code;
3655 const char *zTab = SCHEMA_TABLE(iDb);
3656 const char *zDb = db->aDb[iDb].zDbSName;
3657 const char *zArg2 = 0;
3658 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
3659 goto exit_drop_table;
3660 }
3661 if( isView ){
3662 if( !OMIT_TEMPDB && iDb==1 ){
3663 code = SQLITE_DROP_TEMP_VIEW;
3664 }else{
3665 code = SQLITE_DROP_VIEW;
3666 }
3667#ifndef SQLITE_OMIT_VIRTUALTABLE
3668 }else if( IsVirtual(pTab) ){
3669 code = SQLITE_DROP_VTABLE;
3670 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
3671#endif
3672 }else{
3673 if( !OMIT_TEMPDB && iDb==1 ){
3674 code = SQLITE_DROP_TEMP_TABLE;
3675 }else{
3676 code = SQLITE_DROP_TABLE;
3677 }
3678 }
3679 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
3680 goto exit_drop_table;
3681 }
3682 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
3683 goto exit_drop_table;
3684 }
3685 }
3686#endif
3687 if( tableMayNotBeDropped(db, pTab) ){
3688 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
3689 goto exit_drop_table;
3690 }
3691
3692#ifndef SQLITE_OMIT_VIEW
3693 /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
3694 ** on a table.
3695 */
3696 if( isView && !IsView(pTab) ){
3697 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
3698 goto exit_drop_table;
3699 }
3700 if( !isView && IsView(pTab) ){
3701 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
3702 goto exit_drop_table;
3703 }
3704#endif
3705
3706 /* Generate code to remove the table from the schema table
3707 ** on disk.
3708 */
3709 v = sqlite3GetVdbe(pParse);
3710 if( v ){
3711 sqlite3BeginWriteOperation(pParse, 1, iDb);
3712 if( !isView ){
3713 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
3714 sqlite3FkDropTable(pParse, pName, pTab);
3715 }
3716 sqlite3CodeDropTable(pParse, pTab, iDb, isView);
3717 }
3718
3719exit_drop_table:
3720 sqlite3SrcListDelete(db, pName);
3721}
3722
3723/*
3724** This routine is called to create a new foreign key on the table
3725** currently under construction. pFromCol determines which columns
3726** in the current table point to the foreign key. If pFromCol==0 then
3727** connect the key to the last column inserted. pTo is the name of
3728** the table referred to (a.k.a the "parent" table). pToCol is a list
3729** of tables in the parent pTo table. flags contains all
3730** information about the conflict resolution algorithms specified
3731** in the ON DELETE, ON UPDATE and ON INSERT clauses.
3732**
3733** An FKey structure is created and added to the table currently
3734** under construction in the pParse->pNewTable field.
3735**
3736** The foreign key is set for IMMEDIATE processing. A subsequent call
3737** to sqlite3DeferForeignKey() might change this to DEFERRED.
3738*/
3739void sqlite3CreateForeignKey(
3740 Parse *pParse, /* Parsing context */
3741 ExprList *pFromCol, /* Columns in this table that point to other table */
3742 Token *pTo, /* Name of the other table */
3743 ExprList *pToCol, /* Columns in the other table */
3744 int flags /* Conflict resolution algorithms. */
3745){
3746 sqlite3 *db = pParse->db;
3747#ifndef SQLITE_OMIT_FOREIGN_KEY
3748 FKey *pFKey = 0;
3749 FKey *pNextTo;
3750 Table *p = pParse->pNewTable;
3751 i64 nByte;
3752 int i;
3753 int nCol;
3754 char *z;
3755
3756 assert( pTo!=0 );
3757 if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
3758 if( pFromCol==0 ){
3759 int iCol = p->nCol-1;
3760 if( NEVER(iCol<0) ) goto fk_end;
3761 if( pToCol && pToCol->nExpr!=1 ){
3762 sqlite3ErrorMsg(pParse, "foreign key on %s"
3763 " should reference only one column of table %T",
3764 p->aCol[iCol].zCnName, pTo);
3765 goto fk_end;
3766 }
3767 nCol = 1;
3768 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
3769 sqlite3ErrorMsg(pParse,
3770 "number of columns in foreign key does not match the number of "
3771 "columns in the referenced table");
3772 goto fk_end;
3773 }else{
3774 nCol = pFromCol->nExpr;
3775 }
3776 nByte = SZ_FKEY(nCol) + pTo->n + 1;
3777 if( pToCol ){
3778 for(i=0; i<pToCol->nExpr; i++){
3779 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
3780 }
3781 }
3782 pFKey = sqlite3DbMallocZero(db, nByte );
3783 if( pFKey==0 ){
3784 goto fk_end;
3785 }
3786 pFKey->pFrom = p;
3787 assert( IsOrdinaryTable(p) );
3788 pFKey->pNextFrom = p->u.tab.pFKey;
3789 z = (char*)&pFKey->aCol[nCol];
3790 pFKey->zTo = z;
3791 if( IN_RENAME_OBJECT ){
3792 sqlite3RenameTokenMap(pParse, (void*)z, pTo);
3793 }
3794 memcpy(z, pTo->z, pTo->n);
3795 z[pTo->n] = 0;
3796 sqlite3Dequote(z);
3797 z += pTo->n+1;
3798 pFKey->nCol = nCol;
3799 if( pFromCol==0 ){
3800 pFKey->aCol[0].iFrom = p->nCol-1;
3801 }else{
3802 for(i=0; i<nCol; i++){
3803 int j;
3804 for(j=0; j<p->nCol; j++){
3805 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
3806 pFKey->aCol[i].iFrom = j;
3807 break;
3808 }
3809 }
3810 if( j>=p->nCol ){
3811 sqlite3ErrorMsg(pParse,
3812 "unknown column \"%s\" in foreign key definition",
3813 pFromCol->a[i].zEName);
3814 goto fk_end;
3815 }
3816 if( IN_RENAME_OBJECT ){
3817 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
3818 }
3819 }
3820 }
3821 if( pToCol ){
3822 for(i=0; i<nCol; i++){
3823 int n = sqlite3Strlen30(pToCol->a[i].zEName);
3824 pFKey->aCol[i].zCol = z;
3825 if( IN_RENAME_OBJECT ){
3826 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
3827 }
3828 memcpy(z, pToCol->a[i].zEName, n);
3829 z[n] = 0;
3830 z += n+1;
3831 }
3832 }
3833 pFKey->isDeferred = 0;
3834 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
3835 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
3836
3837 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
3838 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
3839 pFKey->zTo, (void *)pFKey
3840 );
3841 if( pNextTo==pFKey ){
3842 sqlite3OomFault(db);
3843 goto fk_end;
3844 }
3845 if( pNextTo ){
3846 assert( pNextTo->pPrevTo==0 );
3847 pFKey->pNextTo = pNextTo;
3848 pNextTo->pPrevTo = pFKey;
3849 }
3850
3851 /* Link the foreign key to the table as the last step.
3852 */
3853 assert( IsOrdinaryTable(p) );
3854 p->u.tab.pFKey = pFKey;
3855 pFKey = 0;
3856
3857fk_end:
3858 sqlite3DbFree(db, pFKey);
3859#endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
3860 sqlite3ExprListDelete(db, pFromCol);
3861 sqlite3ExprListDelete(db, pToCol);
3862}
3863
3864/*
3865** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
3866** clause is seen as part of a foreign key definition. The isDeferred
3867** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
3868** The behavior of the most recently created foreign key is adjusted
3869** accordingly.
3870*/
3871void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
3872#ifndef SQLITE_OMIT_FOREIGN_KEY
3873 Table *pTab;
3874 FKey *pFKey;
3875 if( (pTab = pParse->pNewTable)==0 ) return;
3876 if( NEVER(!IsOrdinaryTable(pTab)) ) return;
3877 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
3878 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
3879 pFKey->isDeferred = (u8)isDeferred;
3880#endif
3881}
3882
3883/*
3884** Generate code that will erase and refill index *pIdx. This is
3885** used to initialize a newly created index or to recompute the
3886** content of an index in response to a REINDEX command.
3887**
3888** if memRootPage is not negative, it means that the index is newly
3889** created. The register specified by memRootPage contains the
3890** root page number of the index. If memRootPage is negative, then
3891** the index already exists and must be cleared before being refilled and
3892** the root page number of the index is taken from pIndex->tnum.
3893*/
3894static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
3895 Table *pTab = pIndex->pTable; /* The table that is indexed */
3896 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
3897 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
3898 int iSorter; /* Cursor opened by OpenSorter (if in use) */
3899 int addr1; /* Address of top of loop */
3900 int addr2; /* Address to jump to for next iteration */
3901 Pgno tnum; /* Root page of index */
3902 int iPartIdxLabel; /* Jump to this label to skip a row */
3903 Vdbe *v; /* Generate code into this virtual machine */
3904 KeyInfo *pKey; /* KeyInfo for index */
3905 int regRecord; /* Register holding assembled index record */
3906 sqlite3 *db = pParse->db; /* The database connection */
3907 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
3908
3909#ifndef SQLITE_OMIT_AUTHORIZATION
3910 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
3911 db->aDb[iDb].zDbSName ) ){
3912 return;
3913 }
3914#endif
3915
3916 /* Require a write-lock on the table to perform this operation */
3917 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
3918
3919 v = sqlite3GetVdbe(pParse);
3920 if( v==0 ) return;
3921 if( memRootPage>=0 ){
3922 tnum = (Pgno)memRootPage;
3923 }else{
3924 tnum = pIndex->tnum;
3925 }
3926 pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
3927 assert( pKey!=0 || pParse->nErr );
3928
3929 /* Open the sorter cursor if we are to use one. */
3930 iSorter = pParse->nTab++;
3931 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
3932 sqlite3KeyInfoRef(pKey), P4_KEYINFO);
3933
3934 /* Open the table. Loop through all rows of the table, inserting index
3935 ** records into the sorter. */
3936 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
3937 addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
3938 regRecord = sqlite3GetTempReg(pParse);
3939 sqlite3MultiWrite(pParse);
3940
3941 sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
3942 sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
3943 sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
3944 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
3945 sqlite3VdbeJumpHere(v, addr1);
3946 if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
3947 sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, (int)tnum, iDb,
3948 (char *)pKey, P4_KEYINFO);
3949 sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
3950
3951 addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
3952 if( IsUniqueIndex(pIndex) ){
3953 int j2 = sqlite3VdbeGoto(v, 1);
3954 addr2 = sqlite3VdbeCurrentAddr(v);
3955 sqlite3VdbeVerifyAbortable(v, OE_Abort);
3956 sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
3957 pIndex->nKeyCol); VdbeCoverage(v);
3958 sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
3959 sqlite3VdbeJumpHere(v, j2);
3960 }else{
3961 /* Most CREATE INDEX and REINDEX statements that are not UNIQUE can not
3962 ** abort. The exception is if one of the indexed expressions contains a
3963 ** user function that throws an exception when it is evaluated. But the
3964 ** overhead of adding a statement journal to a CREATE INDEX statement is
3965 ** very small (since most of the pages written do not contain content that
3966 ** needs to be restored if the statement aborts), so we call
3967 ** sqlite3MayAbort() for all CREATE INDEX statements. */
3968 sqlite3MayAbort(pParse);
3969 addr2 = sqlite3VdbeCurrentAddr(v);
3970 }
3971 sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
3972 if( !pIndex->bAscKeyBug ){
3973 /* This OP_SeekEnd opcode makes index insert for a REINDEX go much
3974 ** faster by avoiding unnecessary seeks. But the optimization does
3975 ** not work for UNIQUE constraint indexes on WITHOUT ROWID tables
3976 ** with DESC primary keys, since those indexes have there keys in
3977 ** a different order from the main table.
3978 ** See ticket: https://sqlite.org/src/info/bba7b69f9849b5bf
3979 */
3980 sqlite3VdbeAddOp1(v, OP_SeekEnd, iIdx);
3981 }
3982 sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
3983 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
3984 sqlite3ReleaseTempReg(pParse, regRecord);
3985 sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
3986 sqlite3VdbeJumpHere(v, addr1);
3987
3988 sqlite3VdbeAddOp1(v, OP_Close, iTab);
3989 sqlite3VdbeAddOp1(v, OP_Close, iIdx);
3990 sqlite3VdbeAddOp1(v, OP_Close, iSorter);
3991}
3992
3993/*
3994** Allocate heap space to hold an Index object with nCol columns.
3995**
3996** Increase the allocation size to provide an extra nExtra bytes
3997** of 8-byte aligned space after the Index object and return a
3998** pointer to this extra space in *ppExtra.
3999*/
4000Index *sqlite3AllocateIndexObject(
4001 sqlite3 *db, /* Database connection */
4002 int nCol, /* Total number of columns in the index */
4003 int nExtra, /* Number of bytes of extra space to alloc */
4004 char **ppExtra /* Pointer to the "extra" space */
4005){
4006 Index *p; /* Allocated index object */
4007 i64 nByte; /* Bytes of space for Index object + arrays */
4008
4009 assert( nCol <= 2*db->aLimit[SQLITE_LIMIT_COLUMN] );
4010 nByte = ROUND8(sizeof(Index)) + /* Index structure */
4011 ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
4012 ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
4013 sizeof(i16)*nCol + /* Index.aiColumn */
4014 sizeof(u8)*nCol); /* Index.aSortOrder */
4015 p = sqlite3DbMallocZero(db, nByte + nExtra);
4016 if( p ){
4017 char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
4018 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
4019 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
4020 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
4021 p->aSortOrder = (u8*)pExtra;
4022 assert( nCol>0 );
4023 p->nColumn = (u16)nCol;
4024 p->nKeyCol = (u16)(nCol - 1);
4025 *ppExtra = ((char*)p) + nByte;
4026 }
4027 return p;
4028}
4029
4030/*
4031** If expression list pList contains an expression that was parsed with
4032** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
4033** pParse and return non-zero. Otherwise, return zero.
4034*/
4035int sqlite3HasExplicitNulls(Parse *pParse, ExprList *pList){
4036 if( pList ){
4037 int i;
4038 for(i=0; i<pList->nExpr; i++){
4039 if( pList->a[i].fg.bNulls ){
4040 u8 sf = pList->a[i].fg.sortFlags;
4041 sqlite3ErrorMsg(pParse, "unsupported use of NULLS %s",
4042 (sf==0 || sf==3) ? "FIRST" : "LAST"
4043 );
4044 return 1;
4045 }
4046 }
4047 }
4048 return 0;
4049}
4050
4051/*
4052** Create a new index for an SQL table. pName1.pName2 is the name of the index
4053** and pTblList is the name of the table that is to be indexed. Both will
4054** be NULL for a primary key or an index that is created to satisfy a
4055** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
4056** as the table to be indexed. pParse->pNewTable is a table that is
4057** currently being constructed by a CREATE TABLE statement.
4058**
4059** pList is a list of columns to be indexed. pList will be NULL if this
4060** is a primary key or unique-constraint on the most recent column added
4061** to the table currently under construction.
4062*/
4063void sqlite3CreateIndex(
4064 Parse *pParse, /* All information about this parse */
4065 Token *pName1, /* First part of index name. May be NULL */
4066 Token *pName2, /* Second part of index name. May be NULL */
4067 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
4068 ExprList *pList, /* A list of columns to be indexed */
4069 int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
4070 Token *pStart, /* The CREATE token that begins this statement */
4071 Expr *pPIWhere, /* WHERE clause for partial indices */
4072 int sortOrder, /* Sort order of primary key when pList==NULL */
4073 int ifNotExist, /* Omit error if index already exists */
4074 u8 idxType /* The index type */
4075){
4076 Table *pTab = 0; /* Table to be indexed */
4077 Index *pIndex = 0; /* The index to be created */
4078 char *zName = 0; /* Name of the index */
4079 int nName; /* Number of characters in zName */
4080 int i, j;
4081 DbFixer sFix; /* For assigning database names to pTable */
4082 int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
4083 sqlite3 *db = pParse->db;
4084 Db *pDb; /* The specific table containing the indexed database */
4085 int iDb; /* Index of the database that is being written */
4086 Token *pName = 0; /* Unqualified name of the index to create */
4087 struct ExprList_item *pListItem; /* For looping over pList */
4088 int nExtra = 0; /* Space allocated for zExtra[] */
4089 int nExtraCol; /* Number of extra columns needed */
4090 char *zExtra = 0; /* Extra space after the Index object */
4091 Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
4092
4093 assert( db->pParse==pParse );
4094 if( pParse->nErr ){
4095 goto exit_create_index;
4096 }
4097 assert( db->mallocFailed==0 );
4098 if( IN_DECLARE_VTAB && idxType!=SQLITE_IDXTYPE_PRIMARYKEY ){
4099 goto exit_create_index;
4100 }
4101 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4102 goto exit_create_index;
4103 }
4104 if( sqlite3HasExplicitNulls(pParse, pList) ){
4105 goto exit_create_index;
4106 }
4107
4108 /*
4109 ** Find the table that is to be indexed. Return early if not found.
4110 */
4111 if( pTblName!=0 ){
4112
4113 /* Use the two-part index name to determine the database
4114 ** to search for the table. 'Fix' the table name to this db
4115 ** before looking up the table.
4116 */
4117 assert( pName1 && pName2 );
4118 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
4119 if( iDb<0 ) goto exit_create_index;
4120 assert( pName && pName->z );
4121
4122#ifndef SQLITE_OMIT_TEMPDB
4123 /* If the index name was unqualified, check if the table
4124 ** is a temp table. If so, set the database to 1. Do not do this
4125 ** if initializing a database schema, if ALTER TABLE is reparsing an
4126 ** existing index, or if VACUUM is recreating the indexes of a
4127 ** database. */
4128 if( !db->init.busy
4129 && !IN_RENAME_OBJECT
4130 && (db->mDbFlags & DBFLAG_Vacuum)==0
4131 ){
4132 pTab = sqlite3SrcListLookup(pParse, pTblName);
4133 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
4134 iDb = 1;
4135 }
4136 }
4137#endif
4138
4139 sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
4140 if( sqlite3FixSrcList(&sFix, pTblName) ){
4141 /* Because the parser constructs pTblName from a single identifier,
4142 ** sqlite3FixSrcList can never fail. */
4143 assert(0);
4144 }
4145 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
4146 assert( db->mallocFailed==0 || pTab==0 );
4147 if( pTab==0 ) goto exit_create_index;
4148 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
4149 sqlite3ErrorMsg(pParse,
4150 "cannot create a TEMP index on non-TEMP table \"%s\"",
4151 pTab->zName);
4152 goto exit_create_index;
4153 }
4154 if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
4155 }else{
4156 assert( pName==0 );
4157 assert( pStart==0 );
4158 pTab = pParse->pNewTable;
4159 if( !pTab ) goto exit_create_index;
4160 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
4161 }
4162 pDb = &db->aDb[iDb];
4163
4164 assert( pTab!=0 );
4165 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
4166 && db->init.busy==0
4167 && pTblName!=0
4168 ){
4169 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
4170 goto exit_create_index;
4171 }
4172#ifndef SQLITE_OMIT_VIEW
4173 if( IsView(pTab) ){
4174 sqlite3ErrorMsg(pParse, "views may not be indexed");
4175 goto exit_create_index;
4176 }
4177#endif
4178#ifndef SQLITE_OMIT_VIRTUALTABLE
4179 if( IsVirtual(pTab) ){
4180 sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
4181 goto exit_create_index;
4182 }
4183#endif
4184
4185 /*
4186 ** Find the name of the index. Make sure there is not already another
4187 ** index or table with the same name.
4188 **
4189 ** Exception: If we are reading the names of permanent indices from the
4190 ** sqlite_schema table (because some other process changed the schema) and
4191 ** one of the index names collides with the name of a temporary table or
4192 ** index, then we will continue to process this index.
4193 **
4194 ** If pName==0 it means that we are
4195 ** dealing with a primary key or UNIQUE constraint. We have to invent our
4196 ** own name.
4197 */
4198 if( pName ){
4199 zName = sqlite3NameFromToken(db, pName);
4200 if( zName==0 ) goto exit_create_index;
4201 assert( pName->z!=0 );
4202 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName, "index",
4203 pTab->zName, db->aDb[iDb].zDbSName)
4204 ){
4205 goto exit_create_index;
4206 }
4207 if( !IN_RENAME_OBJECT ){
4208 if( !db->init.busy ){
4209 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
4210 sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
4211 goto exit_create_index;
4212 }
4213 }
4214 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
4215 if( !ifNotExist ){
4216 sqlite3ErrorMsg(pParse, "index %s already exists", zName);
4217 }else if( db->init.busy ){
4218 sqlite3ErrorMsg(pParse,""); /* corruptSchema() will do the error */
4219 }else{
4220 sqlite3CodeVerifySchema(pParse, iDb);
4221 sqlite3ForceNotReadOnly(pParse);
4222 }
4223 goto exit_create_index;
4224 }
4225 }
4226 }else{
4227 int n;
4228 Index *pLoop;
4229 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
4230 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
4231 if( zName==0 ){
4232 goto exit_create_index;
4233 }
4234
4235 /* Automatic index names generated from within sqlite3_declare_vtab()
4236 ** must have names that are distinct from normal automatic index names.
4237 ** The following statement converts "sqlite3_autoindex..." into
4238 ** "sqlite3_butoindex..." in order to make the names distinct.
4239 ** The "vtab_err.test" test demonstrates the need of this statement. */
4240 if( IN_SPECIAL_PARSE ) zName[7]++;
4241 }
4242
4243 /* Check for authorization to create an index.
4244 */
4245#ifndef SQLITE_OMIT_AUTHORIZATION
4246 if( !IN_RENAME_OBJECT ){
4247 const char *zDb = pDb->zDbSName;
4248 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
4249 goto exit_create_index;
4250 }
4251 i = SQLITE_CREATE_INDEX;
4252 if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
4253 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
4254 goto exit_create_index;
4255 }
4256 }
4257#endif
4258
4259 /* If pList==0, it means this routine was called to make a primary
4260 ** key out of the last column added to the table under construction.
4261 ** So create a fake list to simulate this.
4262 */
4263 if( pList==0 ){
4264 Token prevCol;
4265 Column *pCol = &pTab->aCol[pTab->nCol-1];
4266 pCol->colFlags |= COLFLAG_UNIQUE;
4267 sqlite3TokenInit(&prevCol, pCol->zCnName);
4268 pList = sqlite3ExprListAppend(pParse, 0,
4269 sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
4270 if( pList==0 ) goto exit_create_index;
4271 assert( pList->nExpr==1 );
4272 sqlite3ExprListSetSortOrder(pList, sortOrder, SQLITE_SO_UNDEFINED);
4273 }else{
4274 sqlite3ExprListCheckLength(pParse, pList, "index");
4275 if( pParse->nErr ) goto exit_create_index;
4276 }
4277
4278 /* Figure out how many bytes of space are required to store explicitly
4279 ** specified collation sequence names.
4280 */
4281 for(i=0; i<pList->nExpr; i++){
4282 Expr *pExpr = pList->a[i].pExpr;
4283 assert( pExpr!=0 );
4284 if( pExpr->op==TK_COLLATE ){
4285 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4286 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
4287 }
4288 }
4289
4290 /*
4291 ** Allocate the index structure.
4292 */
4293 nName = sqlite3Strlen30(zName);
4294 nExtraCol = pPk ? pPk->nKeyCol : 1;
4295 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
4296 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
4297 nName + nExtra + 1, &zExtra);
4298 if( db->mallocFailed ){
4299 goto exit_create_index;
4300 }
4301 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
4302 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
4303 pIndex->zName = zExtra;
4304 zExtra += nName + 1;
4305 memcpy(pIndex->zName, zName, nName+1);
4306 pIndex->pTable = pTab;
4307 pIndex->onError = (u8)onError;
4308 pIndex->uniqNotNull = onError!=OE_None;
4309 pIndex->idxType = idxType;
4310 pIndex->pSchema = db->aDb[iDb].pSchema;
4311 pIndex->nKeyCol = pList->nExpr;
4312 if( pPIWhere ){
4313 sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
4314 pIndex->pPartIdxWhere = pPIWhere;
4315 pPIWhere = 0;
4316 }
4317 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
4318
4319 /* Check to see if we should honor DESC requests on index columns
4320 */
4321 if( pDb->pSchema->file_format>=4 ){
4322 sortOrderMask = -1; /* Honor DESC */
4323 }else{
4324 sortOrderMask = 0; /* Ignore DESC */
4325 }
4326
4327 /* Analyze the list of expressions that form the terms of the index and
4328 ** report any errors. In the common case where the expression is exactly
4329 ** a table column, store that column in aiColumn[]. For general expressions,
4330 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
4331 **
4332 ** TODO: Issue a warning if two or more columns of the index are identical.
4333 ** TODO: Issue a warning if the table primary key is used as part of the
4334 ** index key.
4335 */
4336 pListItem = pList->a;
4337 if( IN_RENAME_OBJECT ){
4338 pIndex->aColExpr = pList;
4339 pList = 0;
4340 }
4341 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
4342 Expr *pCExpr; /* The i-th index expression */
4343 int requestedSortOrder; /* ASC or DESC on the i-th expression */
4344 const char *zColl; /* Collation sequence name */
4345
4346 sqlite3StringToId(pListItem->pExpr);
4347 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
4348 if( pParse->nErr ) goto exit_create_index;
4349 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
4350 if( pCExpr->op!=TK_COLUMN ){
4351 if( pTab==pParse->pNewTable ){
4352 sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
4353 "UNIQUE constraints");
4354 goto exit_create_index;
4355 }
4356 if( pIndex->aColExpr==0 ){
4357 pIndex->aColExpr = pList;
4358 pList = 0;
4359 }
4360 j = XN_EXPR;
4361 pIndex->aiColumn[i] = XN_EXPR;
4362 pIndex->uniqNotNull = 0;
4363 pIndex->bHasExpr = 1;
4364 }else{
4365 j = pCExpr->iColumn;
4366 assert( j<=0x7fff );
4367 if( j<0 ){
4368 j = pTab->iPKey;
4369 }else{
4370 if( pTab->aCol[j].notNull==0 ){
4371 pIndex->uniqNotNull = 0;
4372 }
4373 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
4374 pIndex->bHasVCol = 1;
4375 pIndex->bHasExpr = 1;
4376 }
4377 }
4378 pIndex->aiColumn[i] = (i16)j;
4379 }
4380 zColl = 0;
4381 if( pListItem->pExpr->op==TK_COLLATE ){
4382 int nColl;
4383 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
4384 zColl = pListItem->pExpr->u.zToken;
4385 nColl = sqlite3Strlen30(zColl) + 1;
4386 assert( nExtra>=nColl );
4387 memcpy(zExtra, zColl, nColl);
4388 zColl = zExtra;
4389 zExtra += nColl;
4390 nExtra -= nColl;
4391 }else if( j>=0 ){
4392 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
4393 }
4394 if( !zColl ) zColl = sqlite3StrBINARY;
4395 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
4396 goto exit_create_index;
4397 }
4398 pIndex->azColl[i] = zColl;
4399 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
4400 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
4401 }
4402
4403 /* Append the table key to the end of the index. For WITHOUT ROWID
4404 ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
4405 ** normal tables (when pPk==0) this will be the rowid.
4406 */
4407 if( pPk ){
4408 for(j=0; j<pPk->nKeyCol; j++){
4409 int x = pPk->aiColumn[j];
4410 assert( x>=0 );
4411 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
4412 pIndex->nColumn--;
4413 }else{
4414 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
4415 pIndex->aiColumn[i] = x;
4416 pIndex->azColl[i] = pPk->azColl[j];
4417 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
4418 i++;
4419 }
4420 }
4421 assert( i==pIndex->nColumn );
4422 }else{
4423 pIndex->aiColumn[i] = XN_ROWID;
4424 pIndex->azColl[i] = sqlite3StrBINARY;
4425 }
4426 sqlite3DefaultRowEst(pIndex);
4427 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
4428
4429 /* If this index contains every column of its table, then mark
4430 ** it as a covering index */
4431 assert( HasRowid(pTab)
4432 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
4433 recomputeColumnsNotIndexed(pIndex);
4434 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
4435 pIndex->isCovering = 1;
4436 for(j=0; j<pTab->nCol; j++){
4437 if( j==pTab->iPKey ) continue;
4438 if( sqlite3TableColumnToIndex(pIndex,j)>=0 ) continue;
4439 pIndex->isCovering = 0;
4440 break;
4441 }
4442 }
4443
4444 if( pTab==pParse->pNewTable ){
4445 /* This routine has been called to create an automatic index as a
4446 ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
4447 ** a PRIMARY KEY or UNIQUE clause following the column definitions.
4448 ** i.e. one of:
4449 **
4450 ** CREATE TABLE t(x PRIMARY KEY, y);
4451 ** CREATE TABLE t(x, y, UNIQUE(x, y));
4452 **
4453 ** Either way, check to see if the table already has such an index. If
4454 ** so, don't bother creating this one. This only applies to
4455 ** automatically created indices. Users can do as they wish with
4456 ** explicit indices.
4457 **
4458 ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
4459 ** (and thus suppressing the second one) even if they have different
4460 ** sort orders.
4461 **
4462 ** If there are different collating sequences or if the columns of
4463 ** the constraint occur in different orders, then the constraints are
4464 ** considered distinct and both result in separate indices.
4465 */
4466 Index *pIdx;
4467 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
4468 int k;
4469 assert( IsUniqueIndex(pIdx) );
4470 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
4471 assert( IsUniqueIndex(pIndex) );
4472
4473 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
4474 for(k=0; k<pIdx->nKeyCol; k++){
4475 const char *z1;
4476 const char *z2;
4477 assert( pIdx->aiColumn[k]>=0 );
4478 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
4479 z1 = pIdx->azColl[k];
4480 z2 = pIndex->azColl[k];
4481 if( sqlite3StrICmp(z1, z2) ) break;
4482 }
4483 if( k==pIdx->nKeyCol ){
4484 if( pIdx->onError!=pIndex->onError ){
4485 /* This constraint creates the same index as a previous
4486 ** constraint specified somewhere in the CREATE TABLE statement.
4487 ** However the ON CONFLICT clauses are different. If both this
4488 ** constraint and the previous equivalent constraint have explicit
4489 ** ON CONFLICT clauses this is an error. Otherwise, use the
4490 ** explicitly specified behavior for the index.
4491 */
4492 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
4493 sqlite3ErrorMsg(pParse,
4494 "conflicting ON CONFLICT clauses specified", 0);
4495 }
4496 if( pIdx->onError==OE_Default ){
4497 pIdx->onError = pIndex->onError;
4498 }
4499 }
4500 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
4501 if( IN_RENAME_OBJECT ){
4502 pIndex->pNext = pParse->pNewIndex;
4503 pParse->pNewIndex = pIndex;
4504 pIndex = 0;
4505 }
4506 goto exit_create_index;
4507 }
4508 }
4509 }
4510
4511 if( !IN_RENAME_OBJECT ){
4512
4513 /* Link the new Index structure to its table and to the other
4514 ** in-memory database structures.
4515 */
4516 assert( pParse->nErr==0 );
4517 if( db->init.busy ){
4518 Index *p;
4519 assert( !IN_SPECIAL_PARSE );
4520 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
4521 if( pTblName!=0 ){
4522 pIndex->tnum = db->init.newTnum;
4523 if( sqlite3IndexHasDuplicateRootPage(pIndex) ){
4524 sqlite3ErrorMsg(pParse, "invalid rootpage");
4525 pParse->rc = SQLITE_CORRUPT_BKPT;
4526 goto exit_create_index;
4527 }
4528 }
4529 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
4530 pIndex->zName, pIndex);
4531 if( p ){
4532 assert( p==pIndex ); /* Malloc must have failed */
4533 sqlite3OomFault(db);
4534 goto exit_create_index;
4535 }
4536 db->mDbFlags |= DBFLAG_SchemaChange;
4537 }
4538
4539 /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
4540 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
4541 ** emit code to allocate the index rootpage on disk and make an entry for
4542 ** the index in the sqlite_schema table and populate the index with
4543 ** content. But, do not do this if we are simply reading the sqlite_schema
4544 ** table to parse the schema, or if this index is the PRIMARY KEY index
4545 ** of a WITHOUT ROWID table.
4546 **
4547 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
4548 ** or UNIQUE index in a CREATE TABLE statement. Since the table
4549 ** has just been created, it contains no data and the index initialization
4550 ** step can be skipped.
4551 */
4552 else if( HasRowid(pTab) || pTblName!=0 ){
4553 Vdbe *v;
4554 char *zStmt;
4555 int iMem = ++pParse->nMem;
4556
4557 v = sqlite3GetVdbe(pParse);
4558 if( v==0 ) goto exit_create_index;
4559
4560 sqlite3BeginWriteOperation(pParse, 1, iDb);
4561
4562 /* Create the rootpage for the index using CreateIndex. But before
4563 ** doing so, code a Noop instruction and store its address in
4564 ** Index.tnum. This is required in case this index is actually a
4565 ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
4566 ** that case the convertToWithoutRowidTable() routine will replace
4567 ** the Noop with a Goto to jump over the VDBE code generated below. */
4568 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
4569 sqlite3VdbeAddOp3(v, OP_CreateBtree, iDb, iMem, BTREE_BLOBKEY);
4570
4571 /* Gather the complete text of the CREATE INDEX statement into
4572 ** the zStmt variable
4573 */
4574 assert( pName!=0 || pStart==0 );
4575 if( pStart ){
4576 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
4577 if( pName->z[n-1]==';' ) n--;
4578 /* A named index with an explicit CREATE INDEX statement */
4579 zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
4580 onError==OE_None ? "" : " UNIQUE", n, pName->z);
4581 }else{
4582 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
4583 /* zStmt = sqlite3MPrintf(""); */
4584 zStmt = 0;
4585 }
4586
4587 /* Add an entry in sqlite_schema for this index
4588 */
4589 sqlite3NestedParse(pParse,
4590 "INSERT INTO %Q." LEGACY_SCHEMA_TABLE " VALUES('index',%Q,%Q,#%d,%Q);",
4591 db->aDb[iDb].zDbSName,
4592 pIndex->zName,
4593 pTab->zName,
4594 iMem,
4595 zStmt
4596 );
4597 sqlite3DbFree(db, zStmt);
4598
4599 /* Fill the index with data and reparse the schema. Code an OP_Expire
4600 ** to invalidate all pre-compiled statements.
4601 */
4602 if( pTblName ){
4603 sqlite3RefillIndex(pParse, pIndex, iMem);
4604 sqlite3ChangeCookie(pParse, iDb);
4605 sqlite3VdbeAddParseSchemaOp(v, iDb,
4606 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
4607 sqlite3VdbeAddOp2(v, OP_Expire, 0, 1);
4608 }
4609
4610 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
4611 }
4612 }
4613 if( db->init.busy || pTblName==0 ){
4614 pIndex->pNext = pTab->pIndex;
4615 pTab->pIndex = pIndex;
4616 pIndex = 0;
4617 }
4618 else if( IN_RENAME_OBJECT ){
4619 assert( pParse->pNewIndex==0 );
4620 pParse->pNewIndex = pIndex;
4621 pIndex = 0;
4622 }
4623
4624 /* Clean up before exiting */
4625exit_create_index:
4626 if( pIndex ) sqlite3FreeIndex(db, pIndex);
4627 if( pTab ){
4628 /* Ensure all REPLACE indexes on pTab are at the end of the pIndex list.
4629 ** The list was already ordered when this routine was entered, so at this
4630 ** point at most a single index (the newly added index) will be out of
4631 ** order. So we have to reorder at most one index. */
4632 Index **ppFrom;
4633 Index *pThis;
4634 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
4635 Index *pNext;
4636 if( pThis->onError!=OE_Replace ) continue;
4637 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
4638 *ppFrom = pNext;
4639 pThis->pNext = pNext->pNext;
4640 pNext->pNext = pThis;
4641 ppFrom = &pNext->pNext;
4642 }
4643 break;
4644 }
4645#ifdef SQLITE_DEBUG
4646 /* Verify that all REPLACE indexes really are now at the end
4647 ** of the index list. In other words, no other index type ever
4648 ** comes after a REPLACE index on the list. */
4649 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
4650 assert( pThis->onError!=OE_Replace
4651 || pThis->pNext==0
4652 || pThis->pNext->onError==OE_Replace );
4653 }
4654#endif
4655 }
4656 sqlite3ExprDelete(db, pPIWhere);
4657 sqlite3ExprListDelete(db, pList);
4658 sqlite3SrcListDelete(db, pTblName);
4659 sqlite3DbFree(db, zName);
4660}
4661
4662/*
4663** Fill the Index.aiRowEst[] array with default information - information
4664** to be used when we have not run the ANALYZE command.
4665**
4666** aiRowEst[0] is supposed to contain the number of elements in the index.
4667** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
4668** number of rows in the table that match any particular value of the
4669** first column of the index. aiRowEst[2] is an estimate of the number
4670** of rows that match any particular combination of the first 2 columns
4671** of the index. And so forth. It must always be the case that
4672*
4673** aiRowEst[N]<=aiRowEst[N-1]
4674** aiRowEst[N]>=1
4675**
4676** Apart from that, we have little to go on besides intuition as to
4677** how aiRowEst[] should be initialized. The numbers generated here
4678** are based on typical values found in actual indices.
4679*/
4680void sqlite3DefaultRowEst(Index *pIdx){
4681 /* 10, 9, 8, 7, 6 */
4682 static const LogEst aVal[] = { 33, 32, 30, 28, 26 };
4683 LogEst *a = pIdx->aiRowLogEst;
4684 LogEst x;
4685 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
4686 int i;
4687
4688 /* Indexes with default row estimates should not have stat1 data */
4689 assert( !pIdx->hasStat1 );
4690
4691 /* Set the first entry (number of rows in the index) to the estimated
4692 ** number of rows in the table, or half the number of rows in the table
4693 ** for a partial index.
4694 **
4695 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
4696 ** table but other parts we are having to guess at, then do not let the
4697 ** estimated number of rows in the table be less than 1000 (LogEst 99).
4698 ** Failure to do this can cause the indexes for which we do not have
4699 ** stat1 data to be ignored by the query planner.
4700 */
4701 x = pIdx->pTable->nRowLogEst;
4702 assert( 99==sqlite3LogEst(1000) );
4703 if( x<99 ){
4704 pIdx->pTable->nRowLogEst = x = 99;
4705 }
4706 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
4707 a[0] = x;
4708
4709 /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
4710 ** 6 and each subsequent value (if any) is 5. */
4711 memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
4712 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
4713 a[i] = 23; assert( 23==sqlite3LogEst(5) );
4714 }
4715
4716 assert( 0==sqlite3LogEst(1) );
4717 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
4718}
4719
4720/*
4721** This routine will drop an existing named index. This routine
4722** implements the DROP INDEX statement.
4723*/
4724void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
4725 Index *pIndex;
4726 Vdbe *v;
4727 sqlite3 *db = pParse->db;
4728 int iDb;
4729
4730 if( db->mallocFailed ){
4731 goto exit_drop_index;
4732 }
4733 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
4734 assert( pName->nSrc==1 );
4735 assert( pName->a[0].fg.fixedSchema==0 );
4736 assert( pName->a[0].fg.isSubquery==0 );
4737 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
4738 goto exit_drop_index;
4739 }
4740 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].u4.zDatabase);
4741 if( pIndex==0 ){
4742 if( !ifExists ){
4743 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
4744 }else{
4745 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
4746 sqlite3ForceNotReadOnly(pParse);
4747 }
4748 pParse->checkSchema = 1;
4749 goto exit_drop_index;
4750 }
4751 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
4752 sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
4753 "or PRIMARY KEY constraint cannot be dropped", 0);
4754 goto exit_drop_index;
4755 }
4756 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
4757 assert( iDb>=0 && iDb<db->nDb );
4758#ifndef SQLITE_OMIT_AUTHORIZATION
4759 {
4760 int code = SQLITE_DROP_INDEX;
4761 Table *pTab = pIndex->pTable;
4762 const char *zDb = db->aDb[iDb].zDbSName;
4763 const char *zTab = SCHEMA_TABLE(iDb);
4764 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
4765 goto exit_drop_index;
4766 }
4767 if( !OMIT_TEMPDB && iDb==1 ) code = SQLITE_DROP_TEMP_INDEX;
4768 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
4769 goto exit_drop_index;
4770 }
4771 }
4772#endif
4773
4774 /* Generate code to remove the index and from the schema table */
4775 v = sqlite3GetVdbe(pParse);
4776 if( v ){
4777 sqlite3BeginWriteOperation(pParse, 1, iDb);
4778 sqlite3NestedParse(pParse,
4779 "DELETE FROM %Q." LEGACY_SCHEMA_TABLE " WHERE name=%Q AND type='index'",
4780 db->aDb[iDb].zDbSName, pIndex->zName
4781 );
4782 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
4783 destroyRootPage(pParse, pIndex->tnum, iDb);
4784 sqlite3ChangeCookie(pParse, iDb);
4785 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
4786 }
4787
4788exit_drop_index:
4789 sqlite3SrcListDelete(db, pName);
4790}
4791
4792/*
4793** pArray is a pointer to an array of objects. Each object in the
4794** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
4795** to extend the array so that there is space for a new object at the end.
4796**
4797** When this function is called, *pnEntry contains the current size of
4798** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
4799** in total).
4800**
4801** If the realloc() is successful (i.e. if no OOM condition occurs), the
4802** space allocated for the new object is zeroed, *pnEntry updated to
4803** reflect the new size of the array and a pointer to the new allocation
4804** returned. *pIdx is set to the index of the new array entry in this case.
4805**
4806** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
4807** unchanged and a copy of pArray returned.
4808*/
4809void *sqlite3ArrayAllocate(
4810 sqlite3 *db, /* Connection to notify of malloc failures */
4811 void *pArray, /* Array of objects. Might be reallocated */
4812 int szEntry, /* Size of each object in the array */
4813 int *pnEntry, /* Number of objects currently in use */
4814 int *pIdx /* Write the index of a new slot here */
4815){
4816 char *z;
4817 sqlite3_int64 n = *pIdx = *pnEntry;
4818 if( (n & (n-1))==0 ){
4819 sqlite3_int64 sz = (n==0) ? 1 : 2*n;
4820 void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
4821 if( pNew==0 ){
4822 *pIdx = -1;
4823 return pArray;
4824 }
4825 pArray = pNew;
4826 }
4827 z = (char*)pArray;
4828 memset(&z[n * szEntry], 0, szEntry);
4829 ++*pnEntry;
4830 return pArray;
4831}
4832
4833/*
4834** Append a new element to the given IdList. Create a new IdList if
4835** need be.
4836**
4837** A new IdList is returned, or NULL if malloc() fails.
4838*/
4839IdList *sqlite3IdListAppend(Parse *pParse, IdList *pList, Token *pToken){
4840 sqlite3 *db = pParse->db;
4841 int i;
4842 if( pList==0 ){
4843 pList = sqlite3DbMallocZero(db, SZ_IDLIST(1));
4844 if( pList==0 ) return 0;
4845 }else{
4846 IdList *pNew;
4847 pNew = sqlite3DbRealloc(db, pList, SZ_IDLIST(pList->nId+1));
4848 if( pNew==0 ){
4849 sqlite3IdListDelete(db, pList);
4850 return 0;
4851 }
4852 pList = pNew;
4853 }
4854 i = pList->nId++;
4855 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
4856 if( IN_RENAME_OBJECT && pList->a[i].zName ){
4857 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
4858 }
4859 return pList;
4860}
4861
4862/*
4863** Delete an IdList.
4864*/
4865void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
4866 int i;
4867 assert( db!=0 );
4868 if( pList==0 ) return;
4869 for(i=0; i<pList->nId; i++){
4870 sqlite3DbFree(db, pList->a[i].zName);
4871 }
4872 sqlite3DbNNFreeNN(db, pList);
4873}
4874
4875/*
4876** Return the index in pList of the identifier named zId. Return -1
4877** if not found.
4878*/
4879int sqlite3IdListIndex(IdList *pList, const char *zName){
4880 int i;
4881 assert( pList!=0 );
4882 for(i=0; i<pList->nId; i++){
4883 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
4884 }
4885 return -1;
4886}
4887
4888/*
4889** Maximum size of a SrcList object.
4890** The SrcList object is used to represent the FROM clause of a
4891** SELECT statement, and the query planner cannot deal with more
4892** than 64 tables in a join. So any value larger than 64 here
4893** is sufficient for most uses. Smaller values, like say 10, are
4894** appropriate for small and memory-limited applications.
4895*/
4896#ifndef SQLITE_MAX_SRCLIST
4897# define SQLITE_MAX_SRCLIST 200
4898#endif
4899
4900/*
4901** Expand the space allocated for the given SrcList object by
4902** creating nExtra new slots beginning at iStart. iStart is zero based.
4903** New slots are zeroed.
4904**
4905** For example, suppose a SrcList initially contains two entries: A,B.
4906** To append 3 new entries onto the end, do this:
4907**
4908** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
4909**
4910** After the call above it would contain: A, B, nil, nil, nil.
4911** If the iStart argument had been 1 instead of 2, then the result
4912** would have been: A, nil, nil, nil, B. To prepend the new slots,
4913** the iStart value would be 0. The result then would
4914** be: nil, nil, nil, A, B.
4915**
4916** If a memory allocation fails or the SrcList becomes too large, leave
4917** the original SrcList unchanged, return NULL, and leave an error message
4918** in pParse.
4919*/
4920SrcList *sqlite3SrcListEnlarge(
4921 Parse *pParse, /* Parsing context into which errors are reported */
4922 SrcList *pSrc, /* The SrcList to be enlarged */
4923 int nExtra, /* Number of new slots to add to pSrc->a[] */
4924 int iStart /* Index in pSrc->a[] of first new slot */
4925){
4926 int i;
4927
4928 /* Sanity checking on calling parameters */
4929 assert( iStart>=0 );
4930 assert( nExtra>=1 );
4931 assert( pSrc!=0 );
4932 assert( iStart<=pSrc->nSrc );
4933
4934 /* Allocate additional space if needed */
4935 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
4936 SrcList *pNew;
4937 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
4938 sqlite3 *db = pParse->db;
4939
4940 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
4941 sqlite3ErrorMsg(pParse, "too many FROM clause terms, max: %d",
4942 SQLITE_MAX_SRCLIST);
4943 return 0;
4944 }
4945 if( nAlloc>SQLITE_MAX_SRCLIST ) nAlloc = SQLITE_MAX_SRCLIST;
4946 pNew = sqlite3DbRealloc(db, pSrc, SZ_SRCLIST(nAlloc));
4947 if( pNew==0 ){
4948 assert( db->mallocFailed );
4949 return 0;
4950 }
4951 pSrc = pNew;
4952 pSrc->nAlloc = nAlloc;
4953 }
4954
4955 /* Move existing slots that come after the newly inserted slots
4956 ** out of the way */
4957 for(i=pSrc->nSrc-1; i>=iStart; i--){
4958 pSrc->a[i+nExtra] = pSrc->a[i];
4959 }
4960 pSrc->nSrc += nExtra;
4961
4962 /* Zero the newly allocated slots */
4963 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
4964 for(i=iStart; i<iStart+nExtra; i++){
4965 pSrc->a[i].iCursor = -1;
4966 }
4967
4968 /* Return a pointer to the enlarged SrcList */
4969 return pSrc;
4970}
4971
4972
4973/*
4974** Append a new table name to the given SrcList. Create a new SrcList if
4975** need be. A new entry is created in the SrcList even if pTable is NULL.
4976**
4977** A SrcList is returned, or NULL if there is an OOM error or if the
4978** SrcList grows to large. The returned
4979** SrcList might be the same as the SrcList that was input or it might be
4980** a new one. If an OOM error does occurs, then the prior value of pList
4981** that is input to this routine is automatically freed.
4982**
4983** If pDatabase is not null, it means that the table has an optional
4984** database name prefix. Like this: "database.table". The pDatabase
4985** points to the table name and the pTable points to the database name.
4986** The SrcList.a[].zName field is filled with the table name which might
4987** come from pTable (if pDatabase is NULL) or from pDatabase.
4988** SrcList.a[].zDatabase is filled with the database name from pTable,
4989** or with NULL if no database is specified.
4990**
4991** In other words, if call like this:
4992**
4993** sqlite3SrcListAppend(D,A,B,0);
4994**
4995** Then B is a table name and the database name is unspecified. If called
4996** like this:
4997**
4998** sqlite3SrcListAppend(D,A,B,C);
4999**
5000** Then C is the table name and B is the database name. If C is defined
5001** then so is B. In other words, we never have a case where:
5002**
5003** sqlite3SrcListAppend(D,A,0,C);
5004**
5005** Both pTable and pDatabase are assumed to be quoted. They are dequoted
5006** before being added to the SrcList.
5007*/
5008SrcList *sqlite3SrcListAppend(
5009 Parse *pParse, /* Parsing context, in which errors are reported */
5010 SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
5011 Token *pTable, /* Table to append */
5012 Token *pDatabase /* Database of the table */
5013){
5014 SrcItem *pItem;
5015 sqlite3 *db;
5016 assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
5017 assert( pParse!=0 );
5018 assert( pParse->db!=0 );
5019 db = pParse->db;
5020 if( pList==0 ){
5021 pList = sqlite3DbMallocRawNN(pParse->db, SZ_SRCLIST(1));
5022 if( pList==0 ) return 0;
5023 pList->nAlloc = 1;
5024 pList->nSrc = 1;
5025 memset(&pList->a[0], 0, sizeof(pList->a[0]));
5026 pList->a[0].iCursor = -1;
5027 }else{
5028 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
5029 if( pNew==0 ){
5030 sqlite3SrcListDelete(db, pList);
5031 return 0;
5032 }else{
5033 pList = pNew;
5034 }
5035 }
5036 pItem = &pList->a[pList->nSrc-1];
5037 if( pDatabase && pDatabase->z==0 ){
5038 pDatabase = 0;
5039 }
5040 assert( pItem->fg.fixedSchema==0 );
5041 assert( pItem->fg.isSubquery==0 );
5042 if( pDatabase ){
5043 pItem->zName = sqlite3NameFromToken(db, pDatabase);
5044 pItem->u4.zDatabase = sqlite3NameFromToken(db, pTable);
5045 }else{
5046 pItem->zName = sqlite3NameFromToken(db, pTable);
5047 pItem->u4.zDatabase = 0;
5048 }
5049 return pList;
5050}
5051
5052/*
5053** Assign VdbeCursor index numbers to all tables in a SrcList
5054*/
5055void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
5056 int i;
5057 SrcItem *pItem;
5058 assert( pList || pParse->db->mallocFailed );
5059 if( ALWAYS(pList) ){
5060 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
5061 if( pItem->iCursor>=0 ) continue;
5062 pItem->iCursor = pParse->nTab++;
5063 if( pItem->fg.isSubquery ){
5064 assert( pItem->u4.pSubq!=0 );
5065 assert( pItem->u4.pSubq->pSelect!=0 );
5066 assert( pItem->u4.pSubq->pSelect->pSrc!=0 );
5067 sqlite3SrcListAssignCursors(pParse, pItem->u4.pSubq->pSelect->pSrc);
5068 }
5069 }
5070 }
5071}
5072
5073/*
5074** Delete a Subquery object and its substructure.
5075*/
5076void sqlite3SubqueryDelete(sqlite3 *db, Subquery *pSubq){
5077 assert( pSubq!=0 && pSubq->pSelect!=0 );
5078 sqlite3SelectDelete(db, pSubq->pSelect);
5079 sqlite3DbFree(db, pSubq);
5080}
5081
5082/*
5083** Remove a Subquery from a SrcItem. Return the associated Select object.
5084** The returned Select becomes the responsibility of the caller.
5085*/
5086Select *sqlite3SubqueryDetach(sqlite3 *db, SrcItem *pItem){
5087 Select *pSel;
5088 assert( pItem!=0 );
5089 assert( pItem->fg.isSubquery );
5090 pSel = pItem->u4.pSubq->pSelect;
5091 sqlite3DbFree(db, pItem->u4.pSubq);
5092 pItem->u4.pSubq = 0;
5093 pItem->fg.isSubquery = 0;
5094 return pSel;
5095}
5096
5097/*
5098** Delete an entire SrcList including all its substructure.
5099*/
5100void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
5101 int i;
5102 SrcItem *pItem;
5103 assert( db!=0 );
5104 if( pList==0 ) return;
5105 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
5106
5107 /* Check invariants on SrcItem */
5108 assert( !pItem->fg.isIndexedBy || !pItem->fg.isTabFunc );
5109 assert( !pItem->fg.isCte || !pItem->fg.isIndexedBy );
5110 assert( !pItem->fg.fixedSchema || !pItem->fg.isSubquery );
5111 assert( !pItem->fg.isSubquery || (pItem->u4.pSubq!=0 &&
5112 pItem->u4.pSubq->pSelect!=0) );
5113
5114 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
5115 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
5116 if( pItem->fg.isSubquery ){
5117 sqlite3SubqueryDelete(db, pItem->u4.pSubq);
5118 }else if( pItem->fg.fixedSchema==0 && pItem->u4.zDatabase!=0 ){
5119 sqlite3DbNNFreeNN(db, pItem->u4.zDatabase);
5120 }
5121 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
5122 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
5123 sqlite3DeleteTable(db, pItem->pSTab);
5124 if( pItem->fg.isUsing ){
5125 sqlite3IdListDelete(db, pItem->u3.pUsing);
5126 }else if( pItem->u3.pOn ){
5127 sqlite3ExprDelete(db, pItem->u3.pOn);
5128 }
5129 }
5130 sqlite3DbNNFreeNN(db, pList);
5131}
5132
5133/*
5134** Attach a Subquery object to pItem->uv.pSubq. Set the
5135** pSelect value but leave all the other values initialized
5136** to zero.
5137**
5138** A copy of the Select object is made if dupSelect is true, and the
5139** SrcItem takes responsibility for deleting the copy. If dupSelect is
5140** false, ownership of the Select passes to the SrcItem. Either way,
5141** the SrcItem will take responsibility for deleting the Select.
5142**
5143** When dupSelect is zero, that means the Select might get deleted right
5144** away if there is an OOM error. Beware.
5145**
5146** Return non-zero on success. Return zero on an OOM error.
5147*/
5148int sqlite3SrcItemAttachSubquery(
5149 Parse *pParse, /* Parsing context */
5150 SrcItem *pItem, /* Item to which the subquery is to be attached */
5151 Select *pSelect, /* The subquery SELECT. Must be non-NULL */
5152 int dupSelect /* If true, attach a copy of pSelect, not pSelect itself.*/
5153){
5154 Subquery *p;
5155 assert( pSelect!=0 );
5156 assert( pItem->fg.isSubquery==0 );
5157 if( pItem->fg.fixedSchema ){
5158 pItem->u4.pSchema = 0;
5159 pItem->fg.fixedSchema = 0;
5160 }else if( pItem->u4.zDatabase!=0 ){
5161 sqlite3DbFree(pParse->db, pItem->u4.zDatabase);
5162 pItem->u4.zDatabase = 0;
5163 }
5164 if( dupSelect ){
5165 pSelect = sqlite3SelectDup(pParse->db, pSelect, 0);
5166 if( pSelect==0 ) return 0;
5167 }
5168 p = pItem->u4.pSubq = sqlite3DbMallocRawNN(pParse->db, sizeof(Subquery));
5169 if( p==0 ){
5170 sqlite3SelectDelete(pParse->db, pSelect);
5171 return 0;
5172 }
5173 pItem->fg.isSubquery = 1;
5174 p->pSelect = pSelect;
5175 assert( offsetof(Subquery, pSelect)==0 );
5176 memset(((char*)p)+sizeof(p->pSelect), 0, sizeof(*p)-sizeof(p->pSelect));
5177 return 1;
5178}
5179
5180
5181/*
5182** This routine is called by the parser to add a new term to the
5183** end of a growing FROM clause. The "p" parameter is the part of
5184** the FROM clause that has already been constructed. "p" is NULL
5185** if this is the first term of the FROM clause. pTable and pDatabase
5186** are the name of the table and database named in the FROM clause term.
5187** pDatabase is NULL if the database name qualifier is missing - the
5188** usual case. If the term has an alias, then pAlias points to the
5189** alias token. If the term is a subquery, then pSubquery is the
5190** SELECT statement that the subquery encodes. The pTable and
5191** pDatabase parameters are NULL for subqueries. The pOn and pUsing
5192** parameters are the content of the ON and USING clauses.
5193**
5194** Return a new SrcList which encodes is the FROM with the new
5195** term added.
5196*/
5197SrcList *sqlite3SrcListAppendFromTerm(
5198 Parse *pParse, /* Parsing context */
5199 SrcList *p, /* The left part of the FROM clause already seen */
5200 Token *pTable, /* Name of the table to add to the FROM clause */
5201 Token *pDatabase, /* Name of the database containing pTable */
5202 Token *pAlias, /* The right-hand side of the AS subexpression */
5203 Select *pSubquery, /* A subquery used in place of a table name */
5204 OnOrUsing *pOnUsing /* Either the ON clause or the USING clause */
5205){
5206 SrcItem *pItem;
5207 sqlite3 *db = pParse->db;
5208 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
5209 sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
5210 (pOnUsing->pOn ? "ON" : "USING")
5211 );
5212 goto append_from_error;
5213 }
5214 p = sqlite3SrcListAppend(pParse, p, pTable, pDatabase);
5215 if( p==0 ){
5216 goto append_from_error;
5217 }
5218 assert( p->nSrc>0 );
5219 pItem = &p->a[p->nSrc-1];
5220 assert( (pTable==0)==(pDatabase==0) );
5221 assert( pItem->zName==0 || pDatabase!=0 );
5222 if( IN_RENAME_OBJECT && pItem->zName ){
5223 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
5224 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
5225 }
5226 assert( pAlias!=0 );
5227 if( pAlias->n ){
5228 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
5229 }
5230 assert( pSubquery==0 || pDatabase==0 );
5231 if( pSubquery ){
5232 if( sqlite3SrcItemAttachSubquery(pParse, pItem, pSubquery, 0) ){
5233 if( pSubquery->selFlags & SF_NestedFrom ){
5234 pItem->fg.isNestedFrom = 1;
5235 }
5236 }
5237 }
5238 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
5239 assert( pItem->fg.isUsing==0 );
5240 if( pOnUsing==0 ){
5241 pItem->u3.pOn = 0;
5242 }else if( pOnUsing->pUsing ){
5243 pItem->fg.isUsing = 1;
5244 pItem->u3.pUsing = pOnUsing->pUsing;
5245 }else{
5246 pItem->u3.pOn = pOnUsing->pOn;
5247 }
5248 return p;
5249
5250append_from_error:
5251 assert( p==0 );
5252 sqlite3ClearOnOrUsing(db, pOnUsing);
5253 sqlite3SelectDelete(db, pSubquery);
5254 return 0;
5255}
5256
5257/*
5258** Add an INDEXED BY or NOT INDEXED clause to the most recently added
5259** element of the source-list passed as the second argument.
5260*/
5261void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
5262 assert( pIndexedBy!=0 );
5263 if( p && pIndexedBy->n>0 ){
5264 SrcItem *pItem;
5265 assert( p->nSrc>0 );
5266 pItem = &p->a[p->nSrc-1];
5267 assert( pItem->fg.notIndexed==0 );
5268 assert( pItem->fg.isIndexedBy==0 );
5269 assert( pItem->fg.isTabFunc==0 );
5270 if( pIndexedBy->n==1 && !pIndexedBy->z ){
5271 /* A "NOT INDEXED" clause was supplied. See parse.y
5272 ** construct "indexed_opt" for details. */
5273 pItem->fg.notIndexed = 1;
5274 }else{
5275 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
5276 pItem->fg.isIndexedBy = 1;
5277 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
5278 }
5279 }
5280}
5281
5282/*
5283** Append the contents of SrcList p2 to SrcList p1 and return the resulting
5284** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
5285** are deleted by this function.
5286*/
5287SrcList *sqlite3SrcListAppendList(Parse *pParse, SrcList *p1, SrcList *p2){
5288 assert( p1 );
5289 assert( p2 || pParse->nErr );
5290 assert( p2==0 || p2->nSrc>=1 );
5291 testcase( p1->nSrc==0 );
5292 if( p2 ){
5293 int nOld = p1->nSrc;
5294 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, nOld);
5295 if( pNew==0 ){
5296 sqlite3SrcListDelete(pParse->db, p2);
5297 }else{
5298 p1 = pNew;
5299 memcpy(&p1->a[nOld], p2->a, p2->nSrc*sizeof(SrcItem));
5300 assert( nOld==1 || (p2->a[0].fg.jointype & JT_LTORJ)==0 );
5301 assert( p1->nSrc>=1 );
5302 p1->a[0].fg.jointype |= (JT_LTORJ & p2->a[0].fg.jointype);
5303 sqlite3DbFree(pParse->db, p2);
5304 }
5305 }
5306 return p1;
5307}
5308
5309/*
5310** Add the list of function arguments to the SrcList entry for a
5311** table-valued-function.
5312*/
5313void sqlite3SrcListFuncArgs(Parse *pParse, SrcList *p, ExprList *pList){
5314 if( p ){
5315 SrcItem *pItem = &p->a[p->nSrc-1];
5316 assert( pItem->fg.notIndexed==0 );
5317 assert( pItem->fg.isIndexedBy==0 );
5318 assert( pItem->fg.isTabFunc==0 );
5319 pItem->u1.pFuncArg = pList;
5320 pItem->fg.isTabFunc = 1;
5321 }else{
5322 sqlite3ExprListDelete(pParse->db, pList);
5323 }
5324}
5325
5326/*
5327** When building up a FROM clause in the parser, the join operator
5328** is initially attached to the left operand. But the code generator
5329** expects the join operator to be on the right operand. This routine
5330** Shifts all join operators from left to right for an entire FROM
5331** clause.
5332**
5333** Example: Suppose the join is like this:
5334**
5335** A natural cross join B
5336**
5337** The operator is "natural cross join". The A and B operands are stored
5338** in p->a[0] and p->a[1], respectively. The parser initially stores the
5339** operator with A. This routine shifts that operator over to B.
5340**
5341** Additional changes:
5342**
5343** * All tables to the left of the right-most RIGHT JOIN are tagged with
5344** JT_LTORJ (mnemonic: Left Table Of Right Join) so that the
5345** code generator can easily tell that the table is part of
5346** the left operand of at least one RIGHT JOIN.
5347*/
5348void sqlite3SrcListShiftJoinType(Parse *pParse, SrcList *p){
5349 (void)pParse;
5350 if( p && p->nSrc>1 ){
5351 int i = p->nSrc-1;
5352 u8 allFlags = 0;
5353 do{
5354 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
5355 }while( (--i)>0 );
5356 p->a[0].fg.jointype = 0;
5357
5358 /* All terms to the left of a RIGHT JOIN should be tagged with the
5359 ** JT_LTORJ flags */
5360 if( allFlags & JT_RIGHT ){
5361 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
5362 i--;
5363 assert( i>=0 );
5364 do{
5365 p->a[i].fg.jointype |= JT_LTORJ;
5366 }while( (--i)>=0 );
5367 }
5368 }
5369}
5370
5371/*
5372** Generate VDBE code for a BEGIN statement.
5373*/
5374void sqlite3BeginTransaction(Parse *pParse, int type){
5375 sqlite3 *db;
5376 Vdbe *v;
5377 int i;
5378
5379 assert( pParse!=0 );
5380 db = pParse->db;
5381 assert( db!=0 );
5382 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
5383 return;
5384 }
5385 v = sqlite3GetVdbe(pParse);
5386 if( !v ) return;
5387 if( type!=TK_DEFERRED ){
5388 for(i=0; i<db->nDb; i++){
5389 int eTxnType;
5390 Btree *pBt = db->aDb[i].pBt;
5391 if( pBt && sqlite3BtreeIsReadonly(pBt) ){
5392 eTxnType = 0; /* Read txn */
5393 }else if( type==TK_EXCLUSIVE ){
5394 eTxnType = 2; /* Exclusive txn */
5395 }else{
5396 eTxnType = 1; /* Write txn */
5397 }
5398 sqlite3VdbeAddOp2(v, OP_Transaction, i, eTxnType);
5399 sqlite3VdbeUsesBtree(v, i);
5400 }
5401 }
5402 sqlite3VdbeAddOp0(v, OP_AutoCommit);
5403}
5404
5405/*
5406** Generate VDBE code for a COMMIT or ROLLBACK statement.
5407** Code for ROLLBACK is generated if eType==TK_ROLLBACK. Otherwise
5408** code is generated for a COMMIT.
5409*/
5410void sqlite3EndTransaction(Parse *pParse, int eType){
5411 Vdbe *v;
5412 int isRollback;
5413
5414 assert( pParse!=0 );
5415 assert( pParse->db!=0 );
5416 assert( eType==TK_COMMIT || eType==TK_END || eType==TK_ROLLBACK );
5417 isRollback = eType==TK_ROLLBACK;
5418 if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION,
5419 isRollback ? "ROLLBACK" : "COMMIT", 0, 0) ){
5420 return;
5421 }
5422 v = sqlite3GetVdbe(pParse);
5423 if( v ){
5424 sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, isRollback);
5425 }
5426}
5427
5428/*
5429** This function is called by the parser when it parses a command to create,
5430** release or rollback an SQL savepoint.
5431*/
5432void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
5433 char *zName = sqlite3NameFromToken(pParse->db, pName);
5434 if( zName ){
5435 Vdbe *v = sqlite3GetVdbe(pParse);
5436#ifndef SQLITE_OMIT_AUTHORIZATION
5437 static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
5438 assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
5439#endif
5440 if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
5441 sqlite3DbFree(pParse->db, zName);
5442 return;
5443 }
5444 sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
5445 }
5446}
5447
5448/*
5449** Make sure the TEMP database is open and available for use. Return
5450** the number of errors. Leave any error messages in the pParse structure.
5451*/
5452int sqlite3OpenTempDatabase(Parse *pParse){
5453 sqlite3 *db = pParse->db;
5454 if( db->aDb[1].pBt==0 && !pParse->explain ){
5455 int rc;
5456 Btree *pBt;
5457 static const int flags =
5458 SQLITE_OPEN_READWRITE |
5459 SQLITE_OPEN_CREATE |
5460 SQLITE_OPEN_EXCLUSIVE |
5461 SQLITE_OPEN_DELETEONCLOSE |
5462 SQLITE_OPEN_TEMP_DB;
5463
5464 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
5465 if( rc!=SQLITE_OK ){
5466 sqlite3ErrorMsg(pParse, "unable to open a temporary database "
5467 "file for storing temporary tables");
5468 pParse->rc = rc;
5469 return 1;
5470 }
5471 db->aDb[1].pBt = pBt;
5472 assert( db->aDb[1].pSchema );
5473 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
5474 sqlite3OomFault(db);
5475 return 1;
5476 }
5477 }
5478 return 0;
5479}
5480
5481/*
5482** Record the fact that the schema cookie will need to be verified
5483** for database iDb. The code to actually verify the schema cookie
5484** will occur at the end of the top-level VDBE and will be generated
5485** later, by sqlite3FinishCoding().
5486*/
5487static void sqlite3CodeVerifySchemaAtToplevel(Parse *pToplevel, int iDb){
5488 assert( iDb>=0 && iDb<pToplevel->db->nDb );
5489 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
5490 assert( iDb<SQLITE_MAX_DB );
5491 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
5492 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
5493 DbMaskSet(pToplevel->cookieMask, iDb);
5494 if( !OMIT_TEMPDB && iDb==1 ){
5495 sqlite3OpenTempDatabase(pToplevel);
5496 }
5497 }
5498}
5499void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
5500 sqlite3CodeVerifySchemaAtToplevel(sqlite3ParseToplevel(pParse), iDb);
5501}
5502
5503
5504/*
5505** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
5506** attached database. Otherwise, invoke it for the database named zDb only.
5507*/
5508void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
5509 sqlite3 *db = pParse->db;
5510 int i;
5511 for(i=0; i<db->nDb; i++){
5512 Db *pDb = &db->aDb[i];
5513 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
5514 sqlite3CodeVerifySchema(pParse, i);
5515 }
5516 }
5517}
5518
5519/*
5520** Generate VDBE code that prepares for doing an operation that
5521** might change the database.
5522**
5523** This routine starts a new transaction if we are not already within
5524** a transaction. If we are already within a transaction, then a checkpoint
5525** is set if the setStatement parameter is true. A checkpoint should
5526** be set for operations that might fail (due to a constraint) part of
5527** the way through and which will need to undo some writes without having to
5528** rollback the whole transaction. For operations where all constraints
5529** can be checked before any changes are made to the database, it is never
5530** necessary to undo a write and the checkpoint should not be set.
5531*/
5532void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
5533 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5534 sqlite3CodeVerifySchemaAtToplevel(pToplevel, iDb);
5535 DbMaskSet(pToplevel->writeMask, iDb);
5536 pToplevel->isMultiWrite |= setStatement;
5537}
5538
5539/*
5540** Indicate that the statement currently under construction might write
5541** more than one entry (example: deleting one row then inserting another,
5542** inserting multiple rows in a table, or inserting a row and index entries.)
5543** If an abort occurs after some of these writes have completed, then it will
5544** be necessary to undo the completed writes.
5545*/
5546void sqlite3MultiWrite(Parse *pParse){
5547 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5548 pToplevel->isMultiWrite = 1;
5549}
5550
5551/*
5552** The code generator calls this routine if is discovers that it is
5553** possible to abort a statement prior to completion. In order to
5554** perform this abort without corrupting the database, we need to make
5555** sure that the statement is protected by a statement transaction.
5556**
5557** Technically, we only need to set the mayAbort flag if the
5558** isMultiWrite flag was previously set. There is a time dependency
5559** such that the abort must occur after the multiwrite. This makes
5560** some statements involving the REPLACE conflict resolution algorithm
5561** go a little faster. But taking advantage of this time dependency
5562** makes it more difficult to prove that the code is correct (in
5563** particular, it prevents us from writing an effective
5564** implementation of sqlite3AssertMayAbort()) and so we have chosen
5565** to take the safe route and skip the optimization.
5566*/
5567void sqlite3MayAbort(Parse *pParse){
5568 Parse *pToplevel = sqlite3ParseToplevel(pParse);
5569 pToplevel->mayAbort = 1;
5570}
5571
5572/*
5573** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
5574** error. The onError parameter determines which (if any) of the statement
5575** and/or current transaction is rolled back.
5576*/
5577void sqlite3HaltConstraint(
5578 Parse *pParse, /* Parsing context */
5579 int errCode, /* extended error code */
5580 int onError, /* Constraint type */
5581 char *p4, /* Error message */
5582 i8 p4type, /* P4_STATIC or P4_TRANSIENT */
5583 u8 p5Errmsg /* P5_ErrMsg type */
5584){
5585 Vdbe *v;
5586 assert( pParse->pVdbe!=0 );
5587 v = sqlite3GetVdbe(pParse);
5588 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
5589 if( onError==OE_Abort ){
5590 sqlite3MayAbort(pParse);
5591 }
5592 sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
5593 sqlite3VdbeChangeP5(v, p5Errmsg);
5594}
5595
5596/*
5597** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
5598*/
5599void sqlite3UniqueConstraint(
5600 Parse *pParse, /* Parsing context */
5601 int onError, /* Constraint type */
5602 Index *pIdx /* The index that triggers the constraint */
5603){
5604 char *zErr;
5605 int j;
5606 StrAccum errMsg;
5607 Table *pTab = pIdx->pTable;
5608
5609 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
5610 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
5611 if( pIdx->aColExpr ){
5612 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
5613 }else{
5614 for(j=0; j<pIdx->nKeyCol; j++){
5615 char *zCol;
5616 assert( pIdx->aiColumn[j]>=0 );
5617 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
5618 if( j ) sqlite3_str_append(&errMsg, ", ", 2);
5619 sqlite3_str_appendall(&errMsg, pTab->zName);
5620 sqlite3_str_append(&errMsg, ".", 1);
5621 sqlite3_str_appendall(&errMsg, zCol);
5622 }
5623 }
5624 zErr = sqlite3StrAccumFinish(&errMsg);
5625 sqlite3HaltConstraint(pParse,
5626 IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
5627 : SQLITE_CONSTRAINT_UNIQUE,
5628 onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
5629}
5630
5631
5632/*
5633** Code an OP_Halt due to non-unique rowid.
5634*/
5635void sqlite3RowidConstraint(
5636 Parse *pParse, /* Parsing context */
5637 int onError, /* Conflict resolution algorithm */
5638 Table *pTab /* The table with the non-unique rowid */
5639){
5640 char *zMsg;
5641 int rc;
5642 if( pTab->iPKey>=0 ){
5643 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
5644 pTab->aCol[pTab->iPKey].zCnName);
5645 rc = SQLITE_CONSTRAINT_PRIMARYKEY;
5646 }else{
5647 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
5648 rc = SQLITE_CONSTRAINT_ROWID;
5649 }
5650 sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
5651 P5_ConstraintUnique);
5652}
5653
5654/*
5655** Return true if any column of pIndex uses the zColl collation
5656*/
5657#ifndef SQLITE_OMIT_REINDEX
5658static int collationMatch(const char *zColl, Index *pIndex){
5659 int i;
5660 assert( zColl!=0 );
5661 for(i=0; i<pIndex->nColumn; i++){
5662 const char *z = pIndex->azColl[i];
5663 assert( z!=0 );
5664 if( 0==sqlite3StrICmp(z, zColl) ){
5665 return 1;
5666 }
5667 }
5668 return 0;
5669}
5670#endif
5671
5672/*
5673** Generate code for the REINDEX command.
5674**
5675** REINDEX -- 1
5676** REINDEX <collation> -- 2
5677** REINDEX ?<database>.?<indexname> -- 3
5678** REINDEX ?<database>.?<tablename> -- 4
5679** REINDEX EXPRESSIONS -- 5
5680**
5681** Form 1 causes all indexes in all attached databases to be rebuilt.
5682** Form 2 rebuilds all indexes in all databases that use the named
5683** collating function. Forms 3 and 4 rebuild the named index or all
5684** indexes associated with the named table, respectively. Form 5
5685** rebuilds all expression indexes in addition to all collations,
5686** indexes, or tables named "EXPRESSIONS".
5687**
5688** If the name is ambiguous such that it matches two or more of
5689** forms 2 through 5, then rebuild the union of all matching indexes,
5690** taken care to avoid rebuilding the same index more than once.
5691*/
5692#ifndef SQLITE_OMIT_REINDEX
5693void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
5694 char *z = 0; /* Name of a table or index or collation */
5695 const char *zDb = 0; /* Name of the database */
5696 int iReDb = -1; /* The database index number */
5697 sqlite3 *db = pParse->db; /* The database connection */
5698 Token *pObjName; /* Name of the table or index to be reindexed */
5699 int bMatch = 0; /* At least one name match */
5700 const char *zColl = 0; /* Rebuild indexes using this collation */
5701 Table *pReTab = 0; /* Rebuild all indexes of this table */
5702 Index *pReIndex = 0; /* Rebuild this index */
5703 int isExprIdx = 0; /* Rebuild all expression indexes */
5704 int bAll = 0; /* Rebuild all indexes */
5705
5706 /* Read the database schema. If an error occurs, leave an error message
5707 ** and code in pParse and return NULL. */
5708 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
5709 return;
5710 }
5711
5712 if( pName1==0 ){
5713 /* rebuild all indexes */
5714 bMatch = 1;
5715 bAll = 1;
5716 }else if( NEVER(pName2==0) || pName2->z==0 ){
5717 assert( pName1->z );
5718 z = sqlite3NameFromToken(pParse->db, pName1);
5719 if( z==0 ) return;
5720 }else{
5721 iReDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
5722 if( iReDb<0 ) return;
5723 z = sqlite3NameFromToken(db, pObjName);
5724 if( z==0 ) return;
5725 zDb = db->aDb[iReDb].zDbSName;
5726 }
5727 if( !bAll ){
5728 if( zDb==0 && sqlite3StrICmp(z, "expressions")==0 ){
5729 isExprIdx = 1;
5730 bMatch = 1;
5731 }
5732 if( zDb==0 && sqlite3FindCollSeq(db, ENC(db), z, 0)!=0 ){
5733 zColl = z;
5734 bMatch = 1;
5735 }
5736 if( zColl==0 && (pReTab = sqlite3FindTable(db, z, zDb))!=0 ){
5737 bMatch = 1;
5738 }
5739 if( zColl==0 && (pReIndex = sqlite3FindIndex(db, z, zDb))!=0 ){
5740 bMatch = 1;
5741 }
5742 }
5743 if( bMatch ){
5744 int iDb;
5745 HashElem *k;
5746 Table *pTab;
5747 Index *pIdx;
5748 Db *pDb;
5749 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
5750 assert( pDb!=0 );
5751 if( iReDb>=0 && iReDb!=iDb ) continue;
5752 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
5753 pTab = (Table*)sqliteHashData(k);
5754 if( IsVirtual(pTab) ) continue;
5755 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
5756 if( bAll
5757 || pTab==pReTab
5758 || pIdx==pReIndex
5759 || (isExprIdx && pIdx->bHasExpr)
5760 || (zColl!=0 && collationMatch(zColl,pIdx))
5761 ){
5762 sqlite3BeginWriteOperation(pParse, 0, iDb);
5763 sqlite3RefillIndex(pParse, pIdx, -1);
5764 }
5765 } /* End loop over indexes of pTab */
5766 } /* End loop over tables of iDb */
5767 } /* End loop over databases */
5768 }else{
5769 sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
5770 }
5771 sqlite3DbFree(db, z);
5772 return;
5773}
5774#endif
5775
5776/*
5777** Return a KeyInfo structure that is appropriate for the given Index.
5778**
5779** The caller should invoke sqlite3KeyInfoUnref() on the returned object
5780** when it has finished using it.
5781*/
5782KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
5783 int i;
5784 int nCol = pIdx->nColumn;
5785 int nKey = pIdx->nKeyCol;
5786 KeyInfo *pKey;
5787 if( pParse->nErr ) return 0;
5788 if( pIdx->uniqNotNull ){
5789 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
5790 }else{
5791 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
5792 }
5793 if( pKey ){
5794 assert( sqlite3KeyInfoIsWriteable(pKey) );
5795 for(i=0; i<nCol; i++){
5796 const char *zColl = pIdx->azColl[i];
5797 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
5798 sqlite3LocateCollSeq(pParse, zColl);
5799 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
5800 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
5801 }
5802 if( pParse->nErr ){
5803 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
5804 if( pIdx->bNoQuery==0
5805 && sqlite3HashFind(&pIdx->pSchema->idxHash, pIdx->zName)
5806 ){
5807 /* Deactivate the index because it contains an unknown collating
5808 ** sequence. The only way to reactive the index is to reload the
5809 ** schema. Adding the missing collating sequence later does not
5810 ** reactive the index. The application had the chance to register
5811 ** the missing index using the collation-needed callback. For
5812 ** simplicity, SQLite will not give the application a second chance.
5813 **
5814 ** Except, do not do this if the index is not in the schema hash
5815 ** table. In this case the index is currently being constructed
5816 ** by a CREATE INDEX statement, and retrying will not help. */
5817 pIdx->bNoQuery = 1;
5818 pParse->rc = SQLITE_ERROR_RETRY;
5819 }
5820 sqlite3KeyInfoUnref(pKey);
5821 pKey = 0;
5822 }
5823 }
5824 return pKey;
5825}
5826
5827#ifndef SQLITE_OMIT_CTE
5828/*
5829** Create a new CTE object
5830*/
5831Cte *sqlite3CteNew(
5832 Parse *pParse, /* Parsing context */
5833 Token *pName, /* Name of the common-table */
5834 ExprList *pArglist, /* Optional column name list for the table */
5835 Select *pQuery, /* Query used to initialize the table */
5836 u8 eM10d /* The MATERIALIZED flag */
5837){
5838 Cte *pNew;
5839 sqlite3 *db = pParse->db;
5840
5841 pNew = sqlite3DbMallocZero(db, sizeof(*pNew));
5842 assert( pNew!=0 || db->mallocFailed );
5843
5844 if( db->mallocFailed ){
5845 sqlite3ExprListDelete(db, pArglist);
5846 sqlite3SelectDelete(db, pQuery);
5847 }else{
5848 pNew->pSelect = pQuery;
5849 pNew->pCols = pArglist;
5850 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
5851 pNew->eM10d = eM10d;
5852 }
5853 return pNew;
5854}
5855
5856/*
5857** Clear information from a Cte object, but do not deallocate storage
5858** for the object itself.
5859*/
5860static void cteClear(sqlite3 *db, Cte *pCte){
5861 assert( pCte!=0 );
5862 sqlite3ExprListDelete(db, pCte->pCols);
5863 sqlite3SelectDelete(db, pCte->pSelect);
5864 sqlite3DbFree(db, pCte->zName);
5865}
5866
5867/*
5868** Free the contents of the CTE object passed as the second argument.
5869*/
5870void sqlite3CteDelete(sqlite3 *db, Cte *pCte){
5871 assert( pCte!=0 );
5872 cteClear(db, pCte);
5873 sqlite3DbFree(db, pCte);
5874}
5875
5876/*
5877** This routine is invoked once per CTE by the parser while parsing a
5878** WITH clause. The CTE described by the third argument is added to
5879** the WITH clause of the second argument. If the second argument is
5880** NULL, then a new WITH argument is created.
5881*/
5882With *sqlite3WithAdd(
5883 Parse *pParse, /* Parsing context */
5884 With *pWith, /* Existing WITH clause, or NULL */
5885 Cte *pCte /* CTE to add to the WITH clause */
5886){
5887 sqlite3 *db = pParse->db;
5888 With *pNew;
5889 char *zName;
5890
5891 if( pCte==0 ){
5892 return pWith;
5893 }
5894
5895 /* Check that the CTE name is unique within this WITH clause. If
5896 ** not, store an error in the Parse structure. */
5897 zName = pCte->zName;
5898 if( zName && pWith ){
5899 int i;
5900 for(i=0; i<pWith->nCte; i++){
5901 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
5902 sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
5903 }
5904 }
5905 }
5906
5907 if( pWith ){
5908 pNew = sqlite3DbRealloc(db, pWith, SZ_WITH(pWith->nCte+1));
5909 }else{
5910 pNew = sqlite3DbMallocZero(db, SZ_WITH(1));
5911 }
5912 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
5913
5914 if( db->mallocFailed ){
5915 sqlite3CteDelete(db, pCte);
5916 pNew = pWith;
5917 }else{
5918 pNew->a[pNew->nCte++] = *pCte;
5919 sqlite3DbFree(db, pCte);
5920 }
5921
5922 return pNew;
5923}
5924
5925/*
5926** Free the contents of the With object passed as the second argument.
5927*/
5928void sqlite3WithDelete(sqlite3 *db, With *pWith){
5929 if( pWith ){
5930 int i;
5931 for(i=0; i<pWith->nCte; i++){
5932 cteClear(db, &pWith->a[i]);
5933 }
5934 sqlite3DbFree(db, pWith);
5935 }
5936}
5937void sqlite3WithDeleteGeneric(sqlite3 *db, void *pWith){
5938 sqlite3WithDelete(db, (With*)pWith);
5939}
5940#endif /* !defined(SQLITE_OMIT_CTE) */