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