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