xref: /sqlite-3.40.0/src/alter.c (revision bd462bcc)
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 'sqlite_%%'"
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 'sqlite_%%'"
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.
170   ** Then modify the schema cookie (since the ALTER TABLE modifies the
171   ** schema). Open a statement transaction if the table is a virtual
172   ** table.
173   */
174   v = sqlite3GetVdbe(pParse);
175   if( v==0 ){
176     goto exit_rename_table;
177   }
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 'sqlite_%%'"
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 'sqlite_autoindex%%' AND type='index' THEN "
201              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
202             "ELSE name END "
203       "WHERE tbl_name=%Q COLLATE nocase AND "
204           "(type='table' OR type='index' OR type='trigger');",
205       zDb, MASTER_NAME,
206       zName, zName, zName,
207       nTabName, zTabName
208   );
209 
210 #ifndef SQLITE_OMIT_AUTOINCREMENT
211   /* If the sqlite_sequence table exists in this database, then update
212   ** it with the new table name.
213   */
214   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
215     sqlite3NestedParse(pParse,
216         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
217         zDb, zName, pTab->zName);
218   }
219 #endif
220 
221   /* If the table being renamed is not itself part of the temp database,
222   ** edit view and trigger definitions within the temp database
223   ** as required.  */
224   if( iDb!=1 ){
225     sqlite3NestedParse(pParse,
226         "UPDATE sqlite_temp_master SET "
227             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
228             "tbl_name = "
229               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
230               "          sqlite_rename_test(%Q, sql, type, name, 1) "
231               "THEN %Q ELSE tbl_name END "
232             "WHERE type IN ('view', 'trigger')"
233         , zDb, zTabName, zName, zTabName, zDb, zName);
234   }
235 
236   /* If this is a virtual table, invoke the xRename() function if
237   ** one is defined. The xRename() callback will modify the names
238   ** of any resources used by the v-table implementation (including other
239   ** SQLite tables) that are identified by the name of the virtual table.
240   */
241 #ifndef SQLITE_OMIT_VIRTUALTABLE
242   if( pVTab ){
243     int i = ++pParse->nMem;
244     sqlite3VdbeLoadString(v, i, zName);
245     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
246     sqlite3MayAbort(pParse);
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   zNew = sqlite3NameFromToken(db, pNew);
568   if( !zNew ) goto exit_rename_column;
569   assert( pNew->n>0 );
570   bQuote = sqlite3Isquote(pNew->z[0]);
571   sqlite3NestedParse(pParse,
572       "UPDATE \"%w\".%s SET "
573       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
574       "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
575       " AND sql NOT LIKE 'create virtual%%'",
576       zDb, MASTER_NAME,
577       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
578       pTab->zName
579   );
580 
581   sqlite3NestedParse(pParse,
582       "UPDATE temp.%s SET "
583       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
584       "WHERE type IN ('trigger', 'view')",
585       MASTER_NAME,
586       zDb, pTab->zName, iCol, zNew, bQuote
587   );
588 
589   /* Drop and reload the database schema. */
590   renameReloadSchema(pParse, iSchema);
591   renameTestSchema(pParse, zDb, iSchema==1);
592 
593  exit_rename_column:
594   sqlite3SrcListDelete(db, pSrc);
595   sqlite3DbFree(db, zOld);
596   sqlite3DbFree(db, zNew);
597   return;
598 }
599 
600 /*
601 ** Each RenameToken object maps an element of the parse tree into
602 ** the token that generated that element.  The parse tree element
603 ** might be one of:
604 **
605 **     *  A pointer to an Expr that represents an ID
606 **     *  The name of a table column in Column.zName
607 **
608 ** A list of RenameToken objects can be constructed during parsing.
609 ** Each new object is created by sqlite3RenameTokenMap().
610 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
611 ** routine is used to keep the mapping current.
612 **
613 ** After the parse finishes, renameTokenFind() routine can be used
614 ** to look up the actual token value that created some element in
615 ** the parse tree.
616 */
617 struct RenameToken {
618   void *p;               /* Parse tree element created by token t */
619   Token t;               /* The token that created parse tree element p */
620   RenameToken *pNext;    /* Next is a list of all RenameToken objects */
621 };
622 
623 /*
624 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
625 ** down into the Walker.
626 */
627 typedef struct RenameCtx RenameCtx;
628 struct RenameCtx {
629   RenameToken *pList;             /* List of tokens to overwrite */
630   int nList;                      /* Number of tokens in pList */
631   int iCol;                       /* Index of column being renamed */
632   Table *pTab;                    /* Table being ALTERed */
633   const char *zOld;               /* Old column name */
634 };
635 
636 #ifdef SQLITE_DEBUG
637 /*
638 ** This function is only for debugging. It performs two tasks:
639 **
640 **   1. Checks that pointer pPtr does not already appear in the
641 **      rename-token list.
642 **
643 **   2. Dereferences each pointer in the rename-token list.
644 **
645 ** The second is most effective when debugging under valgrind or
646 ** address-sanitizer or similar. If any of these pointers no longer
647 ** point to valid objects, an exception is raised by the memory-checking
648 ** tool.
649 **
650 ** The point of this is to prevent comparisons of invalid pointer values.
651 ** Even though this always seems to work, it is undefined according to the
652 ** C standard. Example of undefined comparison:
653 **
654 **     sqlite3_free(x);
655 **     if( x==y ) ...
656 **
657 ** Technically, as x no longer points into a valid object or to the byte
658 ** following a valid object, it may not be used in comparison operations.
659 */
660 static void renameTokenCheckAll(Parse *pParse, void *pPtr){
661   if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
662     RenameToken *p;
663     u8 i = 0;
664     for(p=pParse->pRename; p; p=p->pNext){
665       if( p->p ){
666         assert( p->p!=pPtr );
667         i += *(u8*)(p->p);
668       }
669     }
670   }
671 }
672 #else
673 # define renameTokenCheckAll(x,y)
674 #endif
675 
676 /*
677 ** Remember that the parser tree element pPtr was created using
678 ** the token pToken.
679 **
680 ** In other words, construct a new RenameToken object and add it
681 ** to the list of RenameToken objects currently being built up
682 ** in pParse->pRename.
683 **
684 ** The pPtr argument is returned so that this routine can be used
685 ** with tail recursion in tokenExpr() routine, for a small performance
686 ** improvement.
687 */
688 void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
689   RenameToken *pNew;
690   assert( pPtr || pParse->db->mallocFailed );
691   renameTokenCheckAll(pParse, pPtr);
692   pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
693   if( pNew ){
694     pNew->p = pPtr;
695     pNew->t = *pToken;
696     pNew->pNext = pParse->pRename;
697     pParse->pRename = pNew;
698   }
699 
700   return pPtr;
701 }
702 
703 /*
704 ** It is assumed that there is already a RenameToken object associated
705 ** with parse tree element pFrom. This function remaps the associated token
706 ** to parse tree element pTo.
707 */
708 void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
709   RenameToken *p;
710   renameTokenCheckAll(pParse, pTo);
711   for(p=pParse->pRename; p; p=p->pNext){
712     if( p->p==pFrom ){
713       p->p = pTo;
714       break;
715     }
716   }
717 }
718 
719 /*
720 ** Walker callback used by sqlite3RenameExprUnmap().
721 */
722 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
723   Parse *pParse = pWalker->pParse;
724   sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
725   return WRC_Continue;
726 }
727 
728 /*
729 ** Remove all nodes that are part of expression pExpr from the rename list.
730 */
731 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
732   Walker sWalker;
733   memset(&sWalker, 0, sizeof(Walker));
734   sWalker.pParse = pParse;
735   sWalker.xExprCallback = renameUnmapExprCb;
736   sqlite3WalkExpr(&sWalker, pExpr);
737 }
738 
739 /*
740 ** Remove all nodes that are part of expression-list pEList from the
741 ** rename list.
742 */
743 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
744   if( pEList ){
745     int i;
746     Walker sWalker;
747     memset(&sWalker, 0, sizeof(Walker));
748     sWalker.pParse = pParse;
749     sWalker.xExprCallback = renameUnmapExprCb;
750     sqlite3WalkExprList(&sWalker, pEList);
751     for(i=0; i<pEList->nExpr; i++){
752       sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
753     }
754   }
755 }
756 
757 /*
758 ** Free the list of RenameToken objects given in the second argument
759 */
760 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
761   RenameToken *pNext;
762   RenameToken *p;
763   for(p=pToken; p; p=pNext){
764     pNext = p->pNext;
765     sqlite3DbFree(db, p);
766   }
767 }
768 
769 /*
770 ** Search the Parse object passed as the first argument for a RenameToken
771 ** object associated with parse tree element pPtr. If found, remove it
772 ** from the Parse object and add it to the list maintained by the
773 ** RenameCtx object passed as the second argument.
774 */
775 static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
776   RenameToken **pp;
777   assert( pPtr!=0 );
778   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
779     if( (*pp)->p==pPtr ){
780       RenameToken *pToken = *pp;
781       *pp = pToken->pNext;
782       pToken->pNext = pCtx->pList;
783       pCtx->pList = pToken;
784       pCtx->nList++;
785       break;
786     }
787   }
788 }
789 
790 /*
791 ** Iterate through the Select objects that are part of WITH clauses attached
792 ** to select statement pSelect.
793 */
794 static void renameWalkWith(Walker *pWalker, Select *pSelect){
795   if( pSelect->pWith ){
796     int i;
797     for(i=0; i<pSelect->pWith->nCte; i++){
798       Select *p = pSelect->pWith->a[i].pSelect;
799       NameContext sNC;
800       memset(&sNC, 0, sizeof(sNC));
801       sNC.pParse = pWalker->pParse;
802       sqlite3SelectPrep(sNC.pParse, p, &sNC);
803       sqlite3WalkSelect(pWalker, p);
804     }
805   }
806 }
807 
808 /*
809 ** This is a Walker select callback. It does nothing. It is only required
810 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
811 ** descend into sub-select statements.
812 */
813 static int renameColumnSelectCb(Walker *pWalker, Select *p){
814   renameWalkWith(pWalker, p);
815   return WRC_Continue;
816 }
817 
818 /*
819 ** This is a Walker expression callback.
820 **
821 ** For every TK_COLUMN node in the expression tree, search to see
822 ** if the column being references is the column being renamed by an
823 ** ALTER TABLE statement.  If it is, then attach its associated
824 ** RenameToken object to the list of RenameToken objects being
825 ** constructed in RenameCtx object at pWalker->u.pRename.
826 */
827 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
828   RenameCtx *p = pWalker->u.pRename;
829   if( pExpr->op==TK_TRIGGER
830    && pExpr->iColumn==p->iCol
831    && pWalker->pParse->pTriggerTab==p->pTab
832   ){
833     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
834   }else if( pExpr->op==TK_COLUMN
835    && pExpr->iColumn==p->iCol
836    && p->pTab==pExpr->y.pTab
837   ){
838     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
839   }
840   return WRC_Continue;
841 }
842 
843 /*
844 ** The RenameCtx contains a list of tokens that reference a column that
845 ** is being renamed by an ALTER TABLE statement.  Return the "last"
846 ** RenameToken in the RenameCtx and remove that RenameToken from the
847 ** RenameContext.  "Last" means the last RenameToken encountered when
848 ** the input SQL is parsed from left to right.  Repeated calls to this routine
849 ** return all column name tokens in the order that they are encountered
850 ** in the SQL statement.
851 */
852 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
853   RenameToken *pBest = pCtx->pList;
854   RenameToken *pToken;
855   RenameToken **pp;
856 
857   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
858     if( pToken->t.z>pBest->t.z ) pBest = pToken;
859   }
860   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
861   *pp = pBest->pNext;
862 
863   return pBest;
864 }
865 
866 /*
867 ** An error occured while parsing or otherwise processing a database
868 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
869 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
870 ** sub-routine is currently stored in pParse->zErrMsg. This function
871 ** adds context to the error message and then stores it in pCtx.
872 */
873 static void renameColumnParseError(
874   sqlite3_context *pCtx,
875   int bPost,
876   sqlite3_value *pType,
877   sqlite3_value *pObject,
878   Parse *pParse
879 ){
880   const char *zT = (const char*)sqlite3_value_text(pType);
881   const char *zN = (const char*)sqlite3_value_text(pObject);
882   char *zErr;
883 
884   zErr = sqlite3_mprintf("error in %s %s%s: %s",
885       zT, zN, (bPost ? " after rename" : ""),
886       pParse->zErrMsg
887   );
888   sqlite3_result_error(pCtx, zErr, -1);
889   sqlite3_free(zErr);
890 }
891 
892 /*
893 ** For each name in the the expression-list pEList (i.e. each
894 ** pEList->a[i].zName) that matches the string in zOld, extract the
895 ** corresponding rename-token from Parse object pParse and add it
896 ** to the RenameCtx pCtx.
897 */
898 static void renameColumnElistNames(
899   Parse *pParse,
900   RenameCtx *pCtx,
901   ExprList *pEList,
902   const char *zOld
903 ){
904   if( pEList ){
905     int i;
906     for(i=0; i<pEList->nExpr; i++){
907       char *zName = pEList->a[i].zName;
908       if( 0==sqlite3_stricmp(zName, zOld) ){
909         renameTokenFind(pParse, pCtx, (void*)zName);
910       }
911     }
912   }
913 }
914 
915 /*
916 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
917 ** that matches the string in zOld, extract the corresponding rename-token
918 ** from Parse object pParse and add it to the RenameCtx pCtx.
919 */
920 static void renameColumnIdlistNames(
921   Parse *pParse,
922   RenameCtx *pCtx,
923   IdList *pIdList,
924   const char *zOld
925 ){
926   if( pIdList ){
927     int i;
928     for(i=0; i<pIdList->nId; i++){
929       char *zName = pIdList->a[i].zName;
930       if( 0==sqlite3_stricmp(zName, zOld) ){
931         renameTokenFind(pParse, pCtx, (void*)zName);
932       }
933     }
934   }
935 }
936 
937 /*
938 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
939 ** is initialized by this function before it is used.
940 */
941 static int renameParseSql(
942   Parse *p,                       /* Memory to use for Parse object */
943   const char *zDb,                /* Name of schema SQL belongs to */
944   int bTable,                     /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
945   sqlite3 *db,                    /* Database handle */
946   const char *zSql,               /* SQL to parse */
947   int bTemp                       /* True if SQL is from temp schema */
948 ){
949   int rc;
950   char *zErr = 0;
951 
952   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
953 
954   /* Parse the SQL statement passed as the first argument. If no error
955   ** occurs and the parse does not result in a new table, index or
956   ** trigger object, the database must be corrupt. */
957   memset(p, 0, sizeof(Parse));
958   p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
959   p->db = db;
960   p->nQueryLoop = 1;
961   rc = sqlite3RunParser(p, zSql, &zErr);
962   assert( p->zErrMsg==0 );
963   assert( rc!=SQLITE_OK || zErr==0 );
964   assert( (0!=p->pNewTable) + (0!=p->pNewIndex) + (0!=p->pNewTrigger)<2 );
965   p->zErrMsg = zErr;
966   if( db->mallocFailed ) rc = SQLITE_NOMEM;
967   if( rc==SQLITE_OK
968    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
969   ){
970     rc = SQLITE_CORRUPT_BKPT;
971   }
972 
973 #ifdef SQLITE_DEBUG
974   /* Ensure that all mappings in the Parse.pRename list really do map to
975   ** a part of the input string.  */
976   if( rc==SQLITE_OK ){
977     int nSql = sqlite3Strlen30(zSql);
978     RenameToken *pToken;
979     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
980       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
981     }
982   }
983 #endif
984 
985   db->init.iDb = 0;
986   return rc;
987 }
988 
989 /*
990 ** This function edits SQL statement zSql, replacing each token identified
991 ** by the linked list pRename with the text of zNew. If argument bQuote is
992 ** true, then zNew is always quoted first. If no error occurs, the result
993 ** is loaded into context object pCtx as the result.
994 **
995 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
996 ** pCtx and an SQLite error code returned.
997 */
998 static int renameEditSql(
999   sqlite3_context *pCtx,          /* Return result here */
1000   RenameCtx *pRename,             /* Rename context */
1001   const char *zSql,               /* SQL statement to edit */
1002   const char *zNew,               /* New token text */
1003   int bQuote                      /* True to always quote token */
1004 ){
1005   int nNew = sqlite3Strlen30(zNew);
1006   int nSql = sqlite3Strlen30(zSql);
1007   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1008   int rc = SQLITE_OK;
1009   char *zQuot;
1010   char *zOut;
1011   int nQuot;
1012 
1013   /* Set zQuot to point to a buffer containing a quoted copy of the
1014   ** identifier zNew. If the corresponding identifier in the original
1015   ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1016   ** point to zQuot so that all substitutions are made using the
1017   ** quoted version of the new column name.  */
1018   zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
1019   if( zQuot==0 ){
1020     return SQLITE_NOMEM;
1021   }else{
1022     nQuot = sqlite3Strlen30(zQuot);
1023   }
1024   if( bQuote ){
1025     zNew = zQuot;
1026     nNew = nQuot;
1027   }
1028 
1029   /* At this point pRename->pList contains a list of RenameToken objects
1030   ** corresponding to all tokens in the input SQL that must be replaced
1031   ** with the new column name. All that remains is to construct and
1032   ** return the edited SQL string. */
1033   assert( nQuot>=nNew );
1034   zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1035   if( zOut ){
1036     int nOut = nSql;
1037     memcpy(zOut, zSql, nSql);
1038     while( pRename->pList ){
1039       int iOff;                   /* Offset of token to replace in zOut */
1040       RenameToken *pBest = renameColumnTokenNext(pRename);
1041 
1042       u32 nReplace;
1043       const char *zReplace;
1044       if( sqlite3IsIdChar(*pBest->t.z) ){
1045         nReplace = nNew;
1046         zReplace = zNew;
1047       }else{
1048         nReplace = nQuot;
1049         zReplace = zQuot;
1050       }
1051 
1052       iOff = pBest->t.z - zSql;
1053       if( pBest->t.n!=nReplace ){
1054         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1055             nOut - (iOff + pBest->t.n)
1056         );
1057         nOut += nReplace - pBest->t.n;
1058         zOut[nOut] = '\0';
1059       }
1060       memcpy(&zOut[iOff], zReplace, nReplace);
1061       sqlite3DbFree(db, pBest);
1062     }
1063 
1064     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1065     sqlite3DbFree(db, zOut);
1066   }else{
1067     rc = SQLITE_NOMEM;
1068   }
1069 
1070   sqlite3_free(zQuot);
1071   return rc;
1072 }
1073 
1074 /*
1075 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1076 ** it was read from the schema of database zDb. Return SQLITE_OK if
1077 ** successful. Otherwise, return an SQLite error code and leave an error
1078 ** message in the Parse object.
1079 */
1080 static int renameResolveTrigger(Parse *pParse, const char *zDb){
1081   sqlite3 *db = pParse->db;
1082   Trigger *pNew = pParse->pNewTrigger;
1083   TriggerStep *pStep;
1084   NameContext sNC;
1085   int rc = SQLITE_OK;
1086 
1087   memset(&sNC, 0, sizeof(sNC));
1088   sNC.pParse = pParse;
1089   assert( pNew->pTabSchema );
1090   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1091       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1092   );
1093   pParse->eTriggerOp = pNew->op;
1094   /* ALWAYS() because if the table of the trigger does not exist, the
1095   ** error would have been hit before this point */
1096   if( ALWAYS(pParse->pTriggerTab) ){
1097     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1098   }
1099 
1100   /* Resolve symbols in WHEN clause */
1101   if( rc==SQLITE_OK && pNew->pWhen ){
1102     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1103   }
1104 
1105   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1106     if( pStep->pSelect ){
1107       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1108       if( pParse->nErr ) rc = pParse->rc;
1109     }
1110     if( rc==SQLITE_OK && pStep->zTarget ){
1111       Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1112       if( pTarget==0 ){
1113         rc = SQLITE_ERROR;
1114       }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
1115         SrcList sSrc;
1116         memset(&sSrc, 0, sizeof(sSrc));
1117         sSrc.nSrc = 1;
1118         sSrc.a[0].zName = pStep->zTarget;
1119         sSrc.a[0].pTab = pTarget;
1120         sNC.pSrcList = &sSrc;
1121         if( pStep->pWhere ){
1122           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1123         }
1124         if( rc==SQLITE_OK ){
1125           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1126         }
1127         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1128         if( pStep->pUpsert ){
1129           Upsert *pUpsert = pStep->pUpsert;
1130           assert( rc==SQLITE_OK );
1131           pUpsert->pUpsertSrc = &sSrc;
1132           sNC.uNC.pUpsert = pUpsert;
1133           sNC.ncFlags = NC_UUpsert;
1134           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1135           if( rc==SQLITE_OK ){
1136             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1137             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1138           }
1139           if( rc==SQLITE_OK ){
1140             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1141           }
1142           if( rc==SQLITE_OK ){
1143             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1144           }
1145           sNC.ncFlags = 0;
1146         }
1147       }
1148     }
1149   }
1150   return rc;
1151 }
1152 
1153 /*
1154 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1155 ** objects that are part of the trigger passed as the second argument.
1156 */
1157 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1158   TriggerStep *pStep;
1159 
1160   /* Find tokens to edit in WHEN clause */
1161   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1162 
1163   /* Find tokens to edit in trigger steps */
1164   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1165     sqlite3WalkSelect(pWalker, pStep->pSelect);
1166     sqlite3WalkExpr(pWalker, pStep->pWhere);
1167     sqlite3WalkExprList(pWalker, pStep->pExprList);
1168     if( pStep->pUpsert ){
1169       Upsert *pUpsert = pStep->pUpsert;
1170       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1171       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1172       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1173       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1174     }
1175   }
1176 }
1177 
1178 /*
1179 ** Free the contents of Parse object (*pParse). Do not free the memory
1180 ** occupied by the Parse object itself.
1181 */
1182 static void renameParseCleanup(Parse *pParse){
1183   sqlite3 *db = pParse->db;
1184   if( pParse->pVdbe ){
1185     sqlite3VdbeFinalize(pParse->pVdbe);
1186   }
1187   sqlite3DeleteTable(db, pParse->pNewTable);
1188   if( pParse->pNewIndex ) sqlite3FreeIndex(db, pParse->pNewIndex);
1189   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1190   sqlite3DbFree(db, pParse->zErrMsg);
1191   renameTokenFree(db, pParse->pRename);
1192   sqlite3ParserReset(pParse);
1193 }
1194 
1195 /*
1196 ** SQL function:
1197 **
1198 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1199 **
1200 **   0. zSql:     SQL statement to rewrite
1201 **   1. type:     Type of object ("table", "view" etc.)
1202 **   2. object:   Name of object
1203 **   3. Database: Database name (e.g. "main")
1204 **   4. Table:    Table name
1205 **   5. iCol:     Index of column to rename
1206 **   6. zNew:     New column name
1207 **   7. bQuote:   Non-zero if the new column name should be quoted.
1208 **   8. bTemp:    True if zSql comes from temp schema
1209 **
1210 ** Do a column rename operation on the CREATE statement given in zSql.
1211 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1212 ** into zNew.  The name should be quoted if bQuote is true.
1213 **
1214 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1215 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1216 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1217 */
1218 static void renameColumnFunc(
1219   sqlite3_context *context,
1220   int NotUsed,
1221   sqlite3_value **argv
1222 ){
1223   sqlite3 *db = sqlite3_context_db_handle(context);
1224   RenameCtx sCtx;
1225   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1226   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1227   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1228   int iCol = sqlite3_value_int(argv[5]);
1229   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1230   int bQuote = sqlite3_value_int(argv[7]);
1231   int bTemp = sqlite3_value_int(argv[8]);
1232   const char *zOld;
1233   int rc;
1234   Parse sParse;
1235   Walker sWalker;
1236   Index *pIdx;
1237   int i;
1238   Table *pTab;
1239 #ifndef SQLITE_OMIT_AUTHORIZATION
1240   sqlite3_xauth xAuth = db->xAuth;
1241 #endif
1242 
1243   UNUSED_PARAMETER(NotUsed);
1244   if( zSql==0 ) return;
1245   if( zTable==0 ) return;
1246   if( zNew==0 ) return;
1247   if( iCol<0 ) return;
1248   sqlite3BtreeEnterAll(db);
1249   pTab = sqlite3FindTable(db, zTable, zDb);
1250   if( pTab==0 || iCol>=pTab->nCol ){
1251     sqlite3BtreeLeaveAll(db);
1252     return;
1253   }
1254   zOld = pTab->aCol[iCol].zName;
1255   memset(&sCtx, 0, sizeof(sCtx));
1256   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1257 
1258 #ifndef SQLITE_OMIT_AUTHORIZATION
1259   db->xAuth = 0;
1260 #endif
1261   rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
1262 
1263   /* Find tokens that need to be replaced. */
1264   memset(&sWalker, 0, sizeof(Walker));
1265   sWalker.pParse = &sParse;
1266   sWalker.xExprCallback = renameColumnExprCb;
1267   sWalker.xSelectCallback = renameColumnSelectCb;
1268   sWalker.u.pRename = &sCtx;
1269 
1270   sCtx.pTab = pTab;
1271   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1272   if( sParse.pNewTable ){
1273     Select *pSelect = sParse.pNewTable->pSelect;
1274     if( pSelect ){
1275       sParse.rc = SQLITE_OK;
1276       sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1277       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1278       if( rc==SQLITE_OK ){
1279         sqlite3WalkSelect(&sWalker, pSelect);
1280       }
1281       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1282     }else{
1283       /* A regular table */
1284       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1285       FKey *pFKey;
1286       assert( sParse.pNewTable->pSelect==0 );
1287       sCtx.pTab = sParse.pNewTable;
1288       if( bFKOnly==0 ){
1289         renameTokenFind(
1290             &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1291         );
1292         if( sCtx.iCol<0 ){
1293           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1294         }
1295         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1296         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1297           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1298         }
1299       }
1300 
1301       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1302         for(i=0; i<pFKey->nCol; i++){
1303           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1304             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1305           }
1306           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1307            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1308           ){
1309             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1310           }
1311         }
1312       }
1313     }
1314   }else if( sParse.pNewIndex ){
1315     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1316     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1317   }else{
1318     /* A trigger */
1319     TriggerStep *pStep;
1320     rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
1321     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1322 
1323     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1324       if( pStep->zTarget ){
1325         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1326         if( pTarget==pTab ){
1327           if( pStep->pUpsert ){
1328             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1329             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1330           }
1331           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1332           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1333         }
1334       }
1335     }
1336 
1337 
1338     /* Find tokens to edit in UPDATE OF clause */
1339     if( sParse.pTriggerTab==pTab ){
1340       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1341     }
1342 
1343     /* Find tokens to edit in various expressions and selects */
1344     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1345   }
1346 
1347   assert( rc==SQLITE_OK );
1348   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1349 
1350 renameColumnFunc_done:
1351   if( rc!=SQLITE_OK ){
1352     if( sParse.zErrMsg ){
1353       renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1354     }else{
1355       sqlite3_result_error_code(context, rc);
1356     }
1357   }
1358 
1359   renameParseCleanup(&sParse);
1360   renameTokenFree(db, sCtx.pList);
1361 #ifndef SQLITE_OMIT_AUTHORIZATION
1362   db->xAuth = xAuth;
1363 #endif
1364   sqlite3BtreeLeaveAll(db);
1365 }
1366 
1367 /*
1368 ** Walker expression callback used by "RENAME TABLE".
1369 */
1370 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1371   RenameCtx *p = pWalker->u.pRename;
1372   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1373     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1374   }
1375   return WRC_Continue;
1376 }
1377 
1378 /*
1379 ** Walker select callback used by "RENAME TABLE".
1380 */
1381 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1382   int i;
1383   RenameCtx *p = pWalker->u.pRename;
1384   SrcList *pSrc = pSelect->pSrc;
1385   if( pSrc==0 ){
1386     assert( pWalker->pParse->db->mallocFailed );
1387     return WRC_Abort;
1388   }
1389   for(i=0; i<pSrc->nSrc; i++){
1390     struct SrcList_item *pItem = &pSrc->a[i];
1391     if( pItem->pTab==p->pTab ){
1392       renameTokenFind(pWalker->pParse, p, pItem->zName);
1393     }
1394   }
1395   renameWalkWith(pWalker, pSelect);
1396 
1397   return WRC_Continue;
1398 }
1399 
1400 
1401 /*
1402 ** This C function implements an SQL user function that is used by SQL code
1403 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1404 ** of any foreign key constraints that use the table being renamed as the
1405 ** parent table. It is passed three arguments:
1406 **
1407 **   0: The database containing the table being renamed.
1408 **   1. type:     Type of object ("table", "view" etc.)
1409 **   2. object:   Name of object
1410 **   3: The complete text of the schema statement being modified,
1411 **   4: The old name of the table being renamed, and
1412 **   5: The new name of the table being renamed.
1413 **   6: True if the schema statement comes from the temp db.
1414 **
1415 ** It returns the new schema statement. For example:
1416 **
1417 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1418 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1419 */
1420 static void renameTableFunc(
1421   sqlite3_context *context,
1422   int NotUsed,
1423   sqlite3_value **argv
1424 ){
1425   sqlite3 *db = sqlite3_context_db_handle(context);
1426   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1427   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1428   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1429   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1430   int bTemp = sqlite3_value_int(argv[6]);
1431   UNUSED_PARAMETER(NotUsed);
1432 
1433   if( zInput && zOld && zNew ){
1434     Parse sParse;
1435     int rc;
1436     int bQuote = 1;
1437     RenameCtx sCtx;
1438     Walker sWalker;
1439 
1440 #ifndef SQLITE_OMIT_AUTHORIZATION
1441     sqlite3_xauth xAuth = db->xAuth;
1442     db->xAuth = 0;
1443 #endif
1444 
1445     sqlite3BtreeEnterAll(db);
1446 
1447     memset(&sCtx, 0, sizeof(RenameCtx));
1448     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1449     memset(&sWalker, 0, sizeof(Walker));
1450     sWalker.pParse = &sParse;
1451     sWalker.xExprCallback = renameTableExprCb;
1452     sWalker.xSelectCallback = renameTableSelectCb;
1453     sWalker.u.pRename = &sCtx;
1454 
1455     rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1456 
1457     if( rc==SQLITE_OK ){
1458       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1459       if( sParse.pNewTable ){
1460         Table *pTab = sParse.pNewTable;
1461 
1462         if( pTab->pSelect ){
1463           if( isLegacy==0 ){
1464             NameContext sNC;
1465             memset(&sNC, 0, sizeof(sNC));
1466             sNC.pParse = &sParse;
1467 
1468             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1469             if( sParse.nErr ) rc = sParse.rc;
1470             sqlite3WalkSelect(&sWalker, pTab->pSelect);
1471           }
1472         }else{
1473           /* Modify any FK definitions to point to the new table. */
1474 #ifndef SQLITE_OMIT_FOREIGN_KEY
1475           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1476             FKey *pFKey;
1477             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1478               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1479                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1480               }
1481             }
1482           }
1483 #endif
1484 
1485           /* If this is the table being altered, fix any table refs in CHECK
1486           ** expressions. Also update the name that appears right after the
1487           ** "CREATE [VIRTUAL] TABLE" bit. */
1488           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1489             sCtx.pTab = pTab;
1490             if( isLegacy==0 ){
1491               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1492             }
1493             renameTokenFind(&sParse, &sCtx, pTab->zName);
1494           }
1495         }
1496       }
1497 
1498       else if( sParse.pNewIndex ){
1499         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1500         if( isLegacy==0 ){
1501           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1502         }
1503       }
1504 
1505 #ifndef SQLITE_OMIT_TRIGGER
1506       else{
1507         Trigger *pTrigger = sParse.pNewTrigger;
1508         TriggerStep *pStep;
1509         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1510             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1511           ){
1512           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1513         }
1514 
1515         if( isLegacy==0 ){
1516           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1517           if( rc==SQLITE_OK ){
1518             renameWalkTrigger(&sWalker, pTrigger);
1519             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1520               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1521                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1522               }
1523             }
1524           }
1525         }
1526       }
1527 #endif
1528     }
1529 
1530     if( rc==SQLITE_OK ){
1531       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1532     }
1533     if( rc!=SQLITE_OK ){
1534       if( sParse.zErrMsg ){
1535         renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1536       }else{
1537         sqlite3_result_error_code(context, rc);
1538       }
1539     }
1540 
1541     renameParseCleanup(&sParse);
1542     renameTokenFree(db, sCtx.pList);
1543     sqlite3BtreeLeaveAll(db);
1544 #ifndef SQLITE_OMIT_AUTHORIZATION
1545     db->xAuth = xAuth;
1546 #endif
1547   }
1548 
1549   return;
1550 }
1551 
1552 /*
1553 ** An SQL user function that checks that there are no parse or symbol
1554 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1555 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1556 ** reloaded, this function is called on each SQL statement in the schema
1557 ** to ensure that it is still usable.
1558 **
1559 **   0: Database name ("main", "temp" etc.).
1560 **   1: SQL statement.
1561 **   2: Object type ("view", "table", "trigger" or "index").
1562 **   3: Object name.
1563 **   4: True if object is from temp schema.
1564 **
1565 ** Unless it finds an error, this function normally returns NULL. However, it
1566 ** returns integer value 1 if:
1567 **
1568 **   * the SQL argument creates a trigger, and
1569 **   * the table that the trigger is attached to is in database zDb.
1570 */
1571 static void renameTableTest(
1572   sqlite3_context *context,
1573   int NotUsed,
1574   sqlite3_value **argv
1575 ){
1576   sqlite3 *db = sqlite3_context_db_handle(context);
1577   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1578   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1579   int bTemp = sqlite3_value_int(argv[4]);
1580   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1581 
1582 #ifndef SQLITE_OMIT_AUTHORIZATION
1583   sqlite3_xauth xAuth = db->xAuth;
1584   db->xAuth = 0;
1585 #endif
1586 
1587   UNUSED_PARAMETER(NotUsed);
1588   if( zDb && zInput ){
1589     int rc;
1590     Parse sParse;
1591     rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1592     if( rc==SQLITE_OK ){
1593       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1594         NameContext sNC;
1595         memset(&sNC, 0, sizeof(sNC));
1596         sNC.pParse = &sParse;
1597         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1598         if( sParse.nErr ) rc = sParse.rc;
1599       }
1600 
1601       else if( sParse.pNewTrigger ){
1602         if( isLegacy==0 ){
1603           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1604         }
1605         if( rc==SQLITE_OK ){
1606           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1607           int i2 = sqlite3FindDbName(db, zDb);
1608           if( i1==i2 ) sqlite3_result_int(context, 1);
1609         }
1610       }
1611     }
1612 
1613     if( rc!=SQLITE_OK ){
1614       renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
1615     }
1616     renameParseCleanup(&sParse);
1617   }
1618 
1619 #ifndef SQLITE_OMIT_AUTHORIZATION
1620   db->xAuth = xAuth;
1621 #endif
1622 }
1623 
1624 /*
1625 ** Register built-in functions used to help implement ALTER TABLE
1626 */
1627 void sqlite3AlterFunctions(void){
1628   static FuncDef aAlterTableFuncs[] = {
1629     INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1630     INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
1631     INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
1632   };
1633   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1634 }
1635 #endif  /* SQLITE_ALTER_TABLE */
1636