xref: /sqlite-3.40.0/src/alter.c (revision f71a243a)
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_Shadow)
35      && (pParse->db->flags & SQLITE_Defensive)
36      && pParse->db->nVdbeExec==0
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(Parse *pParse, const char *zDb, int bTemp){
54   sqlite3NestedParse(pParse,
55       "SELECT 1 "
56       "FROM \"%w\".%s "
57       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
58       " AND sql NOT LIKE 'create virtual%%'"
59       " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
60       zDb, MASTER_NAME,
61       zDb, bTemp
62   );
63 
64   if( bTemp==0 ){
65     sqlite3NestedParse(pParse,
66         "SELECT 1 "
67         "FROM temp.%s "
68         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
69         " AND sql NOT LIKE 'create virtual%%'"
70         " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
71         MASTER_NAME, zDb
72     );
73   }
74 }
75 
76 /*
77 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
78 ** the temp database as well.
79 */
80 static void renameReloadSchema(Parse *pParse, int iDb){
81   Vdbe *v = pParse->pVdbe;
82   if( v ){
83     sqlite3ChangeCookie(pParse, iDb);
84     sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
85     if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
86   }
87 }
88 
89 /*
90 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
91 ** command.
92 */
93 void sqlite3AlterRenameTable(
94   Parse *pParse,            /* Parser context. */
95   SrcList *pSrc,            /* The table to rename. */
96   Token *pName              /* The new table name. */
97 ){
98   int iDb;                  /* Database that contains the table */
99   char *zDb;                /* Name of database iDb */
100   Table *pTab;              /* Table being renamed */
101   char *zName = 0;          /* NULL-terminated version of pName */
102   sqlite3 *db = pParse->db; /* Database connection */
103   int nTabName;             /* Number of UTF-8 characters in zTabName */
104   const char *zTabName;     /* Original name of the table */
105   Vdbe *v;
106   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
107   u32 savedDbFlags;         /* Saved value of db->mDbFlags */
108 
109   savedDbFlags = db->mDbFlags;
110   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
111   assert( pSrc->nSrc==1 );
112   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
113 
114   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
115   if( !pTab ) goto exit_rename_table;
116   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
117   zDb = db->aDb[iDb].zDbSName;
118   db->mDbFlags |= DBFLAG_PreferBuiltin;
119 
120   /* Get a NULL terminated version of the new table name. */
121   zName = sqlite3NameFromToken(db, pName);
122   if( !zName ) goto exit_rename_table;
123 
124   /* Check that a table or index named 'zName' does not already exist
125   ** in database iDb. If so, this is an error.
126   */
127   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
128     sqlite3ErrorMsg(pParse,
129         "there is already another table or index with this name: %s", zName);
130     goto exit_rename_table;
131   }
132 
133   /* Make sure it is not a system table being altered, or a reserved name
134   ** that the table is being renamed to.
135   */
136   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
137     goto exit_rename_table;
138   }
139   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
140     exit_rename_table;
141   }
142 
143 #ifndef SQLITE_OMIT_VIEW
144   if( pTab->pSelect ){
145     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
146     goto exit_rename_table;
147   }
148 #endif
149 
150 #ifndef SQLITE_OMIT_AUTHORIZATION
151   /* Invoke the authorization callback. */
152   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
153     goto exit_rename_table;
154   }
155 #endif
156 
157 #ifndef SQLITE_OMIT_VIRTUALTABLE
158   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
159     goto exit_rename_table;
160   }
161   if( IsVirtual(pTab) ){
162     pVTab = sqlite3GetVTable(db, pTab);
163     if( pVTab->pVtab->pModule->xRename==0 ){
164       pVTab = 0;
165     }
166   }
167 #endif
168 
169   /* Begin a transaction for database iDb. Then modify the schema cookie
170   ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
171   ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
172   ** nested SQL may raise an exception.  */
173   v = sqlite3GetVdbe(pParse);
174   if( v==0 ){
175     goto exit_rename_table;
176   }
177   sqlite3MayAbort(pParse);
178 
179   /* figure out how many UTF-8 characters are in zName */
180   zTabName = pTab->zName;
181   nTabName = sqlite3Utf8CharLen(zTabName, -1);
182 
183   /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
184   ** the schema to use the new table name.  */
185   sqlite3NestedParse(pParse,
186       "UPDATE \"%w\".%s SET "
187       "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
188       "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
189       "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
190       , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
191   );
192 
193   /* Update the tbl_name and name columns of the sqlite_master table
194   ** as required.  */
195   sqlite3NestedParse(pParse,
196       "UPDATE %Q.%s SET "
197           "tbl_name = %Q, "
198           "name = CASE "
199             "WHEN type='table' THEN %Q "
200             "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
201             "     AND type='index' THEN "
202              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
203             "ELSE name END "
204       "WHERE tbl_name=%Q COLLATE nocase AND "
205           "(type='table' OR type='index' OR type='trigger');",
206       zDb, MASTER_NAME,
207       zName, zName, zName,
208       nTabName, zTabName
209   );
210 
211 #ifndef SQLITE_OMIT_AUTOINCREMENT
212   /* If the sqlite_sequence table exists in this database, then update
213   ** it with the new table name.
214   */
215   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
216     sqlite3NestedParse(pParse,
217         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
218         zDb, zName, pTab->zName);
219   }
220 #endif
221 
222   /* If the table being renamed is not itself part of the temp database,
223   ** edit view and trigger definitions within the temp database
224   ** as required.  */
225   if( iDb!=1 ){
226     sqlite3NestedParse(pParse,
227         "UPDATE sqlite_temp_master SET "
228             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
229             "tbl_name = "
230               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
231               "          sqlite_rename_test(%Q, sql, type, name, 1) "
232               "THEN %Q ELSE tbl_name END "
233             "WHERE type IN ('view', 'trigger')"
234         , zDb, zTabName, zName, zTabName, zDb, zName);
235   }
236 
237   /* If this is a virtual table, invoke the xRename() function if
238   ** one is defined. The xRename() callback will modify the names
239   ** of any resources used by the v-table implementation (including other
240   ** SQLite tables) that are identified by the name of the virtual table.
241   */
242 #ifndef SQLITE_OMIT_VIRTUALTABLE
243   if( pVTab ){
244     int i = ++pParse->nMem;
245     sqlite3VdbeLoadString(v, i, zName);
246     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
247   }
248 #endif
249 
250   renameReloadSchema(pParse, iDb);
251   renameTestSchema(pParse, zDb, iDb==1);
252 
253 exit_rename_table:
254   sqlite3SrcListDelete(db, pSrc);
255   sqlite3DbFree(db, zName);
256   db->mDbFlags = savedDbFlags;
257 }
258 
259 /*
260 ** This function is called after an "ALTER TABLE ... ADD" statement
261 ** has been parsed. Argument pColDef contains the text of the new
262 ** column definition.
263 **
264 ** The Table structure pParse->pNewTable was extended to include
265 ** the new column during parsing.
266 */
267 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
268   Table *pNew;              /* Copy of pParse->pNewTable */
269   Table *pTab;              /* Table being altered */
270   int iDb;                  /* Database number */
271   const char *zDb;          /* Database name */
272   const char *zTab;         /* Table name */
273   char *zCol;               /* Null-terminated column definition */
274   Column *pCol;             /* The new column */
275   Expr *pDflt;              /* Default value for the new column */
276   sqlite3 *db;              /* The database connection; */
277   Vdbe *v;                  /* The prepared statement under construction */
278   int r1;                   /* Temporary registers */
279 
280   db = pParse->db;
281   if( pParse->nErr || db->mallocFailed ) return;
282   pNew = pParse->pNewTable;
283   assert( pNew );
284 
285   assert( sqlite3BtreeHoldsAllMutexes(db) );
286   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
287   zDb = db->aDb[iDb].zDbSName;
288   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
289   pCol = &pNew->aCol[pNew->nCol-1];
290   pDflt = pCol->pDflt;
291   pTab = sqlite3FindTable(db, zTab, zDb);
292   assert( pTab );
293 
294 #ifndef SQLITE_OMIT_AUTHORIZATION
295   /* Invoke the authorization callback. */
296   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
297     return;
298   }
299 #endif
300 
301   /* If the default value for the new column was specified with a
302   ** literal NULL, then set pDflt to 0. This simplifies checking
303   ** for an SQL NULL default below.
304   */
305   assert( pDflt==0 || pDflt->op==TK_SPAN );
306   if( pDflt && pDflt->pLeft->op==TK_NULL ){
307     pDflt = 0;
308   }
309 
310   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
311   ** If there is a NOT NULL constraint, then the default value for the
312   ** column must not be NULL.
313   */
314   if( pCol->colFlags & COLFLAG_PRIMKEY ){
315     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
316     return;
317   }
318   if( pNew->pIndex ){
319     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
320     return;
321   }
322   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
323     sqlite3ErrorMsg(pParse,
324         "Cannot add a REFERENCES column with non-NULL default value");
325     return;
326   }
327   if( pCol->notNull && !pDflt ){
328     sqlite3ErrorMsg(pParse,
329         "Cannot add a NOT NULL column with default value NULL");
330     return;
331   }
332 
333   /* Ensure the default expression is something that sqlite3ValueFromExpr()
334   ** can handle (i.e. not CURRENT_TIME etc.)
335   */
336   if( pDflt ){
337     sqlite3_value *pVal = 0;
338     int rc;
339     rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
340     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
341     if( rc!=SQLITE_OK ){
342       assert( db->mallocFailed == 1 );
343       return;
344     }
345     if( !pVal ){
346       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
347       return;
348     }
349     sqlite3ValueFree(pVal);
350   }
351 
352   /* Modify the CREATE TABLE statement. */
353   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
354   if( zCol ){
355     char *zEnd = &zCol[pColDef->n-1];
356     u32 savedDbFlags = db->mDbFlags;
357     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
358       *zEnd-- = '\0';
359     }
360     db->mDbFlags |= DBFLAG_PreferBuiltin;
361     sqlite3NestedParse(pParse,
362         "UPDATE \"%w\".%s SET "
363           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
364         "WHERE type = 'table' AND name = %Q",
365       zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
366       zTab
367     );
368     sqlite3DbFree(db, zCol);
369     db->mDbFlags = savedDbFlags;
370   }
371 
372   /* Make sure the schema version is at least 3.  But do not upgrade
373   ** from less than 3 to 4, as that will corrupt any preexisting DESC
374   ** index.
375   */
376   v = sqlite3GetVdbe(pParse);
377   if( v ){
378     r1 = sqlite3GetTempReg(pParse);
379     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
380     sqlite3VdbeUsesBtree(v, iDb);
381     sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
382     sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
383     VdbeCoverage(v);
384     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
385     sqlite3ReleaseTempReg(pParse, r1);
386   }
387 
388   /* Reload the table definition */
389   renameReloadSchema(pParse, iDb);
390 }
391 
392 /*
393 ** This function is called by the parser after the table-name in
394 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
395 ** pSrc is the full-name of the table being altered.
396 **
397 ** This routine makes a (partial) copy of the Table structure
398 ** for the table being altered and sets Parse.pNewTable to point
399 ** to it. Routines called by the parser as the column definition
400 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
401 ** the copy. The copy of the Table structure is deleted by tokenize.c
402 ** after parsing is finished.
403 **
404 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
405 ** coding the "ALTER TABLE ... ADD" statement.
406 */
407 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
408   Table *pNew;
409   Table *pTab;
410   int iDb;
411   int i;
412   int nAlloc;
413   sqlite3 *db = pParse->db;
414 
415   /* Look up the table being altered. */
416   assert( pParse->pNewTable==0 );
417   assert( sqlite3BtreeHoldsAllMutexes(db) );
418   if( db->mallocFailed ) goto exit_begin_add_column;
419   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
420   if( !pTab ) goto exit_begin_add_column;
421 
422 #ifndef SQLITE_OMIT_VIRTUALTABLE
423   if( IsVirtual(pTab) ){
424     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
425     goto exit_begin_add_column;
426   }
427 #endif
428 
429   /* Make sure this is not an attempt to ALTER a view. */
430   if( pTab->pSelect ){
431     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
432     goto exit_begin_add_column;
433   }
434   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
435     goto exit_begin_add_column;
436   }
437 
438   assert( pTab->addColOffset>0 );
439   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
440 
441   /* Put a copy of the Table struct in Parse.pNewTable for the
442   ** sqlite3AddColumn() function and friends to modify.  But modify
443   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
444   ** prefix, we insure that the name will not collide with an existing
445   ** table because user table are not allowed to have the "sqlite_"
446   ** prefix on their name.
447   */
448   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
449   if( !pNew ) goto exit_begin_add_column;
450   pParse->pNewTable = pNew;
451   pNew->nTabRef = 1;
452   pNew->nCol = pTab->nCol;
453   assert( pNew->nCol>0 );
454   nAlloc = (((pNew->nCol-1)/8)*8)+8;
455   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
456   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
457   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
458   if( !pNew->aCol || !pNew->zName ){
459     assert( db->mallocFailed );
460     goto exit_begin_add_column;
461   }
462   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
463   for(i=0; i<pNew->nCol; i++){
464     Column *pCol = &pNew->aCol[i];
465     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
466     pCol->zColl = 0;
467     pCol->pDflt = 0;
468   }
469   pNew->pSchema = db->aDb[iDb].pSchema;
470   pNew->addColOffset = pTab->addColOffset;
471   pNew->nTabRef = 1;
472 
473 exit_begin_add_column:
474   sqlite3SrcListDelete(db, pSrc);
475   return;
476 }
477 
478 /*
479 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
480 ** command. This function checks if the table is a view or virtual
481 ** table (columns of views or virtual tables may not be renamed). If so,
482 ** it loads an error message into pParse and returns non-zero.
483 **
484 ** Or, if pTab is not a view or virtual table, zero is returned.
485 */
486 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
487 static int isRealTable(Parse *pParse, Table *pTab){
488   const char *zType = 0;
489 #ifndef SQLITE_OMIT_VIEW
490   if( pTab->pSelect ){
491     zType = "view";
492   }
493 #endif
494 #ifndef SQLITE_OMIT_VIRTUALTABLE
495   if( IsVirtual(pTab) ){
496     zType = "virtual table";
497   }
498 #endif
499   if( zType ){
500     sqlite3ErrorMsg(
501         pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
502     );
503     return 1;
504   }
505   return 0;
506 }
507 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
508 # define isRealTable(x,y) (0)
509 #endif
510 
511 /*
512 ** Handles the following parser reduction:
513 **
514 **  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
515 */
516 void sqlite3AlterRenameColumn(
517   Parse *pParse,                  /* Parsing context */
518   SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */
519   Token *pOld,                    /* Name of column being changed */
520   Token *pNew                     /* New column name */
521 ){
522   sqlite3 *db = pParse->db;       /* Database connection */
523   Table *pTab;                    /* Table being updated */
524   int iCol;                       /* Index of column being renamed */
525   char *zOld = 0;                 /* Old column name */
526   char *zNew = 0;                 /* New column name */
527   const char *zDb;                /* Name of schema containing the table */
528   int iSchema;                    /* Index of the schema */
529   int bQuote;                     /* True to quote the new name */
530 
531   /* Locate the table to be altered */
532   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
533   if( !pTab ) goto exit_rename_column;
534 
535   /* Cannot alter a system table */
536   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
537   if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
538 
539   /* Which schema holds the table to be altered */
540   iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
541   assert( iSchema>=0 );
542   zDb = db->aDb[iSchema].zDbSName;
543 
544 #ifndef SQLITE_OMIT_AUTHORIZATION
545   /* Invoke the authorization callback. */
546   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
547     goto exit_rename_column;
548   }
549 #endif
550 
551   /* Make sure the old name really is a column name in the table to be
552   ** altered.  Set iCol to be the index of the column being renamed */
553   zOld = sqlite3NameFromToken(db, pOld);
554   if( !zOld ) goto exit_rename_column;
555   for(iCol=0; iCol<pTab->nCol; iCol++){
556     if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
557   }
558   if( iCol==pTab->nCol ){
559     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
560     goto exit_rename_column;
561   }
562 
563   /* Do the rename operation using a recursive UPDATE statement that
564   ** uses the sqlite_rename_column() SQL function to compute the new
565   ** CREATE statement text for the sqlite_master table.
566   */
567   sqlite3MayAbort(pParse);
568   zNew = sqlite3NameFromToken(db, pNew);
569   if( !zNew ) goto exit_rename_column;
570   assert( pNew->n>0 );
571   bQuote = sqlite3Isquote(pNew->z[0]);
572   sqlite3NestedParse(pParse,
573       "UPDATE \"%w\".%s SET "
574       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
575       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
576       " AND (type != 'index' OR tbl_name = %Q)"
577       " AND sql NOT LIKE 'create virtual%%'",
578       zDb, MASTER_NAME,
579       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
580       pTab->zName
581   );
582 
583   sqlite3NestedParse(pParse,
584       "UPDATE temp.%s SET "
585       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
586       "WHERE type IN ('trigger', 'view')",
587       MASTER_NAME,
588       zDb, pTab->zName, iCol, zNew, bQuote
589   );
590 
591   /* Drop and reload the database schema. */
592   renameReloadSchema(pParse, iSchema);
593   renameTestSchema(pParse, zDb, iSchema==1);
594 
595  exit_rename_column:
596   sqlite3SrcListDelete(db, pSrc);
597   sqlite3DbFree(db, zOld);
598   sqlite3DbFree(db, zNew);
599   return;
600 }
601 
602 /*
603 ** Each RenameToken object maps an element of the parse tree into
604 ** the token that generated that element.  The parse tree element
605 ** might be one of:
606 **
607 **     *  A pointer to an Expr that represents an ID
608 **     *  The name of a table column in Column.zName
609 **
610 ** A list of RenameToken objects can be constructed during parsing.
611 ** Each new object is created by sqlite3RenameTokenMap().
612 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
613 ** routine is used to keep the mapping current.
614 **
615 ** After the parse finishes, renameTokenFind() routine can be used
616 ** to look up the actual token value that created some element in
617 ** the parse tree.
618 */
619 struct RenameToken {
620   void *p;               /* Parse tree element created by token t */
621   Token t;               /* The token that created parse tree element p */
622   RenameToken *pNext;    /* Next is a list of all RenameToken objects */
623 };
624 
625 /*
626 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
627 ** down into the Walker.
628 */
629 typedef struct RenameCtx RenameCtx;
630 struct RenameCtx {
631   RenameToken *pList;             /* List of tokens to overwrite */
632   int nList;                      /* Number of tokens in pList */
633   int iCol;                       /* Index of column being renamed */
634   Table *pTab;                    /* Table being ALTERed */
635   const char *zOld;               /* Old column name */
636 };
637 
638 #ifdef SQLITE_DEBUG
639 /*
640 ** This function is only for debugging. It performs two tasks:
641 **
642 **   1. Checks that pointer pPtr does not already appear in the
643 **      rename-token list.
644 **
645 **   2. Dereferences each pointer in the rename-token list.
646 **
647 ** The second is most effective when debugging under valgrind or
648 ** address-sanitizer or similar. If any of these pointers no longer
649 ** point to valid objects, an exception is raised by the memory-checking
650 ** tool.
651 **
652 ** The point of this is to prevent comparisons of invalid pointer values.
653 ** Even though this always seems to work, it is undefined according to the
654 ** C standard. Example of undefined comparison:
655 **
656 **     sqlite3_free(x);
657 **     if( x==y ) ...
658 **
659 ** Technically, as x no longer points into a valid object or to the byte
660 ** following a valid object, it may not be used in comparison operations.
661 */
662 static void renameTokenCheckAll(Parse *pParse, void *pPtr){
663   if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
664     RenameToken *p;
665     u8 i = 0;
666     for(p=pParse->pRename; p; p=p->pNext){
667       if( p->p ){
668         assert( p->p!=pPtr );
669         i += *(u8*)(p->p);
670       }
671     }
672   }
673 }
674 #else
675 # define renameTokenCheckAll(x,y)
676 #endif
677 
678 /*
679 ** Remember that the parser tree element pPtr was created using
680 ** the token pToken.
681 **
682 ** In other words, construct a new RenameToken object and add it
683 ** to the list of RenameToken objects currently being built up
684 ** in pParse->pRename.
685 **
686 ** The pPtr argument is returned so that this routine can be used
687 ** with tail recursion in tokenExpr() routine, for a small performance
688 ** improvement.
689 */
690 void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
691   RenameToken *pNew;
692   assert( pPtr || pParse->db->mallocFailed );
693   renameTokenCheckAll(pParse, pPtr);
694   pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
695   if( pNew ){
696     pNew->p = pPtr;
697     pNew->t = *pToken;
698     pNew->pNext = pParse->pRename;
699     pParse->pRename = pNew;
700   }
701 
702   return pPtr;
703 }
704 
705 /*
706 ** It is assumed that there is already a RenameToken object associated
707 ** with parse tree element pFrom. This function remaps the associated token
708 ** to parse tree element pTo.
709 */
710 void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
711   RenameToken *p;
712   renameTokenCheckAll(pParse, pTo);
713   for(p=pParse->pRename; p; p=p->pNext){
714     if( p->p==pFrom ){
715       p->p = pTo;
716       break;
717     }
718   }
719 }
720 
721 /*
722 ** Walker callback used by sqlite3RenameExprUnmap().
723 */
724 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
725   Parse *pParse = pWalker->pParse;
726   sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
727   return WRC_Continue;
728 }
729 
730 /*
731 ** Walker callback used by sqlite3RenameExprUnmap().
732 */
733 static int renameUnmapSelectCb(Walker *pWalker, Select *p){
734   Parse *pParse = pWalker->pParse;
735   int i;
736   if( ALWAYS(p->pEList) ){
737     ExprList *pList = p->pEList;
738     for(i=0; i<pList->nExpr; i++){
739       if( pList->a[i].zName ){
740         sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
741       }
742     }
743   }
744   if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */
745     SrcList *pSrc = p->pSrc;
746     for(i=0; i<pSrc->nSrc; i++){
747       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
748     }
749   }
750   return WRC_Continue;
751 }
752 
753 /*
754 ** Remove all nodes that are part of expression pExpr from the rename list.
755 */
756 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
757   Walker sWalker;
758   memset(&sWalker, 0, sizeof(Walker));
759   sWalker.pParse = pParse;
760   sWalker.xExprCallback = renameUnmapExprCb;
761   sWalker.xSelectCallback = renameUnmapSelectCb;
762   sqlite3WalkExpr(&sWalker, pExpr);
763 }
764 
765 /*
766 ** Remove all nodes that are part of expression-list pEList from the
767 ** rename list.
768 */
769 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
770   if( pEList ){
771     int i;
772     Walker sWalker;
773     memset(&sWalker, 0, sizeof(Walker));
774     sWalker.pParse = pParse;
775     sWalker.xExprCallback = renameUnmapExprCb;
776     sqlite3WalkExprList(&sWalker, pEList);
777     for(i=0; i<pEList->nExpr; i++){
778       sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
779     }
780   }
781 }
782 
783 /*
784 ** Free the list of RenameToken objects given in the second argument
785 */
786 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
787   RenameToken *pNext;
788   RenameToken *p;
789   for(p=pToken; p; p=pNext){
790     pNext = p->pNext;
791     sqlite3DbFree(db, p);
792   }
793 }
794 
795 /*
796 ** Search the Parse object passed as the first argument for a RenameToken
797 ** object associated with parse tree element pPtr. If found, remove it
798 ** from the Parse object and add it to the list maintained by the
799 ** RenameCtx object passed as the second argument.
800 */
801 static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
802   RenameToken **pp;
803   assert( pPtr!=0 );
804   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
805     if( (*pp)->p==pPtr ){
806       RenameToken *pToken = *pp;
807       *pp = pToken->pNext;
808       pToken->pNext = pCtx->pList;
809       pCtx->pList = pToken;
810       pCtx->nList++;
811       break;
812     }
813   }
814 }
815 
816 /*
817 ** Iterate through the Select objects that are part of WITH clauses attached
818 ** to select statement pSelect.
819 */
820 static void renameWalkWith(Walker *pWalker, Select *pSelect){
821   if( pSelect->pWith ){
822     int i;
823     for(i=0; i<pSelect->pWith->nCte; i++){
824       Select *p = pSelect->pWith->a[i].pSelect;
825       NameContext sNC;
826       memset(&sNC, 0, sizeof(sNC));
827       sNC.pParse = pWalker->pParse;
828       sqlite3SelectPrep(sNC.pParse, p, &sNC);
829       sqlite3WalkSelect(pWalker, p);
830     }
831   }
832 }
833 
834 /*
835 ** This is a Walker select callback. It does nothing. It is only required
836 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
837 ** descend into sub-select statements.
838 */
839 static int renameColumnSelectCb(Walker *pWalker, Select *p){
840   renameWalkWith(pWalker, p);
841   return WRC_Continue;
842 }
843 
844 /*
845 ** This is a Walker expression callback.
846 **
847 ** For every TK_COLUMN node in the expression tree, search to see
848 ** if the column being references is the column being renamed by an
849 ** ALTER TABLE statement.  If it is, then attach its associated
850 ** RenameToken object to the list of RenameToken objects being
851 ** constructed in RenameCtx object at pWalker->u.pRename.
852 */
853 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
854   RenameCtx *p = pWalker->u.pRename;
855   if( pExpr->op==TK_TRIGGER
856    && pExpr->iColumn==p->iCol
857    && pWalker->pParse->pTriggerTab==p->pTab
858   ){
859     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
860   }else if( pExpr->op==TK_COLUMN
861    && pExpr->iColumn==p->iCol
862    && p->pTab==pExpr->y.pTab
863   ){
864     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
865   }
866   return WRC_Continue;
867 }
868 
869 /*
870 ** The RenameCtx contains a list of tokens that reference a column that
871 ** is being renamed by an ALTER TABLE statement.  Return the "last"
872 ** RenameToken in the RenameCtx and remove that RenameToken from the
873 ** RenameContext.  "Last" means the last RenameToken encountered when
874 ** the input SQL is parsed from left to right.  Repeated calls to this routine
875 ** return all column name tokens in the order that they are encountered
876 ** in the SQL statement.
877 */
878 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
879   RenameToken *pBest = pCtx->pList;
880   RenameToken *pToken;
881   RenameToken **pp;
882 
883   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
884     if( pToken->t.z>pBest->t.z ) pBest = pToken;
885   }
886   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
887   *pp = pBest->pNext;
888 
889   return pBest;
890 }
891 
892 /*
893 ** An error occured while parsing or otherwise processing a database
894 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
895 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
896 ** sub-routine is currently stored in pParse->zErrMsg. This function
897 ** adds context to the error message and then stores it in pCtx.
898 */
899 static void renameColumnParseError(
900   sqlite3_context *pCtx,
901   int bPost,
902   sqlite3_value *pType,
903   sqlite3_value *pObject,
904   Parse *pParse
905 ){
906   const char *zT = (const char*)sqlite3_value_text(pType);
907   const char *zN = (const char*)sqlite3_value_text(pObject);
908   char *zErr;
909 
910   zErr = sqlite3_mprintf("error in %s %s%s: %s",
911       zT, zN, (bPost ? " after rename" : ""),
912       pParse->zErrMsg
913   );
914   sqlite3_result_error(pCtx, zErr, -1);
915   sqlite3_free(zErr);
916 }
917 
918 /*
919 ** For each name in the the expression-list pEList (i.e. each
920 ** pEList->a[i].zName) that matches the string in zOld, extract the
921 ** corresponding rename-token from Parse object pParse and add it
922 ** to the RenameCtx pCtx.
923 */
924 static void renameColumnElistNames(
925   Parse *pParse,
926   RenameCtx *pCtx,
927   ExprList *pEList,
928   const char *zOld
929 ){
930   if( pEList ){
931     int i;
932     for(i=0; i<pEList->nExpr; i++){
933       char *zName = pEList->a[i].zName;
934       if( 0==sqlite3_stricmp(zName, zOld) ){
935         renameTokenFind(pParse, pCtx, (void*)zName);
936       }
937     }
938   }
939 }
940 
941 /*
942 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
943 ** that matches the string in zOld, extract the corresponding rename-token
944 ** from Parse object pParse and add it to the RenameCtx pCtx.
945 */
946 static void renameColumnIdlistNames(
947   Parse *pParse,
948   RenameCtx *pCtx,
949   IdList *pIdList,
950   const char *zOld
951 ){
952   if( pIdList ){
953     int i;
954     for(i=0; i<pIdList->nId; i++){
955       char *zName = pIdList->a[i].zName;
956       if( 0==sqlite3_stricmp(zName, zOld) ){
957         renameTokenFind(pParse, pCtx, (void*)zName);
958       }
959     }
960   }
961 }
962 
963 /*
964 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
965 ** is initialized by this function before it is used.
966 */
967 static int renameParseSql(
968   Parse *p,                       /* Memory to use for Parse object */
969   const char *zDb,                /* Name of schema SQL belongs to */
970   int bTable,                     /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
971   sqlite3 *db,                    /* Database handle */
972   const char *zSql,               /* SQL to parse */
973   int bTemp                       /* True if SQL is from temp schema */
974 ){
975   int rc;
976   char *zErr = 0;
977 
978   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
979 
980   /* Parse the SQL statement passed as the first argument. If no error
981   ** occurs and the parse does not result in a new table, index or
982   ** trigger object, the database must be corrupt. */
983   memset(p, 0, sizeof(Parse));
984   p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
985   p->db = db;
986   p->nQueryLoop = 1;
987   rc = sqlite3RunParser(p, zSql, &zErr);
988   assert( p->zErrMsg==0 );
989   assert( rc!=SQLITE_OK || zErr==0 );
990   p->zErrMsg = zErr;
991   if( db->mallocFailed ) rc = SQLITE_NOMEM;
992   if( rc==SQLITE_OK
993    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
994   ){
995     rc = SQLITE_CORRUPT_BKPT;
996   }
997 
998 #ifdef SQLITE_DEBUG
999   /* Ensure that all mappings in the Parse.pRename list really do map to
1000   ** a part of the input string.  */
1001   if( rc==SQLITE_OK ){
1002     int nSql = sqlite3Strlen30(zSql);
1003     RenameToken *pToken;
1004     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1005       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1006     }
1007   }
1008 #endif
1009 
1010   db->init.iDb = 0;
1011   return rc;
1012 }
1013 
1014 /*
1015 ** This function edits SQL statement zSql, replacing each token identified
1016 ** by the linked list pRename with the text of zNew. If argument bQuote is
1017 ** true, then zNew is always quoted first. If no error occurs, the result
1018 ** is loaded into context object pCtx as the result.
1019 **
1020 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1021 ** pCtx and an SQLite error code returned.
1022 */
1023 static int renameEditSql(
1024   sqlite3_context *pCtx,          /* Return result here */
1025   RenameCtx *pRename,             /* Rename context */
1026   const char *zSql,               /* SQL statement to edit */
1027   const char *zNew,               /* New token text */
1028   int bQuote                      /* True to always quote token */
1029 ){
1030   int nNew = sqlite3Strlen30(zNew);
1031   int nSql = sqlite3Strlen30(zSql);
1032   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1033   int rc = SQLITE_OK;
1034   char *zQuot;
1035   char *zOut;
1036   int nQuot;
1037 
1038   /* Set zQuot to point to a buffer containing a quoted copy of the
1039   ** identifier zNew. If the corresponding identifier in the original
1040   ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1041   ** point to zQuot so that all substitutions are made using the
1042   ** quoted version of the new column name.  */
1043   zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
1044   if( zQuot==0 ){
1045     return SQLITE_NOMEM;
1046   }else{
1047     nQuot = sqlite3Strlen30(zQuot);
1048   }
1049   if( bQuote ){
1050     zNew = zQuot;
1051     nNew = nQuot;
1052   }
1053 
1054   /* At this point pRename->pList contains a list of RenameToken objects
1055   ** corresponding to all tokens in the input SQL that must be replaced
1056   ** with the new column name. All that remains is to construct and
1057   ** return the edited SQL string. */
1058   assert( nQuot>=nNew );
1059   zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1060   if( zOut ){
1061     int nOut = nSql;
1062     memcpy(zOut, zSql, nSql);
1063     while( pRename->pList ){
1064       int iOff;                   /* Offset of token to replace in zOut */
1065       RenameToken *pBest = renameColumnTokenNext(pRename);
1066 
1067       u32 nReplace;
1068       const char *zReplace;
1069       if( sqlite3IsIdChar(*pBest->t.z) ){
1070         nReplace = nNew;
1071         zReplace = zNew;
1072       }else{
1073         nReplace = nQuot;
1074         zReplace = zQuot;
1075       }
1076 
1077       iOff = pBest->t.z - zSql;
1078       if( pBest->t.n!=nReplace ){
1079         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1080             nOut - (iOff + pBest->t.n)
1081         );
1082         nOut += nReplace - pBest->t.n;
1083         zOut[nOut] = '\0';
1084       }
1085       memcpy(&zOut[iOff], zReplace, nReplace);
1086       sqlite3DbFree(db, pBest);
1087     }
1088 
1089     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1090     sqlite3DbFree(db, zOut);
1091   }else{
1092     rc = SQLITE_NOMEM;
1093   }
1094 
1095   sqlite3_free(zQuot);
1096   return rc;
1097 }
1098 
1099 /*
1100 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1101 ** it was read from the schema of database zDb. Return SQLITE_OK if
1102 ** successful. Otherwise, return an SQLite error code and leave an error
1103 ** message in the Parse object.
1104 */
1105 static int renameResolveTrigger(Parse *pParse, const char *zDb){
1106   sqlite3 *db = pParse->db;
1107   Trigger *pNew = pParse->pNewTrigger;
1108   TriggerStep *pStep;
1109   NameContext sNC;
1110   int rc = SQLITE_OK;
1111 
1112   memset(&sNC, 0, sizeof(sNC));
1113   sNC.pParse = pParse;
1114   assert( pNew->pTabSchema );
1115   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1116       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1117   );
1118   pParse->eTriggerOp = pNew->op;
1119   /* ALWAYS() because if the table of the trigger does not exist, the
1120   ** error would have been hit before this point */
1121   if( ALWAYS(pParse->pTriggerTab) ){
1122     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1123   }
1124 
1125   /* Resolve symbols in WHEN clause */
1126   if( rc==SQLITE_OK && pNew->pWhen ){
1127     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1128   }
1129 
1130   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1131     if( pStep->pSelect ){
1132       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1133       if( pParse->nErr ) rc = pParse->rc;
1134     }
1135     if( rc==SQLITE_OK && pStep->zTarget ){
1136       Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1137       if( pTarget==0 ){
1138         rc = SQLITE_ERROR;
1139       }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
1140         SrcList sSrc;
1141         memset(&sSrc, 0, sizeof(sSrc));
1142         sSrc.nSrc = 1;
1143         sSrc.a[0].zName = pStep->zTarget;
1144         sSrc.a[0].pTab = pTarget;
1145         sNC.pSrcList = &sSrc;
1146         if( pStep->pWhere ){
1147           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1148         }
1149         if( rc==SQLITE_OK ){
1150           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1151         }
1152         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1153         if( pStep->pUpsert ){
1154           Upsert *pUpsert = pStep->pUpsert;
1155           assert( rc==SQLITE_OK );
1156           pUpsert->pUpsertSrc = &sSrc;
1157           sNC.uNC.pUpsert = pUpsert;
1158           sNC.ncFlags = NC_UUpsert;
1159           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1160           if( rc==SQLITE_OK ){
1161             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1162             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1163           }
1164           if( rc==SQLITE_OK ){
1165             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1166           }
1167           if( rc==SQLITE_OK ){
1168             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1169           }
1170           sNC.ncFlags = 0;
1171         }
1172         sNC.pSrcList = 0;
1173       }
1174     }
1175   }
1176   return rc;
1177 }
1178 
1179 /*
1180 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1181 ** objects that are part of the trigger passed as the second argument.
1182 */
1183 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1184   TriggerStep *pStep;
1185 
1186   /* Find tokens to edit in WHEN clause */
1187   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1188 
1189   /* Find tokens to edit in trigger steps */
1190   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1191     sqlite3WalkSelect(pWalker, pStep->pSelect);
1192     sqlite3WalkExpr(pWalker, pStep->pWhere);
1193     sqlite3WalkExprList(pWalker, pStep->pExprList);
1194     if( pStep->pUpsert ){
1195       Upsert *pUpsert = pStep->pUpsert;
1196       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1197       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1198       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1199       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1200     }
1201   }
1202 }
1203 
1204 /*
1205 ** Free the contents of Parse object (*pParse). Do not free the memory
1206 ** occupied by the Parse object itself.
1207 */
1208 static void renameParseCleanup(Parse *pParse){
1209   sqlite3 *db = pParse->db;
1210   Index *pIdx;
1211   if( pParse->pVdbe ){
1212     sqlite3VdbeFinalize(pParse->pVdbe);
1213   }
1214   sqlite3DeleteTable(db, pParse->pNewTable);
1215   while( (pIdx = pParse->pNewIndex)!=0 ){
1216     pParse->pNewIndex = pIdx->pNext;
1217     sqlite3FreeIndex(db, pIdx);
1218   }
1219   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1220   sqlite3DbFree(db, pParse->zErrMsg);
1221   renameTokenFree(db, pParse->pRename);
1222   sqlite3ParserReset(pParse);
1223 }
1224 
1225 /*
1226 ** SQL function:
1227 **
1228 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1229 **
1230 **   0. zSql:     SQL statement to rewrite
1231 **   1. type:     Type of object ("table", "view" etc.)
1232 **   2. object:   Name of object
1233 **   3. Database: Database name (e.g. "main")
1234 **   4. Table:    Table name
1235 **   5. iCol:     Index of column to rename
1236 **   6. zNew:     New column name
1237 **   7. bQuote:   Non-zero if the new column name should be quoted.
1238 **   8. bTemp:    True if zSql comes from temp schema
1239 **
1240 ** Do a column rename operation on the CREATE statement given in zSql.
1241 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1242 ** into zNew.  The name should be quoted if bQuote is true.
1243 **
1244 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1245 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1246 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1247 */
1248 static void renameColumnFunc(
1249   sqlite3_context *context,
1250   int NotUsed,
1251   sqlite3_value **argv
1252 ){
1253   sqlite3 *db = sqlite3_context_db_handle(context);
1254   RenameCtx sCtx;
1255   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1256   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1257   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1258   int iCol = sqlite3_value_int(argv[5]);
1259   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1260   int bQuote = sqlite3_value_int(argv[7]);
1261   int bTemp = sqlite3_value_int(argv[8]);
1262   const char *zOld;
1263   int rc;
1264   Parse sParse;
1265   Walker sWalker;
1266   Index *pIdx;
1267   int i;
1268   Table *pTab;
1269 #ifndef SQLITE_OMIT_AUTHORIZATION
1270   sqlite3_xauth xAuth = db->xAuth;
1271 #endif
1272 
1273   UNUSED_PARAMETER(NotUsed);
1274   if( zSql==0 ) return;
1275   if( zTable==0 ) return;
1276   if( zNew==0 ) return;
1277   if( iCol<0 ) return;
1278   sqlite3BtreeEnterAll(db);
1279   pTab = sqlite3FindTable(db, zTable, zDb);
1280   if( pTab==0 || iCol>=pTab->nCol ){
1281     sqlite3BtreeLeaveAll(db);
1282     return;
1283   }
1284   zOld = pTab->aCol[iCol].zName;
1285   memset(&sCtx, 0, sizeof(sCtx));
1286   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1287 
1288 #ifndef SQLITE_OMIT_AUTHORIZATION
1289   db->xAuth = 0;
1290 #endif
1291   rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
1292 
1293   /* Find tokens that need to be replaced. */
1294   memset(&sWalker, 0, sizeof(Walker));
1295   sWalker.pParse = &sParse;
1296   sWalker.xExprCallback = renameColumnExprCb;
1297   sWalker.xSelectCallback = renameColumnSelectCb;
1298   sWalker.u.pRename = &sCtx;
1299 
1300   sCtx.pTab = pTab;
1301   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1302   if( sParse.pNewTable ){
1303     Select *pSelect = sParse.pNewTable->pSelect;
1304     if( pSelect ){
1305       sParse.rc = SQLITE_OK;
1306       sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1307       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1308       if( rc==SQLITE_OK ){
1309         sqlite3WalkSelect(&sWalker, pSelect);
1310       }
1311       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1312     }else{
1313       /* A regular table */
1314       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1315       FKey *pFKey;
1316       assert( sParse.pNewTable->pSelect==0 );
1317       sCtx.pTab = sParse.pNewTable;
1318       if( bFKOnly==0 ){
1319         renameTokenFind(
1320             &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1321         );
1322         if( sCtx.iCol<0 ){
1323           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1324         }
1325         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1326         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1327           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1328         }
1329         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1330           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1331         }
1332       }
1333 
1334       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1335         for(i=0; i<pFKey->nCol; i++){
1336           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1337             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1338           }
1339           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1340            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1341           ){
1342             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1343           }
1344         }
1345       }
1346     }
1347   }else if( sParse.pNewIndex ){
1348     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1349     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1350   }else{
1351     /* A trigger */
1352     TriggerStep *pStep;
1353     rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
1354     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1355 
1356     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1357       if( pStep->zTarget ){
1358         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1359         if( pTarget==pTab ){
1360           if( pStep->pUpsert ){
1361             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1362             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1363           }
1364           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1365           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1366         }
1367       }
1368     }
1369 
1370 
1371     /* Find tokens to edit in UPDATE OF clause */
1372     if( sParse.pTriggerTab==pTab ){
1373       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1374     }
1375 
1376     /* Find tokens to edit in various expressions and selects */
1377     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1378   }
1379 
1380   assert( rc==SQLITE_OK );
1381   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1382 
1383 renameColumnFunc_done:
1384   if( rc!=SQLITE_OK ){
1385     if( sParse.zErrMsg ){
1386       renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1387     }else{
1388       sqlite3_result_error_code(context, rc);
1389     }
1390   }
1391 
1392   renameParseCleanup(&sParse);
1393   renameTokenFree(db, sCtx.pList);
1394 #ifndef SQLITE_OMIT_AUTHORIZATION
1395   db->xAuth = xAuth;
1396 #endif
1397   sqlite3BtreeLeaveAll(db);
1398 }
1399 
1400 /*
1401 ** Walker expression callback used by "RENAME TABLE".
1402 */
1403 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1404   RenameCtx *p = pWalker->u.pRename;
1405   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1406     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1407   }
1408   return WRC_Continue;
1409 }
1410 
1411 /*
1412 ** Walker select callback used by "RENAME TABLE".
1413 */
1414 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1415   int i;
1416   RenameCtx *p = pWalker->u.pRename;
1417   SrcList *pSrc = pSelect->pSrc;
1418   if( pSrc==0 ){
1419     assert( pWalker->pParse->db->mallocFailed );
1420     return WRC_Abort;
1421   }
1422   for(i=0; i<pSrc->nSrc; i++){
1423     struct SrcList_item *pItem = &pSrc->a[i];
1424     if( pItem->pTab==p->pTab ){
1425       renameTokenFind(pWalker->pParse, p, pItem->zName);
1426     }
1427   }
1428   renameWalkWith(pWalker, pSelect);
1429 
1430   return WRC_Continue;
1431 }
1432 
1433 
1434 /*
1435 ** This C function implements an SQL user function that is used by SQL code
1436 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1437 ** of any foreign key constraints that use the table being renamed as the
1438 ** parent table. It is passed three arguments:
1439 **
1440 **   0: The database containing the table being renamed.
1441 **   1. type:     Type of object ("table", "view" etc.)
1442 **   2. object:   Name of object
1443 **   3: The complete text of the schema statement being modified,
1444 **   4: The old name of the table being renamed, and
1445 **   5: The new name of the table being renamed.
1446 **   6: True if the schema statement comes from the temp db.
1447 **
1448 ** It returns the new schema statement. For example:
1449 **
1450 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1451 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1452 */
1453 static void renameTableFunc(
1454   sqlite3_context *context,
1455   int NotUsed,
1456   sqlite3_value **argv
1457 ){
1458   sqlite3 *db = sqlite3_context_db_handle(context);
1459   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1460   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1461   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1462   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1463   int bTemp = sqlite3_value_int(argv[6]);
1464   UNUSED_PARAMETER(NotUsed);
1465 
1466   if( zInput && zOld && zNew ){
1467     Parse sParse;
1468     int rc;
1469     int bQuote = 1;
1470     RenameCtx sCtx;
1471     Walker sWalker;
1472 
1473 #ifndef SQLITE_OMIT_AUTHORIZATION
1474     sqlite3_xauth xAuth = db->xAuth;
1475     db->xAuth = 0;
1476 #endif
1477 
1478     sqlite3BtreeEnterAll(db);
1479 
1480     memset(&sCtx, 0, sizeof(RenameCtx));
1481     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1482     memset(&sWalker, 0, sizeof(Walker));
1483     sWalker.pParse = &sParse;
1484     sWalker.xExprCallback = renameTableExprCb;
1485     sWalker.xSelectCallback = renameTableSelectCb;
1486     sWalker.u.pRename = &sCtx;
1487 
1488     rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1489 
1490     if( rc==SQLITE_OK ){
1491       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1492       if( sParse.pNewTable ){
1493         Table *pTab = sParse.pNewTable;
1494 
1495         if( pTab->pSelect ){
1496           if( isLegacy==0 ){
1497             NameContext sNC;
1498             memset(&sNC, 0, sizeof(sNC));
1499             sNC.pParse = &sParse;
1500 
1501             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1502             if( sParse.nErr ) rc = sParse.rc;
1503             sqlite3WalkSelect(&sWalker, pTab->pSelect);
1504           }
1505         }else{
1506           /* Modify any FK definitions to point to the new table. */
1507 #ifndef SQLITE_OMIT_FOREIGN_KEY
1508           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1509             FKey *pFKey;
1510             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1511               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1512                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1513               }
1514             }
1515           }
1516 #endif
1517 
1518           /* If this is the table being altered, fix any table refs in CHECK
1519           ** expressions. Also update the name that appears right after the
1520           ** "CREATE [VIRTUAL] TABLE" bit. */
1521           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1522             sCtx.pTab = pTab;
1523             if( isLegacy==0 ){
1524               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1525             }
1526             renameTokenFind(&sParse, &sCtx, pTab->zName);
1527           }
1528         }
1529       }
1530 
1531       else if( sParse.pNewIndex ){
1532         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1533         if( isLegacy==0 ){
1534           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1535         }
1536       }
1537 
1538 #ifndef SQLITE_OMIT_TRIGGER
1539       else{
1540         Trigger *pTrigger = sParse.pNewTrigger;
1541         TriggerStep *pStep;
1542         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1543             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1544           ){
1545           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1546         }
1547 
1548         if( isLegacy==0 ){
1549           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1550           if( rc==SQLITE_OK ){
1551             renameWalkTrigger(&sWalker, pTrigger);
1552             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1553               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1554                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1555               }
1556             }
1557           }
1558         }
1559       }
1560 #endif
1561     }
1562 
1563     if( rc==SQLITE_OK ){
1564       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1565     }
1566     if( rc!=SQLITE_OK ){
1567       if( sParse.zErrMsg ){
1568         renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1569       }else{
1570         sqlite3_result_error_code(context, rc);
1571       }
1572     }
1573 
1574     renameParseCleanup(&sParse);
1575     renameTokenFree(db, sCtx.pList);
1576     sqlite3BtreeLeaveAll(db);
1577 #ifndef SQLITE_OMIT_AUTHORIZATION
1578     db->xAuth = xAuth;
1579 #endif
1580   }
1581 
1582   return;
1583 }
1584 
1585 /*
1586 ** An SQL user function that checks that there are no parse or symbol
1587 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1588 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1589 ** reloaded, this function is called on each SQL statement in the schema
1590 ** to ensure that it is still usable.
1591 **
1592 **   0: Database name ("main", "temp" etc.).
1593 **   1: SQL statement.
1594 **   2: Object type ("view", "table", "trigger" or "index").
1595 **   3: Object name.
1596 **   4: True if object is from temp schema.
1597 **
1598 ** Unless it finds an error, this function normally returns NULL. However, it
1599 ** returns integer value 1 if:
1600 **
1601 **   * the SQL argument creates a trigger, and
1602 **   * the table that the trigger is attached to is in database zDb.
1603 */
1604 static void renameTableTest(
1605   sqlite3_context *context,
1606   int NotUsed,
1607   sqlite3_value **argv
1608 ){
1609   sqlite3 *db = sqlite3_context_db_handle(context);
1610   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1611   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1612   int bTemp = sqlite3_value_int(argv[4]);
1613   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1614 
1615 #ifndef SQLITE_OMIT_AUTHORIZATION
1616   sqlite3_xauth xAuth = db->xAuth;
1617   db->xAuth = 0;
1618 #endif
1619 
1620   UNUSED_PARAMETER(NotUsed);
1621   if( zDb && zInput ){
1622     int rc;
1623     Parse sParse;
1624     rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1625     if( rc==SQLITE_OK ){
1626       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1627         NameContext sNC;
1628         memset(&sNC, 0, sizeof(sNC));
1629         sNC.pParse = &sParse;
1630         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1631         if( sParse.nErr ) rc = sParse.rc;
1632       }
1633 
1634       else if( sParse.pNewTrigger ){
1635         if( isLegacy==0 ){
1636           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1637         }
1638         if( rc==SQLITE_OK ){
1639           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1640           int i2 = sqlite3FindDbName(db, zDb);
1641           if( i1==i2 ) sqlite3_result_int(context, 1);
1642         }
1643       }
1644     }
1645 
1646     if( rc!=SQLITE_OK ){
1647       renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
1648     }
1649     renameParseCleanup(&sParse);
1650   }
1651 
1652 #ifndef SQLITE_OMIT_AUTHORIZATION
1653   db->xAuth = xAuth;
1654 #endif
1655 }
1656 
1657 /*
1658 ** Register built-in functions used to help implement ALTER TABLE
1659 */
1660 void sqlite3AlterFunctions(void){
1661   static FuncDef aAlterTableFuncs[] = {
1662     INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1663     INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
1664     INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
1665   };
1666   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1667 }
1668 #endif  /* SQLITE_ALTER_TABLE */
1669