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