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