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