xref: /sqlite-3.40.0/src/alter.c (revision e99cb2da)
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].zName ){
770         sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
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       sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
815     }
816   }
817 }
818 
819 /*
820 ** Free the list of RenameToken objects given in the second argument
821 */
822 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
823   RenameToken *pNext;
824   RenameToken *p;
825   for(p=pToken; p; p=pNext){
826     pNext = p->pNext;
827     sqlite3DbFree(db, p);
828   }
829 }
830 
831 /*
832 ** Search the Parse object passed as the first argument for a RenameToken
833 ** object associated with parse tree element pPtr. If found, remove it
834 ** from the Parse object and add it to the list maintained by the
835 ** RenameCtx object passed as the second argument.
836 */
837 static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
838   RenameToken **pp;
839   assert( pPtr!=0 );
840   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
841     if( (*pp)->p==pPtr ){
842       RenameToken *pToken = *pp;
843       *pp = pToken->pNext;
844       pToken->pNext = pCtx->pList;
845       pCtx->pList = pToken;
846       pCtx->nList++;
847       break;
848     }
849   }
850 }
851 
852 /*
853 ** This is a Walker select callback. It does nothing. It is only required
854 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
855 ** descend into sub-select statements.
856 */
857 static int renameColumnSelectCb(Walker *pWalker, Select *p){
858   if( p->selFlags & SF_View ) return WRC_Prune;
859   renameWalkWith(pWalker, p);
860   return WRC_Continue;
861 }
862 
863 /*
864 ** This is a Walker expression callback.
865 **
866 ** For every TK_COLUMN node in the expression tree, search to see
867 ** if the column being references is the column being renamed by an
868 ** ALTER TABLE statement.  If it is, then attach its associated
869 ** RenameToken object to the list of RenameToken objects being
870 ** constructed in RenameCtx object at pWalker->u.pRename.
871 */
872 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
873   RenameCtx *p = pWalker->u.pRename;
874   if( pExpr->op==TK_TRIGGER
875    && pExpr->iColumn==p->iCol
876    && pWalker->pParse->pTriggerTab==p->pTab
877   ){
878     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
879   }else if( pExpr->op==TK_COLUMN
880    && pExpr->iColumn==p->iCol
881    && p->pTab==pExpr->y.pTab
882   ){
883     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
884   }
885   return WRC_Continue;
886 }
887 
888 /*
889 ** The RenameCtx contains a list of tokens that reference a column that
890 ** is being renamed by an ALTER TABLE statement.  Return the "last"
891 ** RenameToken in the RenameCtx and remove that RenameToken from the
892 ** RenameContext.  "Last" means the last RenameToken encountered when
893 ** the input SQL is parsed from left to right.  Repeated calls to this routine
894 ** return all column name tokens in the order that they are encountered
895 ** in the SQL statement.
896 */
897 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
898   RenameToken *pBest = pCtx->pList;
899   RenameToken *pToken;
900   RenameToken **pp;
901 
902   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
903     if( pToken->t.z>pBest->t.z ) pBest = pToken;
904   }
905   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
906   *pp = pBest->pNext;
907 
908   return pBest;
909 }
910 
911 /*
912 ** An error occured while parsing or otherwise processing a database
913 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
914 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
915 ** sub-routine is currently stored in pParse->zErrMsg. This function
916 ** adds context to the error message and then stores it in pCtx.
917 */
918 static void renameColumnParseError(
919   sqlite3_context *pCtx,
920   int bPost,
921   sqlite3_value *pType,
922   sqlite3_value *pObject,
923   Parse *pParse
924 ){
925   const char *zT = (const char*)sqlite3_value_text(pType);
926   const char *zN = (const char*)sqlite3_value_text(pObject);
927   char *zErr;
928 
929   zErr = sqlite3_mprintf("error in %s %s%s: %s",
930       zT, zN, (bPost ? " after rename" : ""),
931       pParse->zErrMsg
932   );
933   sqlite3_result_error(pCtx, zErr, -1);
934   sqlite3_free(zErr);
935 }
936 
937 /*
938 ** For each name in the the expression-list pEList (i.e. each
939 ** pEList->a[i].zName) that matches the string in zOld, extract the
940 ** corresponding rename-token from Parse object pParse and add it
941 ** to the RenameCtx pCtx.
942 */
943 static void renameColumnElistNames(
944   Parse *pParse,
945   RenameCtx *pCtx,
946   ExprList *pEList,
947   const char *zOld
948 ){
949   if( pEList ){
950     int i;
951     for(i=0; i<pEList->nExpr; i++){
952       char *zName = pEList->a[i].zName;
953       if( 0==sqlite3_stricmp(zName, zOld) ){
954         renameTokenFind(pParse, pCtx, (void*)zName);
955       }
956     }
957   }
958 }
959 
960 /*
961 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
962 ** that matches the string in zOld, extract the corresponding rename-token
963 ** from Parse object pParse and add it to the RenameCtx pCtx.
964 */
965 static void renameColumnIdlistNames(
966   Parse *pParse,
967   RenameCtx *pCtx,
968   IdList *pIdList,
969   const char *zOld
970 ){
971   if( pIdList ){
972     int i;
973     for(i=0; i<pIdList->nId; i++){
974       char *zName = pIdList->a[i].zName;
975       if( 0==sqlite3_stricmp(zName, zOld) ){
976         renameTokenFind(pParse, pCtx, (void*)zName);
977       }
978     }
979   }
980 }
981 
982 /*
983 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
984 ** is initialized by this function before it is used.
985 */
986 static int renameParseSql(
987   Parse *p,                       /* Memory to use for Parse object */
988   const char *zDb,                /* Name of schema SQL belongs to */
989   sqlite3 *db,                    /* Database handle */
990   const char *zSql,               /* SQL to parse */
991   int bTemp                       /* True if SQL is from temp schema */
992 ){
993   int rc;
994   char *zErr = 0;
995 
996   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
997 
998   /* Parse the SQL statement passed as the first argument. If no error
999   ** occurs and the parse does not result in a new table, index or
1000   ** trigger object, the database must be corrupt. */
1001   memset(p, 0, sizeof(Parse));
1002   p->eParseMode = PARSE_MODE_RENAME;
1003   p->db = db;
1004   p->nQueryLoop = 1;
1005   rc = sqlite3RunParser(p, zSql, &zErr);
1006   assert( p->zErrMsg==0 );
1007   assert( rc!=SQLITE_OK || zErr==0 );
1008   p->zErrMsg = zErr;
1009   if( db->mallocFailed ) rc = SQLITE_NOMEM;
1010   if( rc==SQLITE_OK
1011    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1012   ){
1013     rc = SQLITE_CORRUPT_BKPT;
1014   }
1015 
1016 #ifdef SQLITE_DEBUG
1017   /* Ensure that all mappings in the Parse.pRename list really do map to
1018   ** a part of the input string.  */
1019   if( rc==SQLITE_OK ){
1020     int nSql = sqlite3Strlen30(zSql);
1021     RenameToken *pToken;
1022     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1023       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1024     }
1025   }
1026 #endif
1027 
1028   db->init.iDb = 0;
1029   return rc;
1030 }
1031 
1032 /*
1033 ** This function edits SQL statement zSql, replacing each token identified
1034 ** by the linked list pRename with the text of zNew. If argument bQuote is
1035 ** true, then zNew is always quoted first. If no error occurs, the result
1036 ** is loaded into context object pCtx as the result.
1037 **
1038 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1039 ** pCtx and an SQLite error code returned.
1040 */
1041 static int renameEditSql(
1042   sqlite3_context *pCtx,          /* Return result here */
1043   RenameCtx *pRename,             /* Rename context */
1044   const char *zSql,               /* SQL statement to edit */
1045   const char *zNew,               /* New token text */
1046   int bQuote                      /* True to always quote token */
1047 ){
1048   int nNew = sqlite3Strlen30(zNew);
1049   int nSql = sqlite3Strlen30(zSql);
1050   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1051   int rc = SQLITE_OK;
1052   char *zQuot;
1053   char *zOut;
1054   int nQuot;
1055 
1056   /* Set zQuot to point to a buffer containing a quoted copy of the
1057   ** identifier zNew. If the corresponding identifier in the original
1058   ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1059   ** point to zQuot so that all substitutions are made using the
1060   ** quoted version of the new column name.  */
1061   zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
1062   if( zQuot==0 ){
1063     return SQLITE_NOMEM;
1064   }else{
1065     nQuot = sqlite3Strlen30(zQuot);
1066   }
1067   if( bQuote ){
1068     zNew = zQuot;
1069     nNew = nQuot;
1070   }
1071 
1072   /* At this point pRename->pList contains a list of RenameToken objects
1073   ** corresponding to all tokens in the input SQL that must be replaced
1074   ** with the new column name. All that remains is to construct and
1075   ** return the edited SQL string. */
1076   assert( nQuot>=nNew );
1077   zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1078   if( zOut ){
1079     int nOut = nSql;
1080     memcpy(zOut, zSql, nSql);
1081     while( pRename->pList ){
1082       int iOff;                   /* Offset of token to replace in zOut */
1083       RenameToken *pBest = renameColumnTokenNext(pRename);
1084 
1085       u32 nReplace;
1086       const char *zReplace;
1087       if( sqlite3IsIdChar(*pBest->t.z) ){
1088         nReplace = nNew;
1089         zReplace = zNew;
1090       }else{
1091         nReplace = nQuot;
1092         zReplace = zQuot;
1093       }
1094 
1095       iOff = pBest->t.z - zSql;
1096       if( pBest->t.n!=nReplace ){
1097         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1098             nOut - (iOff + pBest->t.n)
1099         );
1100         nOut += nReplace - pBest->t.n;
1101         zOut[nOut] = '\0';
1102       }
1103       memcpy(&zOut[iOff], zReplace, nReplace);
1104       sqlite3DbFree(db, pBest);
1105     }
1106 
1107     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1108     sqlite3DbFree(db, zOut);
1109   }else{
1110     rc = SQLITE_NOMEM;
1111   }
1112 
1113   sqlite3_free(zQuot);
1114   return rc;
1115 }
1116 
1117 /*
1118 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1119 ** it was read from the schema of database zDb. Return SQLITE_OK if
1120 ** successful. Otherwise, return an SQLite error code and leave an error
1121 ** message in the Parse object.
1122 */
1123 static int renameResolveTrigger(Parse *pParse, const char *zDb){
1124   sqlite3 *db = pParse->db;
1125   Trigger *pNew = pParse->pNewTrigger;
1126   TriggerStep *pStep;
1127   NameContext sNC;
1128   int rc = SQLITE_OK;
1129 
1130   memset(&sNC, 0, sizeof(sNC));
1131   sNC.pParse = pParse;
1132   assert( pNew->pTabSchema );
1133   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1134       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1135   );
1136   pParse->eTriggerOp = pNew->op;
1137   /* ALWAYS() because if the table of the trigger does not exist, the
1138   ** error would have been hit before this point */
1139   if( ALWAYS(pParse->pTriggerTab) ){
1140     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1141   }
1142 
1143   /* Resolve symbols in WHEN clause */
1144   if( rc==SQLITE_OK && pNew->pWhen ){
1145     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1146   }
1147 
1148   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1149     if( pStep->pSelect ){
1150       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1151       if( pParse->nErr ) rc = pParse->rc;
1152     }
1153     if( rc==SQLITE_OK && pStep->zTarget ){
1154       Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1155       if( pTarget==0 ){
1156         rc = SQLITE_ERROR;
1157       }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
1158         SrcList sSrc;
1159         memset(&sSrc, 0, sizeof(sSrc));
1160         sSrc.nSrc = 1;
1161         sSrc.a[0].zName = pStep->zTarget;
1162         sSrc.a[0].pTab = pTarget;
1163         sNC.pSrcList = &sSrc;
1164         if( pStep->pWhere ){
1165           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1166         }
1167         if( rc==SQLITE_OK ){
1168           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1169         }
1170         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1171         if( pStep->pUpsert ){
1172           Upsert *pUpsert = pStep->pUpsert;
1173           assert( rc==SQLITE_OK );
1174           pUpsert->pUpsertSrc = &sSrc;
1175           sNC.uNC.pUpsert = pUpsert;
1176           sNC.ncFlags = NC_UUpsert;
1177           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1178           if( rc==SQLITE_OK ){
1179             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1180             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1181           }
1182           if( rc==SQLITE_OK ){
1183             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1184           }
1185           if( rc==SQLITE_OK ){
1186             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1187           }
1188           sNC.ncFlags = 0;
1189         }
1190         sNC.pSrcList = 0;
1191       }
1192     }
1193   }
1194   return rc;
1195 }
1196 
1197 /*
1198 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1199 ** objects that are part of the trigger passed as the second argument.
1200 */
1201 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1202   TriggerStep *pStep;
1203 
1204   /* Find tokens to edit in WHEN clause */
1205   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1206 
1207   /* Find tokens to edit in trigger steps */
1208   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1209     sqlite3WalkSelect(pWalker, pStep->pSelect);
1210     sqlite3WalkExpr(pWalker, pStep->pWhere);
1211     sqlite3WalkExprList(pWalker, pStep->pExprList);
1212     if( pStep->pUpsert ){
1213       Upsert *pUpsert = pStep->pUpsert;
1214       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1215       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1216       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1217       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1218     }
1219   }
1220 }
1221 
1222 /*
1223 ** Free the contents of Parse object (*pParse). Do not free the memory
1224 ** occupied by the Parse object itself.
1225 */
1226 static void renameParseCleanup(Parse *pParse){
1227   sqlite3 *db = pParse->db;
1228   Index *pIdx;
1229   if( pParse->pVdbe ){
1230     sqlite3VdbeFinalize(pParse->pVdbe);
1231   }
1232   sqlite3DeleteTable(db, pParse->pNewTable);
1233   while( (pIdx = pParse->pNewIndex)!=0 ){
1234     pParse->pNewIndex = pIdx->pNext;
1235     sqlite3FreeIndex(db, pIdx);
1236   }
1237   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1238   sqlite3DbFree(db, pParse->zErrMsg);
1239   renameTokenFree(db, pParse->pRename);
1240   sqlite3ParserReset(pParse);
1241 }
1242 
1243 /*
1244 ** SQL function:
1245 **
1246 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1247 **
1248 **   0. zSql:     SQL statement to rewrite
1249 **   1. type:     Type of object ("table", "view" etc.)
1250 **   2. object:   Name of object
1251 **   3. Database: Database name (e.g. "main")
1252 **   4. Table:    Table name
1253 **   5. iCol:     Index of column to rename
1254 **   6. zNew:     New column name
1255 **   7. bQuote:   Non-zero if the new column name should be quoted.
1256 **   8. bTemp:    True if zSql comes from temp schema
1257 **
1258 ** Do a column rename operation on the CREATE statement given in zSql.
1259 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1260 ** into zNew.  The name should be quoted if bQuote is true.
1261 **
1262 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1263 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1264 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1265 */
1266 static void renameColumnFunc(
1267   sqlite3_context *context,
1268   int NotUsed,
1269   sqlite3_value **argv
1270 ){
1271   sqlite3 *db = sqlite3_context_db_handle(context);
1272   RenameCtx sCtx;
1273   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1274   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1275   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1276   int iCol = sqlite3_value_int(argv[5]);
1277   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1278   int bQuote = sqlite3_value_int(argv[7]);
1279   int bTemp = sqlite3_value_int(argv[8]);
1280   const char *zOld;
1281   int rc;
1282   Parse sParse;
1283   Walker sWalker;
1284   Index *pIdx;
1285   int i;
1286   Table *pTab;
1287 #ifndef SQLITE_OMIT_AUTHORIZATION
1288   sqlite3_xauth xAuth = db->xAuth;
1289 #endif
1290 
1291   UNUSED_PARAMETER(NotUsed);
1292   if( zSql==0 ) return;
1293   if( zTable==0 ) return;
1294   if( zNew==0 ) return;
1295   if( iCol<0 ) return;
1296   sqlite3BtreeEnterAll(db);
1297   pTab = sqlite3FindTable(db, zTable, zDb);
1298   if( pTab==0 || iCol>=pTab->nCol ){
1299     sqlite3BtreeLeaveAll(db);
1300     return;
1301   }
1302   zOld = pTab->aCol[iCol].zName;
1303   memset(&sCtx, 0, sizeof(sCtx));
1304   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1305 
1306 #ifndef SQLITE_OMIT_AUTHORIZATION
1307   db->xAuth = 0;
1308 #endif
1309   rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
1310 
1311   /* Find tokens that need to be replaced. */
1312   memset(&sWalker, 0, sizeof(Walker));
1313   sWalker.pParse = &sParse;
1314   sWalker.xExprCallback = renameColumnExprCb;
1315   sWalker.xSelectCallback = renameColumnSelectCb;
1316   sWalker.u.pRename = &sCtx;
1317 
1318   sCtx.pTab = pTab;
1319   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1320   if( sParse.pNewTable ){
1321     Select *pSelect = sParse.pNewTable->pSelect;
1322     if( pSelect ){
1323       pSelect->selFlags &= ~SF_View;
1324       sParse.rc = SQLITE_OK;
1325       sqlite3SelectPrep(&sParse, pSelect, 0);
1326       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1327       if( rc==SQLITE_OK ){
1328         sqlite3WalkSelect(&sWalker, pSelect);
1329       }
1330       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1331     }else{
1332       /* A regular table */
1333       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1334       FKey *pFKey;
1335       assert( sParse.pNewTable->pSelect==0 );
1336       sCtx.pTab = sParse.pNewTable;
1337       if( bFKOnly==0 ){
1338         renameTokenFind(
1339             &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1340         );
1341         if( sCtx.iCol<0 ){
1342           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1343         }
1344         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1345         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1346           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1347         }
1348         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1349           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1350         }
1351       }
1352 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1353       for(i=0; i<sParse.pNewTable->nCol; i++){
1354         sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1355       }
1356 #endif
1357 
1358       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1359         for(i=0; i<pFKey->nCol; i++){
1360           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1361             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1362           }
1363           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1364            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1365           ){
1366             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1367           }
1368         }
1369       }
1370     }
1371   }else if( sParse.pNewIndex ){
1372     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1373     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1374   }else{
1375     /* A trigger */
1376     TriggerStep *pStep;
1377     rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
1378     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1379 
1380     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1381       if( pStep->zTarget ){
1382         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1383         if( pTarget==pTab ){
1384           if( pStep->pUpsert ){
1385             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1386             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1387           }
1388           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1389           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1390         }
1391       }
1392     }
1393 
1394 
1395     /* Find tokens to edit in UPDATE OF clause */
1396     if( sParse.pTriggerTab==pTab ){
1397       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1398     }
1399 
1400     /* Find tokens to edit in various expressions and selects */
1401     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1402   }
1403 
1404   assert( rc==SQLITE_OK );
1405   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1406 
1407 renameColumnFunc_done:
1408   if( rc!=SQLITE_OK ){
1409     if( sParse.zErrMsg ){
1410       renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1411     }else{
1412       sqlite3_result_error_code(context, rc);
1413     }
1414   }
1415 
1416   renameParseCleanup(&sParse);
1417   renameTokenFree(db, sCtx.pList);
1418 #ifndef SQLITE_OMIT_AUTHORIZATION
1419   db->xAuth = xAuth;
1420 #endif
1421   sqlite3BtreeLeaveAll(db);
1422 }
1423 
1424 /*
1425 ** Walker expression callback used by "RENAME TABLE".
1426 */
1427 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1428   RenameCtx *p = pWalker->u.pRename;
1429   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1430     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1431   }
1432   return WRC_Continue;
1433 }
1434 
1435 /*
1436 ** Walker select callback used by "RENAME TABLE".
1437 */
1438 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1439   int i;
1440   RenameCtx *p = pWalker->u.pRename;
1441   SrcList *pSrc = pSelect->pSrc;
1442   if( pSelect->selFlags & SF_View ) return WRC_Prune;
1443   if( pSrc==0 ){
1444     assert( pWalker->pParse->db->mallocFailed );
1445     return WRC_Abort;
1446   }
1447   for(i=0; i<pSrc->nSrc; i++){
1448     struct SrcList_item *pItem = &pSrc->a[i];
1449     if( pItem->pTab==p->pTab ){
1450       renameTokenFind(pWalker->pParse, p, pItem->zName);
1451     }
1452   }
1453   renameWalkWith(pWalker, pSelect);
1454 
1455   return WRC_Continue;
1456 }
1457 
1458 
1459 /*
1460 ** This C function implements an SQL user function that is used by SQL code
1461 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1462 ** of any foreign key constraints that use the table being renamed as the
1463 ** parent table. It is passed three arguments:
1464 **
1465 **   0: The database containing the table being renamed.
1466 **   1. type:     Type of object ("table", "view" etc.)
1467 **   2. object:   Name of object
1468 **   3: The complete text of the schema statement being modified,
1469 **   4: The old name of the table being renamed, and
1470 **   5: The new name of the table being renamed.
1471 **   6: True if the schema statement comes from the temp db.
1472 **
1473 ** It returns the new schema statement. For example:
1474 **
1475 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1476 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1477 */
1478 static void renameTableFunc(
1479   sqlite3_context *context,
1480   int NotUsed,
1481   sqlite3_value **argv
1482 ){
1483   sqlite3 *db = sqlite3_context_db_handle(context);
1484   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1485   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1486   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1487   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1488   int bTemp = sqlite3_value_int(argv[6]);
1489   UNUSED_PARAMETER(NotUsed);
1490 
1491   if( zInput && zOld && zNew ){
1492     Parse sParse;
1493     int rc;
1494     int bQuote = 1;
1495     RenameCtx sCtx;
1496     Walker sWalker;
1497 
1498 #ifndef SQLITE_OMIT_AUTHORIZATION
1499     sqlite3_xauth xAuth = db->xAuth;
1500     db->xAuth = 0;
1501 #endif
1502 
1503     sqlite3BtreeEnterAll(db);
1504 
1505     memset(&sCtx, 0, sizeof(RenameCtx));
1506     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1507     memset(&sWalker, 0, sizeof(Walker));
1508     sWalker.pParse = &sParse;
1509     sWalker.xExprCallback = renameTableExprCb;
1510     sWalker.xSelectCallback = renameTableSelectCb;
1511     sWalker.u.pRename = &sCtx;
1512 
1513     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1514 
1515     if( rc==SQLITE_OK ){
1516       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1517       if( sParse.pNewTable ){
1518         Table *pTab = sParse.pNewTable;
1519 
1520         if( pTab->pSelect ){
1521           if( isLegacy==0 ){
1522             Select *pSelect = pTab->pSelect;
1523             NameContext sNC;
1524             memset(&sNC, 0, sizeof(sNC));
1525             sNC.pParse = &sParse;
1526 
1527             assert( pSelect->selFlags & SF_View );
1528             pSelect->selFlags &= ~SF_View;
1529             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1530             if( sParse.nErr ){
1531               rc = sParse.rc;
1532             }else{
1533               sqlite3WalkSelect(&sWalker, pTab->pSelect);
1534             }
1535           }
1536         }else{
1537           /* Modify any FK definitions to point to the new table. */
1538 #ifndef SQLITE_OMIT_FOREIGN_KEY
1539           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1540             FKey *pFKey;
1541             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1542               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1543                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1544               }
1545             }
1546           }
1547 #endif
1548 
1549           /* If this is the table being altered, fix any table refs in CHECK
1550           ** expressions. Also update the name that appears right after the
1551           ** "CREATE [VIRTUAL] TABLE" bit. */
1552           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1553             sCtx.pTab = pTab;
1554             if( isLegacy==0 ){
1555               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1556             }
1557             renameTokenFind(&sParse, &sCtx, pTab->zName);
1558           }
1559         }
1560       }
1561 
1562       else if( sParse.pNewIndex ){
1563         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1564         if( isLegacy==0 ){
1565           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1566         }
1567       }
1568 
1569 #ifndef SQLITE_OMIT_TRIGGER
1570       else{
1571         Trigger *pTrigger = sParse.pNewTrigger;
1572         TriggerStep *pStep;
1573         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1574             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1575           ){
1576           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1577         }
1578 
1579         if( isLegacy==0 ){
1580           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1581           if( rc==SQLITE_OK ){
1582             renameWalkTrigger(&sWalker, pTrigger);
1583             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1584               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1585                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1586               }
1587             }
1588           }
1589         }
1590       }
1591 #endif
1592     }
1593 
1594     if( rc==SQLITE_OK ){
1595       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1596     }
1597     if( rc!=SQLITE_OK ){
1598       if( sParse.zErrMsg ){
1599         renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1600       }else{
1601         sqlite3_result_error_code(context, rc);
1602       }
1603     }
1604 
1605     renameParseCleanup(&sParse);
1606     renameTokenFree(db, sCtx.pList);
1607     sqlite3BtreeLeaveAll(db);
1608 #ifndef SQLITE_OMIT_AUTHORIZATION
1609     db->xAuth = xAuth;
1610 #endif
1611   }
1612 
1613   return;
1614 }
1615 
1616 /*
1617 ** An SQL user function that checks that there are no parse or symbol
1618 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1619 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1620 ** reloaded, this function is called on each SQL statement in the schema
1621 ** to ensure that it is still usable.
1622 **
1623 **   0: Database name ("main", "temp" etc.).
1624 **   1: SQL statement.
1625 **   2: Object type ("view", "table", "trigger" or "index").
1626 **   3: Object name.
1627 **   4: True if object is from temp schema.
1628 **
1629 ** Unless it finds an error, this function normally returns NULL. However, it
1630 ** returns integer value 1 if:
1631 **
1632 **   * the SQL argument creates a trigger, and
1633 **   * the table that the trigger is attached to is in database zDb.
1634 */
1635 static void renameTableTest(
1636   sqlite3_context *context,
1637   int NotUsed,
1638   sqlite3_value **argv
1639 ){
1640   sqlite3 *db = sqlite3_context_db_handle(context);
1641   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1642   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1643   int bTemp = sqlite3_value_int(argv[4]);
1644   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1645 
1646 #ifndef SQLITE_OMIT_AUTHORIZATION
1647   sqlite3_xauth xAuth = db->xAuth;
1648   db->xAuth = 0;
1649 #endif
1650 
1651   UNUSED_PARAMETER(NotUsed);
1652   if( zDb && zInput ){
1653     int rc;
1654     Parse sParse;
1655     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1656     if( rc==SQLITE_OK ){
1657       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1658         NameContext sNC;
1659         memset(&sNC, 0, sizeof(sNC));
1660         sNC.pParse = &sParse;
1661         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1662         if( sParse.nErr ) rc = sParse.rc;
1663       }
1664 
1665       else if( sParse.pNewTrigger ){
1666         if( isLegacy==0 ){
1667           rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1668         }
1669         if( rc==SQLITE_OK ){
1670           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1671           int i2 = sqlite3FindDbName(db, zDb);
1672           if( i1==i2 ) sqlite3_result_int(context, 1);
1673         }
1674       }
1675     }
1676 
1677     if( rc!=SQLITE_OK ){
1678       renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
1679     }
1680     renameParseCleanup(&sParse);
1681   }
1682 
1683 #ifndef SQLITE_OMIT_AUTHORIZATION
1684   db->xAuth = xAuth;
1685 #endif
1686 }
1687 
1688 /*
1689 ** Register built-in functions used to help implement ALTER TABLE
1690 */
1691 void sqlite3AlterFunctions(void){
1692   static FuncDef aAlterTableFuncs[] = {
1693     INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1694     INTERNAL_FUNCTION(sqlite_rename_table,  7, renameTableFunc),
1695     INTERNAL_FUNCTION(sqlite_rename_test,   5, renameTableTest),
1696   };
1697   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1698 }
1699 #endif  /* SQLITE_ALTER_TABLE */
1700