xref: /sqlite-3.40.0/src/alter.c (revision 779e9906)
1 /*
2 ** 2005 February 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 used to generate VDBE code
13 ** that implements the ALTER TABLE command.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** The code in this file only exists if we are not omitting the
19 ** ALTER TABLE logic from the build.
20 */
21 #ifndef SQLITE_OMIT_ALTERTABLE
22 
23 /*
24 ** Parameter zName is the name of a table that is about to be altered
25 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
26 ** If the table is a system table, this function leaves an error message
27 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
28 **
29 ** Or, if zName is not a system table, zero is returned.
30 */
31 static int isAlterableTable(Parse *pParse, Table *pTab){
32   if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
33 #ifndef SQLITE_OMIT_VIRTUALTABLE
34    || (pTab->tabFlags & TF_Eponymous)!=0
35    || ( (pTab->tabFlags & TF_Shadow)!=0
36         && sqlite3ReadOnlyShadowTables(pParse->db)
37    )
38 #endif
39   ){
40     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
41     return 1;
42   }
43   return 0;
44 }
45 
46 /*
47 ** Generate code to verify that the schemas of database zDb and, if
48 ** bTemp is not true, database "temp", can still be parsed. This is
49 ** called at the end of the generation of an ALTER TABLE ... RENAME ...
50 ** statement to ensure that the operation has not rendered any schema
51 ** objects unusable.
52 */
53 static void renameTestSchema(
54   Parse *pParse,                  /* Parse context */
55   const char *zDb,                /* Name of db to verify schema of */
56   int bTemp,                      /* True if this is the temp db */
57   const char *zWhen,              /* "when" part of error message */
58   int bNoDQS                      /* Do not allow DQS in the schema */
59 ){
60   pParse->colNamesSet = 1;
61   sqlite3NestedParse(pParse,
62       "SELECT 1 "
63       "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
64       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
65       " AND sql NOT LIKE 'create virtual%%'"
66       " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
67       zDb,
68       zDb, bTemp, zWhen, bNoDQS
69   );
70 
71   if( bTemp==0 ){
72     sqlite3NestedParse(pParse,
73         "SELECT 1 "
74         "FROM temp." DFLT_SCHEMA_TABLE " "
75         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
76         " AND sql NOT LIKE 'create virtual%%'"
77         " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
78         zDb, zWhen, bNoDQS
79     );
80   }
81 }
82 
83 /*
84 ** Generate VM code to replace any double-quoted strings (but not double-quoted
85 ** identifiers) within the "sql" column of the sqlite_schema table in
86 ** database zDb with their single-quoted equivalents. If argument bTemp is
87 ** not true, similarly update all SQL statements in the sqlite_schema table
88 ** of the temp db.
89 */
90 static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
91   sqlite3NestedParse(pParse,
92       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
93       " SET sql = sqlite_rename_quotefix(%Q, sql)"
94       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
95       " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
96   );
97   if( bTemp==0 ){
98     sqlite3NestedParse(pParse,
99       "UPDATE temp." DFLT_SCHEMA_TABLE
100       " SET sql = sqlite_rename_quotefix('temp', sql)"
101       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
102       " AND sql NOT LIKE 'create virtual%%'"
103     );
104   }
105 }
106 
107 /*
108 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
109 ** the temp database as well.
110 */
111 static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
112   Vdbe *v = pParse->pVdbe;
113   if( v ){
114     sqlite3ChangeCookie(pParse, iDb);
115     sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
116     if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
117   }
118 }
119 
120 /*
121 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
122 ** command.
123 */
124 void sqlite3AlterRenameTable(
125   Parse *pParse,            /* Parser context. */
126   SrcList *pSrc,            /* The table to rename. */
127   Token *pName              /* The new table name. */
128 ){
129   int iDb;                  /* Database that contains the table */
130   char *zDb;                /* Name of database iDb */
131   Table *pTab;              /* Table being renamed */
132   char *zName = 0;          /* NULL-terminated version of pName */
133   sqlite3 *db = pParse->db; /* Database connection */
134   int nTabName;             /* Number of UTF-8 characters in zTabName */
135   const char *zTabName;     /* Original name of the table */
136   Vdbe *v;
137   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
138   u32 savedDbFlags;         /* Saved value of db->mDbFlags */
139 
140   savedDbFlags = db->mDbFlags;
141   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
142   assert( pSrc->nSrc==1 );
143   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
144 
145   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
146   if( !pTab ) goto exit_rename_table;
147   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
148   zDb = db->aDb[iDb].zDbSName;
149   db->mDbFlags |= DBFLAG_PreferBuiltin;
150 
151   /* Get a NULL terminated version of the new table name. */
152   zName = sqlite3NameFromToken(db, pName);
153   if( !zName ) goto exit_rename_table;
154 
155   /* Check that a table or index named 'zName' does not already exist
156   ** in database iDb. If so, this is an error.
157   */
158   if( sqlite3FindTable(db, zName, zDb)
159    || sqlite3FindIndex(db, zName, zDb)
160    || sqlite3IsShadowTableOf(db, pTab, zName)
161   ){
162     sqlite3ErrorMsg(pParse,
163         "there is already another table or index with this name: %s", zName);
164     goto exit_rename_table;
165   }
166 
167   /* Make sure it is not a system table being altered, or a reserved name
168   ** that the table is being renamed to.
169   */
170   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
171     goto exit_rename_table;
172   }
173   if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
174     goto exit_rename_table;
175   }
176 
177 #ifndef SQLITE_OMIT_VIEW
178   if( pTab->pSelect ){
179     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
180     goto exit_rename_table;
181   }
182 #endif
183 
184 #ifndef SQLITE_OMIT_AUTHORIZATION
185   /* Invoke the authorization callback. */
186   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
187     goto exit_rename_table;
188   }
189 #endif
190 
191 #ifndef SQLITE_OMIT_VIRTUALTABLE
192   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
193     goto exit_rename_table;
194   }
195   if( IsVirtual(pTab) ){
196     pVTab = sqlite3GetVTable(db, pTab);
197     if( pVTab->pVtab->pModule->xRename==0 ){
198       pVTab = 0;
199     }
200   }
201 #endif
202 
203   /* Begin a transaction for database iDb. Then modify the schema cookie
204   ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
205   ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
206   ** nested SQL may raise an exception.  */
207   v = sqlite3GetVdbe(pParse);
208   if( v==0 ){
209     goto exit_rename_table;
210   }
211   sqlite3MayAbort(pParse);
212 
213   /* figure out how many UTF-8 characters are in zName */
214   zTabName = pTab->zName;
215   nTabName = sqlite3Utf8CharLen(zTabName, -1);
216 
217   /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
218   ** the schema to use the new table name.  */
219   sqlite3NestedParse(pParse,
220       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
221       "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
222       "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
223       "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
224       , zDb, zDb, zTabName, zName, (iDb==1), zTabName
225   );
226 
227   /* Update the tbl_name and name columns of the sqlite_schema table
228   ** as required.  */
229   sqlite3NestedParse(pParse,
230       "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
231           "tbl_name = %Q, "
232           "name = CASE "
233             "WHEN type='table' THEN %Q "
234             "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
235             "     AND type='index' THEN "
236              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
237             "ELSE name END "
238       "WHERE tbl_name=%Q COLLATE nocase AND "
239           "(type='table' OR type='index' OR type='trigger');",
240       zDb,
241       zName, zName, zName,
242       nTabName, zTabName
243   );
244 
245 #ifndef SQLITE_OMIT_AUTOINCREMENT
246   /* If the sqlite_sequence table exists in this database, then update
247   ** it with the new table name.
248   */
249   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
250     sqlite3NestedParse(pParse,
251         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
252         zDb, zName, pTab->zName);
253   }
254 #endif
255 
256   /* If the table being renamed is not itself part of the temp database,
257   ** edit view and trigger definitions within the temp database
258   ** as required.  */
259   if( iDb!=1 ){
260     sqlite3NestedParse(pParse,
261         "UPDATE sqlite_temp_schema SET "
262             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
263             "tbl_name = "
264               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
265               "  sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
266               "THEN %Q ELSE tbl_name END "
267             "WHERE type IN ('view', 'trigger')"
268         , zDb, zTabName, zName, zTabName, zDb, zName);
269   }
270 
271   /* If this is a virtual table, invoke the xRename() function if
272   ** one is defined. The xRename() callback will modify the names
273   ** of any resources used by the v-table implementation (including other
274   ** SQLite tables) that are identified by the name of the virtual table.
275   */
276 #ifndef SQLITE_OMIT_VIRTUALTABLE
277   if( pVTab ){
278     int i = ++pParse->nMem;
279     sqlite3VdbeLoadString(v, i, zName);
280     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
281   }
282 #endif
283 
284   renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
285   renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
286 
287 exit_rename_table:
288   sqlite3SrcListDelete(db, pSrc);
289   sqlite3DbFree(db, zName);
290   db->mDbFlags = savedDbFlags;
291 }
292 
293 /*
294 ** Write code that will raise an error if the table described by
295 ** zDb and zTab is not empty.
296 */
297 static void sqlite3ErrorIfNotEmpty(
298   Parse *pParse,        /* Parsing context */
299   const char *zDb,      /* Schema holding the table */
300   const char *zTab,     /* Table to check for empty */
301   const char *zErr      /* Error message text */
302 ){
303   sqlite3NestedParse(pParse,
304      "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
305      zErr, zDb, zTab
306   );
307 }
308 
309 /*
310 ** This function is called after an "ALTER TABLE ... ADD" statement
311 ** has been parsed. Argument pColDef contains the text of the new
312 ** column definition.
313 **
314 ** The Table structure pParse->pNewTable was extended to include
315 ** the new column during parsing.
316 */
317 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
318   Table *pNew;              /* Copy of pParse->pNewTable */
319   Table *pTab;              /* Table being altered */
320   int iDb;                  /* Database number */
321   const char *zDb;          /* Database name */
322   const char *zTab;         /* Table name */
323   char *zCol;               /* Null-terminated column definition */
324   Column *pCol;             /* The new column */
325   Expr *pDflt;              /* Default value for the new column */
326   sqlite3 *db;              /* The database connection; */
327   Vdbe *v;                  /* The prepared statement under construction */
328   int r1;                   /* Temporary registers */
329 
330   db = pParse->db;
331   if( pParse->nErr || db->mallocFailed ) return;
332   pNew = pParse->pNewTable;
333   assert( pNew );
334 
335   assert( sqlite3BtreeHoldsAllMutexes(db) );
336   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
337   zDb = db->aDb[iDb].zDbSName;
338   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
339   pCol = &pNew->aCol[pNew->nCol-1];
340   pDflt = pCol->pDflt;
341   pTab = sqlite3FindTable(db, zTab, zDb);
342   assert( pTab );
343 
344 #ifndef SQLITE_OMIT_AUTHORIZATION
345   /* Invoke the authorization callback. */
346   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
347     return;
348   }
349 #endif
350 
351 
352   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
353   ** If there is a NOT NULL constraint, then the default value for the
354   ** column must not be NULL.
355   */
356   if( pCol->colFlags & COLFLAG_PRIMKEY ){
357     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
358     return;
359   }
360   if( pNew->pIndex ){
361     sqlite3ErrorMsg(pParse,
362          "Cannot add a UNIQUE column");
363     return;
364   }
365   if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
366     /* If the default value for the new column was specified with a
367     ** literal NULL, then set pDflt to 0. This simplifies checking
368     ** for an SQL NULL default below.
369     */
370     assert( pDflt==0 || pDflt->op==TK_SPAN );
371     if( pDflt && pDflt->pLeft->op==TK_NULL ){
372       pDflt = 0;
373     }
374     if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
375       sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
376           "Cannot add a REFERENCES column with non-NULL default value");
377     }
378     if( pCol->notNull && !pDflt ){
379       sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
380           "Cannot add a NOT NULL column with default value NULL");
381     }
382 
383 
384     /* Ensure the default expression is something that sqlite3ValueFromExpr()
385     ** can handle (i.e. not CURRENT_TIME etc.)
386     */
387     if( pDflt ){
388       sqlite3_value *pVal = 0;
389       int rc;
390       rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
391       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
392       if( rc!=SQLITE_OK ){
393         assert( db->mallocFailed == 1 );
394         return;
395       }
396       if( !pVal ){
397         sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
398            "Cannot add a column with non-constant default");
399       }
400       sqlite3ValueFree(pVal);
401     }
402   }else if( pCol->colFlags & COLFLAG_STORED ){
403     sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
404   }
405 
406 
407   /* Modify the CREATE TABLE statement. */
408   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
409   if( zCol ){
410     char *zEnd = &zCol[pColDef->n-1];
411     u32 savedDbFlags = db->mDbFlags;
412     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
413       *zEnd-- = '\0';
414     }
415     db->mDbFlags |= DBFLAG_PreferBuiltin;
416     /* substr() operations on characters, but addColOffset is in bytes. So we
417     ** have to use printf() to translate between these units: */
418     sqlite3NestedParse(pParse,
419         "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
420           "sql = printf('%%.%ds, ',sql) || %Q"
421           " || substr(sql,1+length(printf('%%.%ds',sql))) "
422         "WHERE type = 'table' AND name = %Q",
423       zDb, pNew->addColOffset, zCol, pNew->addColOffset,
424       zTab
425     );
426     sqlite3DbFree(db, zCol);
427     db->mDbFlags = savedDbFlags;
428   }
429 
430   v = sqlite3GetVdbe(pParse);
431   if( v ){
432     /* Make sure the schema version is at least 3.  But do not upgrade
433     ** from less than 3 to 4, as that will corrupt any preexisting DESC
434     ** index.
435     */
436     r1 = sqlite3GetTempReg(pParse);
437     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
438     sqlite3VdbeUsesBtree(v, iDb);
439     sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
440     sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
441     VdbeCoverage(v);
442     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
443     sqlite3ReleaseTempReg(pParse, r1);
444 
445     /* Reload the table definition */
446     renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
447 
448     /* Verify that constraints are still satisfied */
449     if( pNew->pCheck!=0
450      || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
451     ){
452       sqlite3NestedParse(pParse,
453         "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
454         " THEN raise(ABORT,'CHECK constraint failed')"
455         " ELSE raise(ABORT,'NOT NULL constraint failed')"
456         " END"
457         "  FROM pragma_quick_check(\"%w\",\"%w\")"
458         " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
459         zTab, zDb
460       );
461     }
462   }
463 }
464 
465 /*
466 ** This function is called by the parser after the table-name in
467 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
468 ** pSrc is the full-name of the table being altered.
469 **
470 ** This routine makes a (partial) copy of the Table structure
471 ** for the table being altered and sets Parse.pNewTable to point
472 ** to it. Routines called by the parser as the column definition
473 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
474 ** the copy. The copy of the Table structure is deleted by tokenize.c
475 ** after parsing is finished.
476 **
477 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
478 ** coding the "ALTER TABLE ... ADD" statement.
479 */
480 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
481   Table *pNew;
482   Table *pTab;
483   int iDb;
484   int i;
485   int nAlloc;
486   sqlite3 *db = pParse->db;
487 
488   /* Look up the table being altered. */
489   assert( pParse->pNewTable==0 );
490   assert( sqlite3BtreeHoldsAllMutexes(db) );
491   if( db->mallocFailed ) goto exit_begin_add_column;
492   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
493   if( !pTab ) goto exit_begin_add_column;
494 
495 #ifndef SQLITE_OMIT_VIRTUALTABLE
496   if( IsVirtual(pTab) ){
497     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
498     goto exit_begin_add_column;
499   }
500 #endif
501 
502   /* Make sure this is not an attempt to ALTER a view. */
503   if( pTab->pSelect ){
504     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
505     goto exit_begin_add_column;
506   }
507   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
508     goto exit_begin_add_column;
509   }
510 
511   sqlite3MayAbort(pParse);
512   assert( pTab->addColOffset>0 );
513   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
514 
515   /* Put a copy of the Table struct in Parse.pNewTable for the
516   ** sqlite3AddColumn() function and friends to modify.  But modify
517   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
518   ** prefix, we insure that the name will not collide with an existing
519   ** table because user table are not allowed to have the "sqlite_"
520   ** prefix on their name.
521   */
522   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
523   if( !pNew ) goto exit_begin_add_column;
524   pParse->pNewTable = pNew;
525   pNew->nTabRef = 1;
526   pNew->nCol = pTab->nCol;
527   assert( pNew->nCol>0 );
528   nAlloc = (((pNew->nCol-1)/8)*8)+8;
529   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
530   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
531   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
532   if( !pNew->aCol || !pNew->zName ){
533     assert( db->mallocFailed );
534     goto exit_begin_add_column;
535   }
536   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
537   for(i=0; i<pNew->nCol; i++){
538     Column *pCol = &pNew->aCol[i];
539     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
540     pCol->hName = sqlite3StrIHash(pCol->zName);
541     pCol->zColl = 0;
542     pCol->pDflt = 0;
543   }
544   pNew->pSchema = db->aDb[iDb].pSchema;
545   pNew->addColOffset = pTab->addColOffset;
546   pNew->nTabRef = 1;
547 
548 exit_begin_add_column:
549   sqlite3SrcListDelete(db, pSrc);
550   return;
551 }
552 
553 /*
554 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
555 ** command. This function checks if the table is a view or virtual
556 ** table (columns of views or virtual tables may not be renamed). If so,
557 ** it loads an error message into pParse and returns non-zero.
558 **
559 ** Or, if pTab is not a view or virtual table, zero is returned.
560 */
561 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
562 static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
563   const char *zType = 0;
564 #ifndef SQLITE_OMIT_VIEW
565   if( pTab->pSelect ){
566     zType = "view";
567   }
568 #endif
569 #ifndef SQLITE_OMIT_VIRTUALTABLE
570   if( IsVirtual(pTab) ){
571     zType = "virtual table";
572   }
573 #endif
574   if( zType ){
575     sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
576         (bDrop ? "drop column from" : "rename columns of"),
577         zType, pTab->zName
578     );
579     return 1;
580   }
581   return 0;
582 }
583 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
584 # define isRealTable(x,y,z) (0)
585 #endif
586 
587 /*
588 ** Handles the following parser reduction:
589 **
590 **  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
591 */
592 void sqlite3AlterRenameColumn(
593   Parse *pParse,                  /* Parsing context */
594   SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */
595   Token *pOld,                    /* Name of column being changed */
596   Token *pNew                     /* New column name */
597 ){
598   sqlite3 *db = pParse->db;       /* Database connection */
599   Table *pTab;                    /* Table being updated */
600   int iCol;                       /* Index of column being renamed */
601   char *zOld = 0;                 /* Old column name */
602   char *zNew = 0;                 /* New column name */
603   const char *zDb;                /* Name of schema containing the table */
604   int iSchema;                    /* Index of the schema */
605   int bQuote;                     /* True to quote the new name */
606 
607   /* Locate the table to be altered */
608   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
609   if( !pTab ) goto exit_rename_column;
610 
611   /* Cannot alter a system table */
612   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
613   if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
614 
615   /* Which schema holds the table to be altered */
616   iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
617   assert( iSchema>=0 );
618   zDb = db->aDb[iSchema].zDbSName;
619 
620 #ifndef SQLITE_OMIT_AUTHORIZATION
621   /* Invoke the authorization callback. */
622   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
623     goto exit_rename_column;
624   }
625 #endif
626 
627   /* Make sure the old name really is a column name in the table to be
628   ** altered.  Set iCol to be the index of the column being renamed */
629   zOld = sqlite3NameFromToken(db, pOld);
630   if( !zOld ) goto exit_rename_column;
631   for(iCol=0; iCol<pTab->nCol; iCol++){
632     if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
633   }
634   if( iCol==pTab->nCol ){
635     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
636     goto exit_rename_column;
637   }
638 
639   /* Ensure the schema contains no double-quoted strings */
640   renameTestSchema(pParse, zDb, iSchema==1, "", 0);
641   renameFixQuotes(pParse, zDb, iSchema==1);
642 
643   /* Do the rename operation using a recursive UPDATE statement that
644   ** uses the sqlite_rename_column() SQL function to compute the new
645   ** CREATE statement text for the sqlite_schema table.
646   */
647   sqlite3MayAbort(pParse);
648   zNew = sqlite3NameFromToken(db, pNew);
649   if( !zNew ) goto exit_rename_column;
650   assert( pNew->n>0 );
651   bQuote = sqlite3Isquote(pNew->z[0]);
652   sqlite3NestedParse(pParse,
653       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
654       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
655       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
656       " AND (type != 'index' OR tbl_name = %Q)"
657       " AND sql NOT LIKE 'create virtual%%'",
658       zDb,
659       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
660       pTab->zName
661   );
662 
663   sqlite3NestedParse(pParse,
664       "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
665       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
666       "WHERE type IN ('trigger', 'view')",
667       zDb, pTab->zName, iCol, zNew, bQuote
668   );
669 
670   /* Drop and reload the database schema. */
671   renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
672   renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
673 
674  exit_rename_column:
675   sqlite3SrcListDelete(db, pSrc);
676   sqlite3DbFree(db, zOld);
677   sqlite3DbFree(db, zNew);
678   return;
679 }
680 
681 /*
682 ** Each RenameToken object maps an element of the parse tree into
683 ** the token that generated that element.  The parse tree element
684 ** might be one of:
685 **
686 **     *  A pointer to an Expr that represents an ID
687 **     *  The name of a table column in Column.zName
688 **
689 ** A list of RenameToken objects can be constructed during parsing.
690 ** Each new object is created by sqlite3RenameTokenMap().
691 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
692 ** routine is used to keep the mapping current.
693 **
694 ** After the parse finishes, renameTokenFind() routine can be used
695 ** to look up the actual token value that created some element in
696 ** the parse tree.
697 */
698 struct RenameToken {
699   void *p;               /* Parse tree element created by token t */
700   Token t;               /* The token that created parse tree element p */
701   RenameToken *pNext;    /* Next is a list of all RenameToken objects */
702 };
703 
704 /*
705 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
706 ** down into the Walker.
707 */
708 typedef struct RenameCtx RenameCtx;
709 struct RenameCtx {
710   RenameToken *pList;             /* List of tokens to overwrite */
711   int nList;                      /* Number of tokens in pList */
712   int iCol;                       /* Index of column being renamed */
713   Table *pTab;                    /* Table being ALTERed */
714   const char *zOld;               /* Old column name */
715 };
716 
717 #ifdef SQLITE_DEBUG
718 /*
719 ** This function is only for debugging. It performs two tasks:
720 **
721 **   1. Checks that pointer pPtr does not already appear in the
722 **      rename-token list.
723 **
724 **   2. Dereferences each pointer in the rename-token list.
725 **
726 ** The second is most effective when debugging under valgrind or
727 ** address-sanitizer or similar. If any of these pointers no longer
728 ** point to valid objects, an exception is raised by the memory-checking
729 ** tool.
730 **
731 ** The point of this is to prevent comparisons of invalid pointer values.
732 ** Even though this always seems to work, it is undefined according to the
733 ** C standard. Example of undefined comparison:
734 **
735 **     sqlite3_free(x);
736 **     if( x==y ) ...
737 **
738 ** Technically, as x no longer points into a valid object or to the byte
739 ** following a valid object, it may not be used in comparison operations.
740 */
741 static void renameTokenCheckAll(Parse *pParse, void *pPtr){
742   if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
743     RenameToken *p;
744     u8 i = 0;
745     for(p=pParse->pRename; p; p=p->pNext){
746       if( p->p ){
747         assert( p->p!=pPtr );
748         i += *(u8*)(p->p);
749       }
750     }
751   }
752 }
753 #else
754 # define renameTokenCheckAll(x,y)
755 #endif
756 
757 /*
758 ** Remember that the parser tree element pPtr was created using
759 ** the token pToken.
760 **
761 ** In other words, construct a new RenameToken object and add it
762 ** to the list of RenameToken objects currently being built up
763 ** in pParse->pRename.
764 **
765 ** The pPtr argument is returned so that this routine can be used
766 ** with tail recursion in tokenExpr() routine, for a small performance
767 ** improvement.
768 */
769 void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
770   RenameToken *pNew;
771   assert( pPtr || pParse->db->mallocFailed );
772   renameTokenCheckAll(pParse, pPtr);
773   if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
774     pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
775     if( pNew ){
776       pNew->p = pPtr;
777       pNew->t = *pToken;
778       pNew->pNext = pParse->pRename;
779       pParse->pRename = pNew;
780     }
781   }
782 
783   return pPtr;
784 }
785 
786 /*
787 ** It is assumed that there is already a RenameToken object associated
788 ** with parse tree element pFrom. This function remaps the associated token
789 ** to parse tree element pTo.
790 */
791 void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
792   RenameToken *p;
793   renameTokenCheckAll(pParse, pTo);
794   for(p=pParse->pRename; p; p=p->pNext){
795     if( p->p==pFrom ){
796       p->p = pTo;
797       break;
798     }
799   }
800 }
801 
802 /*
803 ** Walker callback used by sqlite3RenameExprUnmap().
804 */
805 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
806   Parse *pParse = pWalker->pParse;
807   sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
808   return WRC_Continue;
809 }
810 
811 /*
812 ** Iterate through the Select objects that are part of WITH clauses attached
813 ** to select statement pSelect.
814 */
815 static void renameWalkWith(Walker *pWalker, Select *pSelect){
816   With *pWith = pSelect->pWith;
817   if( pWith ){
818     Parse *pParse = pWalker->pParse;
819     int i;
820     With *pCopy = 0;
821     assert( pWith->nCte>0 );
822     if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
823       /* Push a copy of the With object onto the with-stack. We use a copy
824       ** here as the original will be expanded and resolved (flags SF_Expanded
825       ** and SF_Resolved) below. And the parser code that uses the with-stack
826       ** fails if the Select objects on it have already been expanded and
827       ** resolved.  */
828       pCopy = sqlite3WithDup(pParse->db, pWith);
829       pCopy = sqlite3WithPush(pParse, pCopy, 1);
830     }
831     for(i=0; i<pWith->nCte; i++){
832       Select *p = pWith->a[i].pSelect;
833       NameContext sNC;
834       memset(&sNC, 0, sizeof(sNC));
835       sNC.pParse = pParse;
836       if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
837       sqlite3WalkSelect(pWalker, p);
838       sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
839     }
840     if( pCopy && pParse->pWith==pCopy ){
841       pParse->pWith = pCopy->pOuter;
842     }
843   }
844 }
845 
846 /*
847 ** Unmap all tokens in the IdList object passed as the second argument.
848 */
849 static void unmapColumnIdlistNames(
850   Parse *pParse,
851   IdList *pIdList
852 ){
853   if( pIdList ){
854     int ii;
855     for(ii=0; ii<pIdList->nId; ii++){
856       sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
857     }
858   }
859 }
860 
861 /*
862 ** Walker callback used by sqlite3RenameExprUnmap().
863 */
864 static int renameUnmapSelectCb(Walker *pWalker, Select *p){
865   Parse *pParse = pWalker->pParse;
866   int i;
867   if( pParse->nErr ) return WRC_Abort;
868   if( p->selFlags & (SF_View|SF_CopyCte) ){
869     testcase( p->selFlags & SF_View );
870     testcase( p->selFlags & SF_CopyCte );
871     return WRC_Prune;
872   }
873   if( ALWAYS(p->pEList) ){
874     ExprList *pList = p->pEList;
875     for(i=0; i<pList->nExpr; i++){
876       if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
877         sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
878       }
879     }
880   }
881   if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */
882     SrcList *pSrc = p->pSrc;
883     for(i=0; i<pSrc->nSrc; i++){
884       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
885       if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
886       unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
887     }
888   }
889 
890   renameWalkWith(pWalker, p);
891   return WRC_Continue;
892 }
893 
894 /*
895 ** Remove all nodes that are part of expression pExpr from the rename list.
896 */
897 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
898   u8 eMode = pParse->eParseMode;
899   Walker sWalker;
900   memset(&sWalker, 0, sizeof(Walker));
901   sWalker.pParse = pParse;
902   sWalker.xExprCallback = renameUnmapExprCb;
903   sWalker.xSelectCallback = renameUnmapSelectCb;
904   pParse->eParseMode = PARSE_MODE_UNMAP;
905   sqlite3WalkExpr(&sWalker, pExpr);
906   pParse->eParseMode = eMode;
907 }
908 
909 /*
910 ** Remove all nodes that are part of expression-list pEList from the
911 ** rename list.
912 */
913 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
914   if( pEList ){
915     int i;
916     Walker sWalker;
917     memset(&sWalker, 0, sizeof(Walker));
918     sWalker.pParse = pParse;
919     sWalker.xExprCallback = renameUnmapExprCb;
920     sqlite3WalkExprList(&sWalker, pEList);
921     for(i=0; i<pEList->nExpr; i++){
922       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
923         sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
924       }
925     }
926   }
927 }
928 
929 /*
930 ** Free the list of RenameToken objects given in the second argument
931 */
932 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
933   RenameToken *pNext;
934   RenameToken *p;
935   for(p=pToken; p; p=pNext){
936     pNext = p->pNext;
937     sqlite3DbFree(db, p);
938   }
939 }
940 
941 /*
942 ** Search the Parse object passed as the first argument for a RenameToken
943 ** object associated with parse tree element pPtr. If found, return a pointer
944 ** to it. Otherwise, return NULL.
945 **
946 ** If the second argument passed to this function is not NULL and a matching
947 ** RenameToken object is found, remove it from the Parse object and add it to
948 ** the list maintained by the RenameCtx object.
949 */
950 static RenameToken *renameTokenFind(
951   Parse *pParse,
952   struct RenameCtx *pCtx,
953   void *pPtr
954 ){
955   RenameToken **pp;
956   if( NEVER(pPtr==0) ){
957     return 0;
958   }
959   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
960     if( (*pp)->p==pPtr ){
961       RenameToken *pToken = *pp;
962       if( pCtx ){
963         *pp = pToken->pNext;
964         pToken->pNext = pCtx->pList;
965         pCtx->pList = pToken;
966         pCtx->nList++;
967       }
968       return pToken;
969     }
970   }
971   return 0;
972 }
973 
974 /*
975 ** This is a Walker select callback. It does nothing. It is only required
976 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
977 ** descend into sub-select statements.
978 */
979 static int renameColumnSelectCb(Walker *pWalker, Select *p){
980   if( p->selFlags & (SF_View|SF_CopyCte) ){
981     testcase( p->selFlags & SF_View );
982     testcase( p->selFlags & SF_CopyCte );
983     return WRC_Prune;
984   }
985   renameWalkWith(pWalker, p);
986   return WRC_Continue;
987 }
988 
989 /*
990 ** This is a Walker expression callback.
991 **
992 ** For every TK_COLUMN node in the expression tree, search to see
993 ** if the column being references is the column being renamed by an
994 ** ALTER TABLE statement.  If it is, then attach its associated
995 ** RenameToken object to the list of RenameToken objects being
996 ** constructed in RenameCtx object at pWalker->u.pRename.
997 */
998 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
999   RenameCtx *p = pWalker->u.pRename;
1000   if( pExpr->op==TK_TRIGGER
1001    && pExpr->iColumn==p->iCol
1002    && pWalker->pParse->pTriggerTab==p->pTab
1003   ){
1004     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
1005   }else if( pExpr->op==TK_COLUMN
1006    && pExpr->iColumn==p->iCol
1007    && p->pTab==pExpr->y.pTab
1008   ){
1009     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
1010   }
1011   return WRC_Continue;
1012 }
1013 
1014 /*
1015 ** The RenameCtx contains a list of tokens that reference a column that
1016 ** is being renamed by an ALTER TABLE statement.  Return the "last"
1017 ** RenameToken in the RenameCtx and remove that RenameToken from the
1018 ** RenameContext.  "Last" means the last RenameToken encountered when
1019 ** the input SQL is parsed from left to right.  Repeated calls to this routine
1020 ** return all column name tokens in the order that they are encountered
1021 ** in the SQL statement.
1022 */
1023 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
1024   RenameToken *pBest = pCtx->pList;
1025   RenameToken *pToken;
1026   RenameToken **pp;
1027 
1028   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1029     if( pToken->t.z>pBest->t.z ) pBest = pToken;
1030   }
1031   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1032   *pp = pBest->pNext;
1033 
1034   return pBest;
1035 }
1036 
1037 /*
1038 ** An error occured while parsing or otherwise processing a database
1039 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1040 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1041 ** sub-routine is currently stored in pParse->zErrMsg. This function
1042 ** adds context to the error message and then stores it in pCtx.
1043 */
1044 static void renameColumnParseError(
1045   sqlite3_context *pCtx,
1046   const char *zWhen,
1047   sqlite3_value *pType,
1048   sqlite3_value *pObject,
1049   Parse *pParse
1050 ){
1051   const char *zT = (const char*)sqlite3_value_text(pType);
1052   const char *zN = (const char*)sqlite3_value_text(pObject);
1053   char *zErr;
1054 
1055   zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1056       zT, zN, (zWhen[0] ? " " : ""), zWhen,
1057       pParse->zErrMsg
1058   );
1059   sqlite3_result_error(pCtx, zErr, -1);
1060   sqlite3_free(zErr);
1061 }
1062 
1063 /*
1064 ** For each name in the the expression-list pEList (i.e. each
1065 ** pEList->a[i].zName) that matches the string in zOld, extract the
1066 ** corresponding rename-token from Parse object pParse and add it
1067 ** to the RenameCtx pCtx.
1068 */
1069 static void renameColumnElistNames(
1070   Parse *pParse,
1071   RenameCtx *pCtx,
1072   ExprList *pEList,
1073   const char *zOld
1074 ){
1075   if( pEList ){
1076     int i;
1077     for(i=0; i<pEList->nExpr; i++){
1078       char *zName = pEList->a[i].zEName;
1079       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1080        && ALWAYS(zName!=0)
1081        && 0==sqlite3_stricmp(zName, zOld)
1082       ){
1083         renameTokenFind(pParse, pCtx, (void*)zName);
1084       }
1085     }
1086   }
1087 }
1088 
1089 /*
1090 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1091 ** that matches the string in zOld, extract the corresponding rename-token
1092 ** from Parse object pParse and add it to the RenameCtx pCtx.
1093 */
1094 static void renameColumnIdlistNames(
1095   Parse *pParse,
1096   RenameCtx *pCtx,
1097   IdList *pIdList,
1098   const char *zOld
1099 ){
1100   if( pIdList ){
1101     int i;
1102     for(i=0; i<pIdList->nId; i++){
1103       char *zName = pIdList->a[i].zName;
1104       if( 0==sqlite3_stricmp(zName, zOld) ){
1105         renameTokenFind(pParse, pCtx, (void*)zName);
1106       }
1107     }
1108   }
1109 }
1110 
1111 
1112 /*
1113 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
1114 ** is initialized by this function before it is used.
1115 */
1116 static int renameParseSql(
1117   Parse *p,                       /* Memory to use for Parse object */
1118   const char *zDb,                /* Name of schema SQL belongs to */
1119   sqlite3 *db,                    /* Database handle */
1120   const char *zSql,               /* SQL to parse */
1121   int bTemp                       /* True if SQL is from temp schema */
1122 ){
1123   int rc;
1124   char *zErr = 0;
1125 
1126   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1127 
1128   /* Parse the SQL statement passed as the first argument. If no error
1129   ** occurs and the parse does not result in a new table, index or
1130   ** trigger object, the database must be corrupt. */
1131   memset(p, 0, sizeof(Parse));
1132   p->eParseMode = PARSE_MODE_RENAME;
1133   p->db = db;
1134   p->nQueryLoop = 1;
1135   rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
1136   assert( p->zErrMsg==0 );
1137   assert( rc!=SQLITE_OK || zErr==0 );
1138   p->zErrMsg = zErr;
1139   if( db->mallocFailed ) rc = SQLITE_NOMEM;
1140   if( rc==SQLITE_OK
1141    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1142   ){
1143     rc = SQLITE_CORRUPT_BKPT;
1144   }
1145 
1146 #ifdef SQLITE_DEBUG
1147   /* Ensure that all mappings in the Parse.pRename list really do map to
1148   ** a part of the input string.  */
1149   if( rc==SQLITE_OK ){
1150     int nSql = sqlite3Strlen30(zSql);
1151     RenameToken *pToken;
1152     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1153       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1154     }
1155   }
1156 #endif
1157 
1158   db->init.iDb = 0;
1159   return rc;
1160 }
1161 
1162 /*
1163 ** This function edits SQL statement zSql, replacing each token identified
1164 ** by the linked list pRename with the text of zNew. If argument bQuote is
1165 ** true, then zNew is always quoted first. If no error occurs, the result
1166 ** is loaded into context object pCtx as the result.
1167 **
1168 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1169 ** pCtx and an SQLite error code returned.
1170 */
1171 static int renameEditSql(
1172   sqlite3_context *pCtx,          /* Return result here */
1173   RenameCtx *pRename,             /* Rename context */
1174   const char *zSql,               /* SQL statement to edit */
1175   const char *zNew,               /* New token text */
1176   int bQuote                      /* True to always quote token */
1177 ){
1178   i64 nNew = sqlite3Strlen30(zNew);
1179   i64 nSql = sqlite3Strlen30(zSql);
1180   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1181   int rc = SQLITE_OK;
1182   char *zQuot = 0;
1183   char *zOut;
1184   i64 nQuot = 0;
1185   char *zBuf1 = 0;
1186   char *zBuf2 = 0;
1187 
1188   if( zNew ){
1189     /* Set zQuot to point to a buffer containing a quoted copy of the
1190     ** identifier zNew. If the corresponding identifier in the original
1191     ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1192     ** point to zQuot so that all substitutions are made using the
1193     ** quoted version of the new column name.  */
1194     zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
1195     if( zQuot==0 ){
1196       return SQLITE_NOMEM;
1197     }else{
1198       nQuot = sqlite3Strlen30(zQuot)-1;
1199     }
1200 
1201     assert( nQuot>=nNew );
1202     zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1203   }else{
1204     zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1205     if( zOut ){
1206       zBuf1 = &zOut[nSql*2+1];
1207       zBuf2 = &zOut[nSql*4+2];
1208     }
1209   }
1210 
1211   /* At this point pRename->pList contains a list of RenameToken objects
1212   ** corresponding to all tokens in the input SQL that must be replaced
1213   ** with the new column name, or with single-quoted versions of themselves.
1214   ** All that remains is to construct and return the edited SQL string. */
1215   if( zOut ){
1216     int nOut = nSql;
1217     memcpy(zOut, zSql, nSql);
1218     while( pRename->pList ){
1219       int iOff;                   /* Offset of token to replace in zOut */
1220       u32 nReplace;
1221       const char *zReplace;
1222       RenameToken *pBest = renameColumnTokenNext(pRename);
1223 
1224       if( zNew ){
1225         if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
1226           nReplace = nNew;
1227           zReplace = zNew;
1228         }else{
1229           nReplace = nQuot;
1230           zReplace = zQuot;
1231           if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
1232         }
1233       }else{
1234         /* Dequote the double-quoted token. Then requote it again, this time
1235         ** using single quotes. If the character immediately following the
1236         ** original token within the input SQL was a single quote ('), then
1237         ** add another space after the new, single-quoted version of the
1238         ** token. This is so that (SELECT "string"'alias') maps to
1239         ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias').  */
1240         memcpy(zBuf1, pBest->t.z, pBest->t.n);
1241         zBuf1[pBest->t.n] = 0;
1242         sqlite3Dequote(zBuf1);
1243         sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1244             pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1245         );
1246         zReplace = zBuf2;
1247         nReplace = sqlite3Strlen30(zReplace);
1248       }
1249 
1250       iOff = pBest->t.z - zSql;
1251       if( pBest->t.n!=nReplace ){
1252         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1253             nOut - (iOff + pBest->t.n)
1254         );
1255         nOut += nReplace - pBest->t.n;
1256         zOut[nOut] = '\0';
1257       }
1258       memcpy(&zOut[iOff], zReplace, nReplace);
1259       sqlite3DbFree(db, pBest);
1260     }
1261 
1262     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1263     sqlite3DbFree(db, zOut);
1264   }else{
1265     rc = SQLITE_NOMEM;
1266   }
1267 
1268   sqlite3_free(zQuot);
1269   return rc;
1270 }
1271 
1272 /*
1273 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1274 ** it was read from the schema of database zDb. Return SQLITE_OK if
1275 ** successful. Otherwise, return an SQLite error code and leave an error
1276 ** message in the Parse object.
1277 */
1278 static int renameResolveTrigger(Parse *pParse){
1279   sqlite3 *db = pParse->db;
1280   Trigger *pNew = pParse->pNewTrigger;
1281   TriggerStep *pStep;
1282   NameContext sNC;
1283   int rc = SQLITE_OK;
1284 
1285   memset(&sNC, 0, sizeof(sNC));
1286   sNC.pParse = pParse;
1287   assert( pNew->pTabSchema );
1288   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1289       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1290   );
1291   pParse->eTriggerOp = pNew->op;
1292   /* ALWAYS() because if the table of the trigger does not exist, the
1293   ** error would have been hit before this point */
1294   if( ALWAYS(pParse->pTriggerTab) ){
1295     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1296   }
1297 
1298   /* Resolve symbols in WHEN clause */
1299   if( rc==SQLITE_OK && pNew->pWhen ){
1300     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1301   }
1302 
1303   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1304     if( pStep->pSelect ){
1305       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1306       if( pParse->nErr ) rc = pParse->rc;
1307     }
1308     if( rc==SQLITE_OK && pStep->zTarget ){
1309       SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1310       if( pSrc ){
1311         int i;
1312         for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
1313           SrcItem *p = &pSrc->a[i];
1314           p->iCursor = pParse->nTab++;
1315           if( p->pSelect ){
1316             sqlite3SelectPrep(pParse, p->pSelect, 0);
1317             sqlite3ExpandSubquery(pParse, p);
1318             assert( i>0 );
1319             assert( pStep->pFrom->a[i-1].pSelect );
1320             sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
1321           }else{
1322             p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1323             if( p->pTab==0 ){
1324               rc = SQLITE_ERROR;
1325             }else{
1326               p->pTab->nTabRef++;
1327               rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1328             }
1329           }
1330         }
1331         sNC.pSrcList = pSrc;
1332         if( rc==SQLITE_OK && pStep->pWhere ){
1333           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1334         }
1335         if( rc==SQLITE_OK ){
1336           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1337         }
1338         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1339         if( pStep->pUpsert && rc==SQLITE_OK ){
1340           Upsert *pUpsert = pStep->pUpsert;
1341           pUpsert->pUpsertSrc = pSrc;
1342           sNC.uNC.pUpsert = pUpsert;
1343           sNC.ncFlags = NC_UUpsert;
1344           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1345           if( rc==SQLITE_OK ){
1346             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1347             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1348           }
1349           if( rc==SQLITE_OK ){
1350             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1351           }
1352           if( rc==SQLITE_OK ){
1353             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1354           }
1355           sNC.ncFlags = 0;
1356         }
1357         sNC.pSrcList = 0;
1358         sqlite3SrcListDelete(db, pSrc);
1359       }else{
1360         rc = SQLITE_NOMEM;
1361       }
1362     }
1363   }
1364   return rc;
1365 }
1366 
1367 /*
1368 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1369 ** objects that are part of the trigger passed as the second argument.
1370 */
1371 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1372   TriggerStep *pStep;
1373 
1374   /* Find tokens to edit in WHEN clause */
1375   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1376 
1377   /* Find tokens to edit in trigger steps */
1378   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1379     sqlite3WalkSelect(pWalker, pStep->pSelect);
1380     sqlite3WalkExpr(pWalker, pStep->pWhere);
1381     sqlite3WalkExprList(pWalker, pStep->pExprList);
1382     if( pStep->pUpsert ){
1383       Upsert *pUpsert = pStep->pUpsert;
1384       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1385       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1386       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1387       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1388     }
1389     if( pStep->pFrom ){
1390       int i;
1391       for(i=0; i<pStep->pFrom->nSrc; i++){
1392         sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1393       }
1394     }
1395   }
1396 }
1397 
1398 /*
1399 ** Free the contents of Parse object (*pParse). Do not free the memory
1400 ** occupied by the Parse object itself.
1401 */
1402 static void renameParseCleanup(Parse *pParse){
1403   sqlite3 *db = pParse->db;
1404   Index *pIdx;
1405   if( pParse->pVdbe ){
1406     sqlite3VdbeFinalize(pParse->pVdbe);
1407   }
1408   sqlite3DeleteTable(db, pParse->pNewTable);
1409   while( (pIdx = pParse->pNewIndex)!=0 ){
1410     pParse->pNewIndex = pIdx->pNext;
1411     sqlite3FreeIndex(db, pIdx);
1412   }
1413   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1414   sqlite3DbFree(db, pParse->zErrMsg);
1415   renameTokenFree(db, pParse->pRename);
1416   sqlite3ParserReset(pParse);
1417 }
1418 
1419 /*
1420 ** SQL function:
1421 **
1422 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1423 **
1424 **   0. zSql:     SQL statement to rewrite
1425 **   1. type:     Type of object ("table", "view" etc.)
1426 **   2. object:   Name of object
1427 **   3. Database: Database name (e.g. "main")
1428 **   4. Table:    Table name
1429 **   5. iCol:     Index of column to rename
1430 **   6. zNew:     New column name
1431 **   7. bQuote:   Non-zero if the new column name should be quoted.
1432 **   8. bTemp:    True if zSql comes from temp schema
1433 **
1434 ** Do a column rename operation on the CREATE statement given in zSql.
1435 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1436 ** into zNew.  The name should be quoted if bQuote is true.
1437 **
1438 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1439 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1440 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1441 */
1442 static void renameColumnFunc(
1443   sqlite3_context *context,
1444   int NotUsed,
1445   sqlite3_value **argv
1446 ){
1447   sqlite3 *db = sqlite3_context_db_handle(context);
1448   RenameCtx sCtx;
1449   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1450   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1451   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1452   int iCol = sqlite3_value_int(argv[5]);
1453   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1454   int bQuote = sqlite3_value_int(argv[7]);
1455   int bTemp = sqlite3_value_int(argv[8]);
1456   const char *zOld;
1457   int rc;
1458   Parse sParse;
1459   Walker sWalker;
1460   Index *pIdx;
1461   int i;
1462   Table *pTab;
1463 #ifndef SQLITE_OMIT_AUTHORIZATION
1464   sqlite3_xauth xAuth = db->xAuth;
1465 #endif
1466 
1467   UNUSED_PARAMETER(NotUsed);
1468   if( zSql==0 ) return;
1469   if( zTable==0 ) return;
1470   if( zNew==0 ) return;
1471   if( iCol<0 ) return;
1472   sqlite3BtreeEnterAll(db);
1473   pTab = sqlite3FindTable(db, zTable, zDb);
1474   if( pTab==0 || iCol>=pTab->nCol ){
1475     sqlite3BtreeLeaveAll(db);
1476     return;
1477   }
1478   zOld = pTab->aCol[iCol].zName;
1479   memset(&sCtx, 0, sizeof(sCtx));
1480   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1481 
1482 #ifndef SQLITE_OMIT_AUTHORIZATION
1483   db->xAuth = 0;
1484 #endif
1485   rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
1486 
1487   /* Find tokens that need to be replaced. */
1488   memset(&sWalker, 0, sizeof(Walker));
1489   sWalker.pParse = &sParse;
1490   sWalker.xExprCallback = renameColumnExprCb;
1491   sWalker.xSelectCallback = renameColumnSelectCb;
1492   sWalker.u.pRename = &sCtx;
1493 
1494   sCtx.pTab = pTab;
1495   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1496   if( sParse.pNewTable ){
1497     Select *pSelect = sParse.pNewTable->pSelect;
1498     if( pSelect ){
1499       pSelect->selFlags &= ~SF_View;
1500       sParse.rc = SQLITE_OK;
1501       sqlite3SelectPrep(&sParse, pSelect, 0);
1502       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1503       if( rc==SQLITE_OK ){
1504         sqlite3WalkSelect(&sWalker, pSelect);
1505       }
1506       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1507     }else{
1508       /* A regular table */
1509       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1510       FKey *pFKey;
1511       assert( sParse.pNewTable->pSelect==0 );
1512       sCtx.pTab = sParse.pNewTable;
1513       if( bFKOnly==0 ){
1514         if( iCol<sParse.pNewTable->nCol ){
1515           renameTokenFind(
1516               &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1517           );
1518         }
1519         if( sCtx.iCol<0 ){
1520           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1521         }
1522         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1523         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1524           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1525         }
1526         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1527           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1528         }
1529 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1530         for(i=0; i<sParse.pNewTable->nCol; i++){
1531           sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1532         }
1533 #endif
1534       }
1535 
1536       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1537         for(i=0; i<pFKey->nCol; i++){
1538           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1539             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1540           }
1541           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1542            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1543           ){
1544             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1545           }
1546         }
1547       }
1548     }
1549   }else if( sParse.pNewIndex ){
1550     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1551     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1552   }else{
1553     /* A trigger */
1554     TriggerStep *pStep;
1555     rc = renameResolveTrigger(&sParse);
1556     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1557 
1558     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1559       if( pStep->zTarget ){
1560         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1561         if( pTarget==pTab ){
1562           if( pStep->pUpsert ){
1563             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1564             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1565           }
1566           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1567           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1568         }
1569       }
1570     }
1571 
1572 
1573     /* Find tokens to edit in UPDATE OF clause */
1574     if( sParse.pTriggerTab==pTab ){
1575       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1576     }
1577 
1578     /* Find tokens to edit in various expressions and selects */
1579     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1580   }
1581 
1582   assert( rc==SQLITE_OK );
1583   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1584 
1585 renameColumnFunc_done:
1586   if( rc!=SQLITE_OK ){
1587     if( sParse.zErrMsg ){
1588       renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1589     }else{
1590       sqlite3_result_error_code(context, rc);
1591     }
1592   }
1593 
1594   renameParseCleanup(&sParse);
1595   renameTokenFree(db, sCtx.pList);
1596 #ifndef SQLITE_OMIT_AUTHORIZATION
1597   db->xAuth = xAuth;
1598 #endif
1599   sqlite3BtreeLeaveAll(db);
1600 }
1601 
1602 /*
1603 ** Walker expression callback used by "RENAME TABLE".
1604 */
1605 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1606   RenameCtx *p = pWalker->u.pRename;
1607   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1608     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1609   }
1610   return WRC_Continue;
1611 }
1612 
1613 /*
1614 ** Walker select callback used by "RENAME TABLE".
1615 */
1616 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1617   int i;
1618   RenameCtx *p = pWalker->u.pRename;
1619   SrcList *pSrc = pSelect->pSrc;
1620   if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1621     testcase( pSelect->selFlags & SF_View );
1622     testcase( pSelect->selFlags & SF_CopyCte );
1623     return WRC_Prune;
1624   }
1625   if( NEVER(pSrc==0) ){
1626     assert( pWalker->pParse->db->mallocFailed );
1627     return WRC_Abort;
1628   }
1629   for(i=0; i<pSrc->nSrc; i++){
1630     SrcItem *pItem = &pSrc->a[i];
1631     if( pItem->pTab==p->pTab ){
1632       renameTokenFind(pWalker->pParse, p, pItem->zName);
1633     }
1634   }
1635   renameWalkWith(pWalker, pSelect);
1636 
1637   return WRC_Continue;
1638 }
1639 
1640 
1641 /*
1642 ** This C function implements an SQL user function that is used by SQL code
1643 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1644 ** of any foreign key constraints that use the table being renamed as the
1645 ** parent table. It is passed three arguments:
1646 **
1647 **   0: The database containing the table being renamed.
1648 **   1. type:     Type of object ("table", "view" etc.)
1649 **   2. object:   Name of object
1650 **   3: The complete text of the schema statement being modified,
1651 **   4: The old name of the table being renamed, and
1652 **   5: The new name of the table being renamed.
1653 **   6: True if the schema statement comes from the temp db.
1654 **
1655 ** It returns the new schema statement. For example:
1656 **
1657 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1658 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1659 */
1660 static void renameTableFunc(
1661   sqlite3_context *context,
1662   int NotUsed,
1663   sqlite3_value **argv
1664 ){
1665   sqlite3 *db = sqlite3_context_db_handle(context);
1666   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1667   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1668   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1669   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1670   int bTemp = sqlite3_value_int(argv[6]);
1671   UNUSED_PARAMETER(NotUsed);
1672 
1673   if( zInput && zOld && zNew ){
1674     Parse sParse;
1675     int rc;
1676     int bQuote = 1;
1677     RenameCtx sCtx;
1678     Walker sWalker;
1679 
1680 #ifndef SQLITE_OMIT_AUTHORIZATION
1681     sqlite3_xauth xAuth = db->xAuth;
1682     db->xAuth = 0;
1683 #endif
1684 
1685     sqlite3BtreeEnterAll(db);
1686 
1687     memset(&sCtx, 0, sizeof(RenameCtx));
1688     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1689     memset(&sWalker, 0, sizeof(Walker));
1690     sWalker.pParse = &sParse;
1691     sWalker.xExprCallback = renameTableExprCb;
1692     sWalker.xSelectCallback = renameTableSelectCb;
1693     sWalker.u.pRename = &sCtx;
1694 
1695     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1696 
1697     if( rc==SQLITE_OK ){
1698       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1699       if( sParse.pNewTable ){
1700         Table *pTab = sParse.pNewTable;
1701 
1702         if( pTab->pSelect ){
1703           if( isLegacy==0 ){
1704             Select *pSelect = pTab->pSelect;
1705             NameContext sNC;
1706             memset(&sNC, 0, sizeof(sNC));
1707             sNC.pParse = &sParse;
1708 
1709             assert( pSelect->selFlags & SF_View );
1710             pSelect->selFlags &= ~SF_View;
1711             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1712             if( sParse.nErr ){
1713               rc = sParse.rc;
1714             }else{
1715               sqlite3WalkSelect(&sWalker, pTab->pSelect);
1716             }
1717           }
1718         }else{
1719           /* Modify any FK definitions to point to the new table. */
1720 #ifndef SQLITE_OMIT_FOREIGN_KEY
1721           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1722             FKey *pFKey;
1723             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1724               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1725                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1726               }
1727             }
1728           }
1729 #endif
1730 
1731           /* If this is the table being altered, fix any table refs in CHECK
1732           ** expressions. Also update the name that appears right after the
1733           ** "CREATE [VIRTUAL] TABLE" bit. */
1734           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1735             sCtx.pTab = pTab;
1736             if( isLegacy==0 ){
1737               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1738             }
1739             renameTokenFind(&sParse, &sCtx, pTab->zName);
1740           }
1741         }
1742       }
1743 
1744       else if( sParse.pNewIndex ){
1745         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1746         if( isLegacy==0 ){
1747           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1748         }
1749       }
1750 
1751 #ifndef SQLITE_OMIT_TRIGGER
1752       else{
1753         Trigger *pTrigger = sParse.pNewTrigger;
1754         TriggerStep *pStep;
1755         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1756             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1757           ){
1758           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1759         }
1760 
1761         if( isLegacy==0 ){
1762           rc = renameResolveTrigger(&sParse);
1763           if( rc==SQLITE_OK ){
1764             renameWalkTrigger(&sWalker, pTrigger);
1765             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1766               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1767                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1768               }
1769             }
1770           }
1771         }
1772       }
1773 #endif
1774     }
1775 
1776     if( rc==SQLITE_OK ){
1777       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1778     }
1779     if( rc!=SQLITE_OK ){
1780       if( sParse.zErrMsg ){
1781         renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1782       }else{
1783         sqlite3_result_error_code(context, rc);
1784       }
1785     }
1786 
1787     renameParseCleanup(&sParse);
1788     renameTokenFree(db, sCtx.pList);
1789     sqlite3BtreeLeaveAll(db);
1790 #ifndef SQLITE_OMIT_AUTHORIZATION
1791     db->xAuth = xAuth;
1792 #endif
1793   }
1794 
1795   return;
1796 }
1797 
1798 static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1799   if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1800     renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1801   }
1802   return WRC_Continue;
1803 }
1804 
1805 /*
1806 ** The implementation of an SQL scalar function that rewrites DDL statements
1807 ** so that any string literals that use double-quotes are modified so that
1808 ** they use single quotes.
1809 **
1810 ** Two arguments must be passed:
1811 **
1812 **   0: Database name ("main", "temp" etc.).
1813 **   1: SQL statement to edit.
1814 **
1815 ** The returned value is the modified SQL statement. For example, given
1816 ** the database schema:
1817 **
1818 **   CREATE TABLE t1(a, b, c);
1819 **
1820 **   SELECT sqlite_rename_quotefix('main',
1821 **       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1822 **   );
1823 **
1824 ** returns the string:
1825 **
1826 **   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1827 */
1828 static void renameQuotefixFunc(
1829   sqlite3_context *context,
1830   int NotUsed,
1831   sqlite3_value **argv
1832 ){
1833   sqlite3 *db = sqlite3_context_db_handle(context);
1834   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1835   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1836 
1837 #ifndef SQLITE_OMIT_AUTHORIZATION
1838   sqlite3_xauth xAuth = db->xAuth;
1839   db->xAuth = 0;
1840 #endif
1841 
1842   sqlite3BtreeEnterAll(db);
1843 
1844   UNUSED_PARAMETER(NotUsed);
1845   if( zDb && zInput ){
1846     int rc;
1847     Parse sParse;
1848     rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1849 
1850     if( rc==SQLITE_OK ){
1851       RenameCtx sCtx;
1852       Walker sWalker;
1853 
1854       /* Walker to find tokens that need to be replaced. */
1855       memset(&sCtx, 0, sizeof(RenameCtx));
1856       memset(&sWalker, 0, sizeof(Walker));
1857       sWalker.pParse = &sParse;
1858       sWalker.xExprCallback = renameQuotefixExprCb;
1859       sWalker.xSelectCallback = renameColumnSelectCb;
1860       sWalker.u.pRename = &sCtx;
1861 
1862       if( sParse.pNewTable ){
1863         Select *pSelect = sParse.pNewTable->pSelect;
1864         if( pSelect ){
1865           pSelect->selFlags &= ~SF_View;
1866           sParse.rc = SQLITE_OK;
1867           sqlite3SelectPrep(&sParse, pSelect, 0);
1868           rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1869           if( rc==SQLITE_OK ){
1870             sqlite3WalkSelect(&sWalker, pSelect);
1871           }
1872         }else{
1873           int i;
1874           sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1875 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1876           for(i=0; i<sParse.pNewTable->nCol; i++){
1877             sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1878           }
1879 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1880         }
1881       }else if( sParse.pNewIndex ){
1882         sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1883         sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1884       }else{
1885 #ifndef SQLITE_OMIT_TRIGGER
1886         rc = renameResolveTrigger(&sParse);
1887         if( rc==SQLITE_OK ){
1888           renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1889         }
1890 #endif /* SQLITE_OMIT_TRIGGER */
1891       }
1892 
1893       if( rc==SQLITE_OK ){
1894         rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1895       }
1896       renameTokenFree(db, sCtx.pList);
1897     }
1898     if( rc!=SQLITE_OK ){
1899       sqlite3_result_error_code(context, rc);
1900     }
1901     renameParseCleanup(&sParse);
1902   }
1903 
1904 #ifndef SQLITE_OMIT_AUTHORIZATION
1905   db->xAuth = xAuth;
1906 #endif
1907 
1908   sqlite3BtreeLeaveAll(db);
1909 }
1910 
1911 /*
1912 ** An SQL user function that checks that there are no parse or symbol
1913 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1914 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1915 ** reloaded, this function is called on each SQL statement in the schema
1916 ** to ensure that it is still usable.
1917 **
1918 **   0: Database name ("main", "temp" etc.).
1919 **   1: SQL statement.
1920 **   2: Object type ("view", "table", "trigger" or "index").
1921 **   3: Object name.
1922 **   4: True if object is from temp schema.
1923 **   5: "when" part of error message.
1924 **   6: True to disable the DQS quirk when parsing SQL.
1925 **
1926 ** Unless it finds an error, this function normally returns NULL. However, it
1927 ** returns integer value 1 if:
1928 **
1929 **   * the SQL argument creates a trigger, and
1930 **   * the table that the trigger is attached to is in database zDb.
1931 */
1932 static void renameTableTest(
1933   sqlite3_context *context,
1934   int NotUsed,
1935   sqlite3_value **argv
1936 ){
1937   sqlite3 *db = sqlite3_context_db_handle(context);
1938   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1939   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1940   int bTemp = sqlite3_value_int(argv[4]);
1941   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1942   char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
1943   int bNoDQS = sqlite3_value_int(argv[6]);
1944 
1945 #ifndef SQLITE_OMIT_AUTHORIZATION
1946   sqlite3_xauth xAuth = db->xAuth;
1947   db->xAuth = 0;
1948 #endif
1949 
1950   UNUSED_PARAMETER(NotUsed);
1951 
1952   if( zDb && zInput ){
1953     int rc;
1954     Parse sParse;
1955     int flags = db->flags;
1956     if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
1957     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1958     db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
1959     if( rc==SQLITE_OK ){
1960       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1961         NameContext sNC;
1962         memset(&sNC, 0, sizeof(sNC));
1963         sNC.pParse = &sParse;
1964         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1965         if( sParse.nErr ) rc = sParse.rc;
1966       }
1967 
1968       else if( sParse.pNewTrigger ){
1969         if( isLegacy==0 ){
1970           rc = renameResolveTrigger(&sParse);
1971         }
1972         if( rc==SQLITE_OK ){
1973           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1974           int i2 = sqlite3FindDbName(db, zDb);
1975           if( i1==i2 ) sqlite3_result_int(context, 1);
1976         }
1977       }
1978     }
1979 
1980     if( rc!=SQLITE_OK && zWhen ){
1981       renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
1982     }
1983     renameParseCleanup(&sParse);
1984   }
1985 
1986 #ifndef SQLITE_OMIT_AUTHORIZATION
1987   db->xAuth = xAuth;
1988 #endif
1989 }
1990 
1991 /*
1992 ** The implementation of internal UDF sqlite_drop_column().
1993 **
1994 ** Arguments:
1995 **
1996 **  argv[0]: An integer - the index of the schema containing the table
1997 **  argv[1]: CREATE TABLE statement to modify.
1998 **  argv[2]: An integer - the index of the column to remove.
1999 **
2000 ** The value returned is a string containing the CREATE TABLE statement
2001 ** with column argv[2] removed.
2002 */
2003 static void dropColumnFunc(
2004   sqlite3_context *context,
2005   int NotUsed,
2006   sqlite3_value **argv
2007 ){
2008   sqlite3 *db = sqlite3_context_db_handle(context);
2009   int iSchema = sqlite3_value_int(argv[0]);
2010   const char *zSql = (const char*)sqlite3_value_text(argv[1]);
2011   int iCol = sqlite3_value_int(argv[2]);
2012   const char *zDb = db->aDb[iSchema].zDbSName;
2013   int rc;
2014   Parse sParse;
2015   RenameToken *pCol;
2016   Table *pTab;
2017   const char *zEnd;
2018   char *zNew = 0;
2019 
2020 #ifndef SQLITE_OMIT_AUTHORIZATION
2021   sqlite3_xauth xAuth = db->xAuth;
2022   db->xAuth = 0;
2023 #endif
2024 
2025   UNUSED_PARAMETER(NotUsed);
2026   rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2027   if( rc!=SQLITE_OK ) goto drop_column_done;
2028   pTab = sParse.pNewTable;
2029   if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
2030     /* This can happen if the sqlite_schema table is corrupt */
2031     rc = SQLITE_CORRUPT_BKPT;
2032     goto drop_column_done;
2033   }
2034 
2035   pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
2036   if( iCol<pTab->nCol-1 ){
2037     RenameToken *pEnd;
2038     pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
2039     zEnd = (const char*)pEnd->t.z;
2040   }else{
2041     zEnd = (const char*)&zSql[pTab->addColOffset];
2042     while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
2043   }
2044 
2045   zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
2046   sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2047   sqlite3_free(zNew);
2048 
2049 drop_column_done:
2050   renameParseCleanup(&sParse);
2051 #ifndef SQLITE_OMIT_AUTHORIZATION
2052   db->xAuth = xAuth;
2053 #endif
2054   if( rc!=SQLITE_OK ){
2055     sqlite3_result_error_code(context, rc);
2056   }
2057 }
2058 
2059 /*
2060 ** This function is called by the parser upon parsing an
2061 **
2062 **     ALTER TABLE pSrc DROP COLUMN pName
2063 **
2064 ** statement. Argument pSrc contains the possibly qualified name of the
2065 ** table being edited, and token pName the name of the column to drop.
2066 */
2067 void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
2068   sqlite3 *db = pParse->db;       /* Database handle */
2069   Table *pTab;                    /* Table to modify */
2070   int iDb;                        /* Index of db containing pTab in aDb[] */
2071   const char *zDb;                /* Database containing pTab ("main" etc.) */
2072   char *zCol = 0;                 /* Name of column to drop */
2073   int iCol;                       /* Index of column zCol in pTab->aCol[] */
2074 
2075   /* Look up the table being altered. */
2076   assert( pParse->pNewTable==0 );
2077   assert( sqlite3BtreeHoldsAllMutexes(db) );
2078   if( NEVER(db->mallocFailed) ) goto exit_drop_column;
2079   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2080   if( !pTab ) goto exit_drop_column;
2081 
2082   /* Make sure this is not an attempt to ALTER a view, virtual table or
2083   ** system table. */
2084   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2085   if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
2086 
2087   /* Find the index of the column being dropped. */
2088   zCol = sqlite3NameFromToken(db, pName);
2089   if( zCol==0 ){
2090     assert( db->mallocFailed );
2091     goto exit_drop_column;
2092   }
2093   iCol = sqlite3ColumnIndex(pTab, zCol);
2094   if( iCol<0 ){
2095     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2096     goto exit_drop_column;
2097   }
2098 
2099   /* Do not allow the user to drop a PRIMARY KEY column or a column
2100   ** constrained by a UNIQUE constraint.  */
2101   if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2102     sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2103         (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2104         zCol
2105     );
2106     goto exit_drop_column;
2107   }
2108 
2109   /* Do not allow the number of columns to go to zero */
2110   if( pTab->nCol<=1 ){
2111     sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2112     goto exit_drop_column;
2113   }
2114 
2115   /* Edit the sqlite_schema table */
2116   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2117   assert( iDb>=0 );
2118   zDb = db->aDb[iDb].zDbSName;
2119   renameTestSchema(pParse, zDb, iDb==1, "", 0);
2120   renameFixQuotes(pParse, zDb, iDb==1);
2121   sqlite3NestedParse(pParse,
2122       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
2123       "sql = sqlite_drop_column(%d, sql, %d) "
2124       "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
2125       , zDb, iDb, iCol, pTab->zName
2126   );
2127 
2128   /* Drop and reload the database schema. */
2129   renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
2130   renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
2131 
2132   /* Edit rows of table on disk */
2133   if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
2134     int i;
2135     int addr;
2136     int reg;
2137     int regRec;
2138     Index *pPk = 0;
2139     int nField = 0;               /* Number of non-virtual columns after drop */
2140     int iCur;
2141     Vdbe *v = sqlite3GetVdbe(pParse);
2142     iCur = pParse->nTab++;
2143     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
2144     addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2145     reg = ++pParse->nMem;
2146     if( HasRowid(pTab) ){
2147       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
2148       pParse->nMem += pTab->nCol;
2149     }else{
2150       pPk = sqlite3PrimaryKeyIndex(pTab);
2151       pParse->nMem += pPk->nColumn;
2152       for(i=0; i<pPk->nKeyCol; i++){
2153         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2154       }
2155       nField = pPk->nKeyCol;
2156     }
2157     regRec = ++pParse->nMem;
2158     for(i=0; i<pTab->nCol; i++){
2159       if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2160         int regOut;
2161         if( pPk ){
2162           int iPos = sqlite3TableColumnToIndex(pPk, i);
2163           int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
2164           if( iPos<pPk->nKeyCol ) continue;
2165           regOut = reg+1+iPos-(iPos>iColPos);
2166         }else{
2167           regOut = reg+1+nField;
2168         }
2169         if( i==pTab->iPKey ){
2170           sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2171         }else{
2172           sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2173         }
2174         nField++;
2175       }
2176     }
2177     if( nField==0 ){
2178       /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
2179       pParse->nMem++;
2180       sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
2181       nField = 1;
2182     }
2183     sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2184     if( pPk ){
2185       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2186     }else{
2187       sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2188     }
2189     sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2190 
2191     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
2192     sqlite3VdbeJumpHere(v, addr);
2193   }
2194 
2195 exit_drop_column:
2196   sqlite3DbFree(db, zCol);
2197   sqlite3SrcListDelete(db, pSrc);
2198 }
2199 
2200 /*
2201 ** Register built-in functions used to help implement ALTER TABLE
2202 */
2203 void sqlite3AlterFunctions(void){
2204   static FuncDef aAlterTableFuncs[] = {
2205     INTERNAL_FUNCTION(sqlite_rename_column,  9, renameColumnFunc),
2206     INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
2207     INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
2208     INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
2209     INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
2210   };
2211   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2212 }
2213 #endif  /* SQLITE_ALTER_TABLE */
2214