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