xref: /sqlite-3.40.0/src/alter.c (revision 9cffb0ff)
1 /*
2 ** 2005 February 15
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains C code routines that used to generate VDBE code
13 ** that implements the ALTER TABLE command.
14 */
15 #include "sqliteInt.h"
16 
17 /*
18 ** The code in this file only exists if we are not omitting the
19 ** ALTER TABLE logic from the build.
20 */
21 #ifndef SQLITE_OMIT_ALTERTABLE
22 
23 /*
24 ** Parameter zName is the name of a table that is about to be altered
25 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
26 ** If the table is a system table, this function leaves an error message
27 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
28 **
29 ** Or, if zName is not a system table, zero is returned.
30 */
31 static int isAlterableTable(Parse *pParse, Table *pTab){
32   if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
33 #ifndef SQLITE_OMIT_VIRTUALTABLE
34    || ( (pTab->tabFlags & TF_Shadow)!=0
35         && sqlite3ReadOnlyShadowTables(pParse->db)
36    )
37 #endif
38   ){
39     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
40     return 1;
41   }
42   return 0;
43 }
44 
45 /*
46 ** Generate code to verify that the schemas of database zDb and, if
47 ** bTemp is not true, database "temp", can still be parsed. This is
48 ** called at the end of the generation of an ALTER TABLE ... RENAME ...
49 ** statement to ensure that the operation has not rendered any schema
50 ** objects unusable.
51 */
52 static void renameTestSchema(
53   Parse *pParse,                  /* Parse context */
54   const char *zDb,                /* Name of db to verify schema of */
55   int bTemp,                      /* True if this is the temp db */
56   const char *zWhen,              /* "when" part of error message */
57   int bNoDQS                      /* Do not allow DQS in the schema */
58 ){
59   pParse->colNamesSet = 1;
60   sqlite3NestedParse(pParse,
61       "SELECT 1 "
62       "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
63       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
64       " AND sql NOT LIKE 'create virtual%%'"
65       " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
66       zDb,
67       zDb, bTemp, zWhen, bNoDQS
68   );
69 
70   if( bTemp==0 ){
71     sqlite3NestedParse(pParse,
72         "SELECT 1 "
73         "FROM temp." DFLT_SCHEMA_TABLE " "
74         "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
75         " AND sql NOT LIKE 'create virtual%%'"
76         " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
77         zDb, zWhen, bNoDQS
78     );
79   }
80 }
81 
82 /*
83 ** Generate VM code to replace any double-quoted strings (but not double-quoted
84 ** identifiers) within the "sql" column of the sqlite_schema table in
85 ** database zDb with their single-quoted equivalents. If argument bTemp is
86 ** not true, similarly update all SQL statements in the sqlite_schema table
87 ** of the temp db.
88 */
89 static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
90   sqlite3NestedParse(pParse,
91       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
92       " SET sql = sqlite_rename_quotefix(%Q, sql)"
93       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
94       " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
95   );
96   if( bTemp==0 ){
97     sqlite3NestedParse(pParse,
98       "UPDATE temp." DFLT_SCHEMA_TABLE
99       " SET sql = sqlite_rename_quotefix('temp', sql)"
100       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
101       " AND sql NOT LIKE 'create virtual%%'"
102     );
103   }
104 }
105 
106 /*
107 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for
108 ** the temp database as well.
109 */
110 static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
111   Vdbe *v = pParse->pVdbe;
112   if( v ){
113     sqlite3ChangeCookie(pParse, iDb);
114     sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
115     if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
116   }
117 }
118 
119 /*
120 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
121 ** command.
122 */
123 void sqlite3AlterRenameTable(
124   Parse *pParse,            /* Parser context. */
125   SrcList *pSrc,            /* The table to rename. */
126   Token *pName              /* The new table name. */
127 ){
128   int iDb;                  /* Database that contains the table */
129   char *zDb;                /* Name of database iDb */
130   Table *pTab;              /* Table being renamed */
131   char *zName = 0;          /* NULL-terminated version of pName */
132   sqlite3 *db = pParse->db; /* Database connection */
133   int nTabName;             /* Number of UTF-8 characters in zTabName */
134   const char *zTabName;     /* Original name of the table */
135   Vdbe *v;
136   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
137   u32 savedDbFlags;         /* Saved value of db->mDbFlags */
138 
139   savedDbFlags = db->mDbFlags;
140   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
141   assert( pSrc->nSrc==1 );
142   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
143 
144   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
145   if( !pTab ) goto exit_rename_table;
146   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
147   zDb = db->aDb[iDb].zDbSName;
148   db->mDbFlags |= DBFLAG_PreferBuiltin;
149 
150   /* Get a NULL terminated version of the new table name. */
151   zName = sqlite3NameFromToken(db, pName);
152   if( !zName ) goto exit_rename_table;
153 
154   /* Check that a table or index named 'zName' does not already exist
155   ** in database iDb. If so, this is an error.
156   */
157   if( sqlite3FindTable(db, zName, zDb)
158    || sqlite3FindIndex(db, zName, zDb)
159    || sqlite3IsShadowTableOf(db, pTab, zName)
160   ){
161     sqlite3ErrorMsg(pParse,
162         "there is already another table or index with this name: %s", zName);
163     goto exit_rename_table;
164   }
165 
166   /* Make sure it is not a system table being altered, or a reserved name
167   ** that the table is being renamed to.
168   */
169   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
170     goto exit_rename_table;
171   }
172   if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
173     goto exit_rename_table;
174   }
175 
176 #ifndef SQLITE_OMIT_VIEW
177   if( pTab->pSelect ){
178     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
179     goto exit_rename_table;
180   }
181 #endif
182 
183 #ifndef SQLITE_OMIT_AUTHORIZATION
184   /* Invoke the authorization callback. */
185   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
186     goto exit_rename_table;
187   }
188 #endif
189 
190 #ifndef SQLITE_OMIT_VIRTUALTABLE
191   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
192     goto exit_rename_table;
193   }
194   if( IsVirtual(pTab) ){
195     pVTab = sqlite3GetVTable(db, pTab);
196     if( pVTab->pVtab->pModule->xRename==0 ){
197       pVTab = 0;
198     }
199   }
200 #endif
201 
202   /* Begin a transaction for database iDb. Then modify the schema cookie
203   ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
204   ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
205   ** nested SQL may raise an exception.  */
206   v = sqlite3GetVdbe(pParse);
207   if( v==0 ){
208     goto exit_rename_table;
209   }
210   sqlite3MayAbort(pParse);
211 
212   /* figure out how many UTF-8 characters are in zName */
213   zTabName = pTab->zName;
214   nTabName = sqlite3Utf8CharLen(zTabName, -1);
215 
216   /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
217   ** the schema to use the new table name.  */
218   sqlite3NestedParse(pParse,
219       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
220       "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
221       "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
222       "AND   name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
223       , zDb, zDb, zTabName, zName, (iDb==1), zTabName
224   );
225 
226   /* Update the tbl_name and name columns of the sqlite_schema table
227   ** as required.  */
228   sqlite3NestedParse(pParse,
229       "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
230           "tbl_name = %Q, "
231           "name = CASE "
232             "WHEN type='table' THEN %Q "
233             "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
234             "     AND type='index' THEN "
235              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
236             "ELSE name END "
237       "WHERE tbl_name=%Q COLLATE nocase AND "
238           "(type='table' OR type='index' OR type='trigger');",
239       zDb,
240       zName, zName, zName,
241       nTabName, zTabName
242   );
243 
244 #ifndef SQLITE_OMIT_AUTOINCREMENT
245   /* If the sqlite_sequence table exists in this database, then update
246   ** it with the new table name.
247   */
248   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
249     sqlite3NestedParse(pParse,
250         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
251         zDb, zName, pTab->zName);
252   }
253 #endif
254 
255   /* If the table being renamed is not itself part of the temp database,
256   ** edit view and trigger definitions within the temp database
257   ** as required.  */
258   if( iDb!=1 ){
259     sqlite3NestedParse(pParse,
260         "UPDATE sqlite_temp_schema SET "
261             "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
262             "tbl_name = "
263               "CASE WHEN tbl_name=%Q COLLATE nocase AND "
264               "  sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
265               "THEN %Q ELSE tbl_name END "
266             "WHERE type IN ('view', 'trigger')"
267         , zDb, zTabName, zName, zTabName, zDb, zName);
268   }
269 
270   /* If this is a virtual table, invoke the xRename() function if
271   ** one is defined. The xRename() callback will modify the names
272   ** of any resources used by the v-table implementation (including other
273   ** SQLite tables) that are identified by the name of the virtual table.
274   */
275 #ifndef SQLITE_OMIT_VIRTUALTABLE
276   if( pVTab ){
277     int i = ++pParse->nMem;
278     sqlite3VdbeLoadString(v, i, zName);
279     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
280   }
281 #endif
282 
283   renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
284   renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
285 
286 exit_rename_table:
287   sqlite3SrcListDelete(db, pSrc);
288   sqlite3DbFree(db, zName);
289   db->mDbFlags = savedDbFlags;
290 }
291 
292 /*
293 ** Write code that will raise an error if the table described by
294 ** zDb and zTab is not empty.
295 */
296 static void sqlite3ErrorIfNotEmpty(
297   Parse *pParse,        /* Parsing context */
298   const char *zDb,      /* Schema holding the table */
299   const char *zTab,     /* Table to check for empty */
300   const char *zErr      /* Error message text */
301 ){
302   sqlite3NestedParse(pParse,
303      "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
304      zErr, zDb, zTab
305   );
306 }
307 
308 /*
309 ** This function is called after an "ALTER TABLE ... ADD" statement
310 ** has been parsed. Argument pColDef contains the text of the new
311 ** column definition.
312 **
313 ** The Table structure pParse->pNewTable was extended to include
314 ** the new column during parsing.
315 */
316 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
317   Table *pNew;              /* Copy of pParse->pNewTable */
318   Table *pTab;              /* Table being altered */
319   int iDb;                  /* Database number */
320   const char *zDb;          /* Database name */
321   const char *zTab;         /* Table name */
322   char *zCol;               /* Null-terminated column definition */
323   Column *pCol;             /* The new column */
324   Expr *pDflt;              /* Default value for the new column */
325   sqlite3 *db;              /* The database connection; */
326   Vdbe *v;                  /* The prepared statement under construction */
327   int r1;                   /* Temporary registers */
328 
329   db = pParse->db;
330   if( pParse->nErr || db->mallocFailed ) return;
331   pNew = pParse->pNewTable;
332   assert( pNew );
333 
334   assert( sqlite3BtreeHoldsAllMutexes(db) );
335   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
336   zDb = db->aDb[iDb].zDbSName;
337   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
338   pCol = &pNew->aCol[pNew->nCol-1];
339   pDflt = pCol->pDflt;
340   pTab = sqlite3FindTable(db, zTab, zDb);
341   assert( pTab );
342 
343 #ifndef SQLITE_OMIT_AUTHORIZATION
344   /* Invoke the authorization callback. */
345   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
346     return;
347   }
348 #endif
349 
350 
351   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
352   ** If there is a NOT NULL constraint, then the default value for the
353   ** column must not be NULL.
354   */
355   if( pCol->colFlags & COLFLAG_PRIMKEY ){
356     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
357     return;
358   }
359   if( pNew->pIndex ){
360     sqlite3ErrorMsg(pParse,
361          "Cannot add a UNIQUE column");
362     return;
363   }
364   if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
365     /* If the default value for the new column was specified with a
366     ** literal NULL, then set pDflt to 0. This simplifies checking
367     ** for an SQL NULL default below.
368     */
369     assert( pDflt==0 || pDflt->op==TK_SPAN );
370     if( pDflt && pDflt->pLeft->op==TK_NULL ){
371       pDflt = 0;
372     }
373     if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
374       sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
375           "Cannot add a REFERENCES column with non-NULL default value");
376     }
377     if( pCol->notNull && !pDflt ){
378       sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
379           "Cannot add a NOT NULL column with default value NULL");
380     }
381 
382 
383     /* Ensure the default expression is something that sqlite3ValueFromExpr()
384     ** can handle (i.e. not CURRENT_TIME etc.)
385     */
386     if( pDflt ){
387       sqlite3_value *pVal = 0;
388       int rc;
389       rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
390       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
391       if( rc!=SQLITE_OK ){
392         assert( db->mallocFailed == 1 );
393         return;
394       }
395       if( !pVal ){
396         sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
397            "Cannot add a column with non-constant default");
398       }
399       sqlite3ValueFree(pVal);
400     }
401   }else if( pCol->colFlags & COLFLAG_STORED ){
402     sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
403   }
404 
405 
406   /* Modify the CREATE TABLE statement. */
407   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
408   if( zCol ){
409     char *zEnd = &zCol[pColDef->n-1];
410     u32 savedDbFlags = db->mDbFlags;
411     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
412       *zEnd-- = '\0';
413     }
414     db->mDbFlags |= DBFLAG_PreferBuiltin;
415     /* substr() operations on characters, but addColOffset is in bytes. So we
416     ** have to use printf() to translate between these units: */
417     sqlite3NestedParse(pParse,
418         "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
419           "sql = printf('%%.%ds, ',sql) || %Q"
420           " || substr(sql,1+length(printf('%%.%ds',sql))) "
421         "WHERE type = 'table' AND name = %Q",
422       zDb, pNew->addColOffset, zCol, pNew->addColOffset,
423       zTab
424     );
425     sqlite3DbFree(db, zCol);
426     db->mDbFlags = savedDbFlags;
427   }
428 
429   /* Make sure the schema version is at least 3.  But do not upgrade
430   ** from less than 3 to 4, as that will corrupt any preexisting DESC
431   ** index.
432   */
433   v = sqlite3GetVdbe(pParse);
434   if( v ){
435     r1 = sqlite3GetTempReg(pParse);
436     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
437     sqlite3VdbeUsesBtree(v, iDb);
438     sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
439     sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
440     VdbeCoverage(v);
441     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
442     sqlite3ReleaseTempReg(pParse, r1);
443   }
444 
445   /* Reload the table definition */
446   renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
447 }
448 
449 /*
450 ** This function is called by the parser after the table-name in
451 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
452 ** pSrc is the full-name of the table being altered.
453 **
454 ** This routine makes a (partial) copy of the Table structure
455 ** for the table being altered and sets Parse.pNewTable to point
456 ** to it. Routines called by the parser as the column definition
457 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
458 ** the copy. The copy of the Table structure is deleted by tokenize.c
459 ** after parsing is finished.
460 **
461 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
462 ** coding the "ALTER TABLE ... ADD" statement.
463 */
464 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
465   Table *pNew;
466   Table *pTab;
467   int iDb;
468   int i;
469   int nAlloc;
470   sqlite3 *db = pParse->db;
471 
472   /* Look up the table being altered. */
473   assert( pParse->pNewTable==0 );
474   assert( sqlite3BtreeHoldsAllMutexes(db) );
475   if( db->mallocFailed ) goto exit_begin_add_column;
476   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
477   if( !pTab ) goto exit_begin_add_column;
478 
479 #ifndef SQLITE_OMIT_VIRTUALTABLE
480   if( IsVirtual(pTab) ){
481     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
482     goto exit_begin_add_column;
483   }
484 #endif
485 
486   /* Make sure this is not an attempt to ALTER a view. */
487   if( pTab->pSelect ){
488     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
489     goto exit_begin_add_column;
490   }
491   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
492     goto exit_begin_add_column;
493   }
494 
495   sqlite3MayAbort(pParse);
496   assert( pTab->addColOffset>0 );
497   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
498 
499   /* Put a copy of the Table struct in Parse.pNewTable for the
500   ** sqlite3AddColumn() function and friends to modify.  But modify
501   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
502   ** prefix, we insure that the name will not collide with an existing
503   ** table because user table are not allowed to have the "sqlite_"
504   ** prefix on their name.
505   */
506   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
507   if( !pNew ) goto exit_begin_add_column;
508   pParse->pNewTable = pNew;
509   pNew->nTabRef = 1;
510   pNew->nCol = pTab->nCol;
511   assert( pNew->nCol>0 );
512   nAlloc = (((pNew->nCol-1)/8)*8)+8;
513   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
514   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
515   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
516   if( !pNew->aCol || !pNew->zName ){
517     assert( db->mallocFailed );
518     goto exit_begin_add_column;
519   }
520   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
521   for(i=0; i<pNew->nCol; i++){
522     Column *pCol = &pNew->aCol[i];
523     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
524     pCol->hName = sqlite3StrIHash(pCol->zName);
525     pCol->zColl = 0;
526     pCol->pDflt = 0;
527   }
528   pNew->pSchema = db->aDb[iDb].pSchema;
529   pNew->addColOffset = pTab->addColOffset;
530   pNew->nTabRef = 1;
531 
532 exit_begin_add_column:
533   sqlite3SrcListDelete(db, pSrc);
534   return;
535 }
536 
537 /*
538 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
539 ** command. This function checks if the table is a view or virtual
540 ** table (columns of views or virtual tables may not be renamed). If so,
541 ** it loads an error message into pParse and returns non-zero.
542 **
543 ** Or, if pTab is not a view or virtual table, zero is returned.
544 */
545 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
546 static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
547   const char *zType = 0;
548 #ifndef SQLITE_OMIT_VIEW
549   if( pTab->pSelect ){
550     zType = "view";
551   }
552 #endif
553 #ifndef SQLITE_OMIT_VIRTUALTABLE
554   if( IsVirtual(pTab) ){
555     zType = "virtual table";
556   }
557 #endif
558   if( zType ){
559     sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
560         (bDrop ? "drop column from" : "rename columns of"),
561         zType, pTab->zName
562     );
563     return 1;
564   }
565   return 0;
566 }
567 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
568 # define isRealTable(x,y,z) (0)
569 #endif
570 
571 /*
572 ** Handles the following parser reduction:
573 **
574 **  cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
575 */
576 void sqlite3AlterRenameColumn(
577   Parse *pParse,                  /* Parsing context */
578   SrcList *pSrc,                  /* Table being altered.  pSrc->nSrc==1 */
579   Token *pOld,                    /* Name of column being changed */
580   Token *pNew                     /* New column name */
581 ){
582   sqlite3 *db = pParse->db;       /* Database connection */
583   Table *pTab;                    /* Table being updated */
584   int iCol;                       /* Index of column being renamed */
585   char *zOld = 0;                 /* Old column name */
586   char *zNew = 0;                 /* New column name */
587   const char *zDb;                /* Name of schema containing the table */
588   int iSchema;                    /* Index of the schema */
589   int bQuote;                     /* True to quote the new name */
590 
591   /* Locate the table to be altered */
592   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
593   if( !pTab ) goto exit_rename_column;
594 
595   /* Cannot alter a system table */
596   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
597   if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
598 
599   /* Which schema holds the table to be altered */
600   iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
601   assert( iSchema>=0 );
602   zDb = db->aDb[iSchema].zDbSName;
603 
604 #ifndef SQLITE_OMIT_AUTHORIZATION
605   /* Invoke the authorization callback. */
606   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
607     goto exit_rename_column;
608   }
609 #endif
610 
611   /* Make sure the old name really is a column name in the table to be
612   ** altered.  Set iCol to be the index of the column being renamed */
613   zOld = sqlite3NameFromToken(db, pOld);
614   if( !zOld ) goto exit_rename_column;
615   for(iCol=0; iCol<pTab->nCol; iCol++){
616     if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
617   }
618   if( iCol==pTab->nCol ){
619     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
620     goto exit_rename_column;
621   }
622 
623   /* Ensure the schema contains no double-quoted strings */
624   renameTestSchema(pParse, zDb, iSchema==1, "", 0);
625   renameFixQuotes(pParse, zDb, iSchema==1);
626 
627   /* Do the rename operation using a recursive UPDATE statement that
628   ** uses the sqlite_rename_column() SQL function to compute the new
629   ** CREATE statement text for the sqlite_schema table.
630   */
631   sqlite3MayAbort(pParse);
632   zNew = sqlite3NameFromToken(db, pNew);
633   if( !zNew ) goto exit_rename_column;
634   assert( pNew->n>0 );
635   bQuote = sqlite3Isquote(pNew->z[0]);
636   sqlite3NestedParse(pParse,
637       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
638       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
639       "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
640       " AND (type != 'index' OR tbl_name = %Q)"
641       " AND sql NOT LIKE 'create virtual%%'",
642       zDb,
643       zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
644       pTab->zName
645   );
646 
647   sqlite3NestedParse(pParse,
648       "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
649       "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
650       "WHERE type IN ('trigger', 'view')",
651       zDb, pTab->zName, iCol, zNew, bQuote
652   );
653 
654   /* Drop and reload the database schema. */
655   renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
656   renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
657 
658  exit_rename_column:
659   sqlite3SrcListDelete(db, pSrc);
660   sqlite3DbFree(db, zOld);
661   sqlite3DbFree(db, zNew);
662   return;
663 }
664 
665 /*
666 ** Each RenameToken object maps an element of the parse tree into
667 ** the token that generated that element.  The parse tree element
668 ** might be one of:
669 **
670 **     *  A pointer to an Expr that represents an ID
671 **     *  The name of a table column in Column.zName
672 **
673 ** A list of RenameToken objects can be constructed during parsing.
674 ** Each new object is created by sqlite3RenameTokenMap().
675 ** As the parse tree is transformed, the sqlite3RenameTokenRemap()
676 ** routine is used to keep the mapping current.
677 **
678 ** After the parse finishes, renameTokenFind() routine can be used
679 ** to look up the actual token value that created some element in
680 ** the parse tree.
681 */
682 struct RenameToken {
683   void *p;               /* Parse tree element created by token t */
684   Token t;               /* The token that created parse tree element p */
685   RenameToken *pNext;    /* Next is a list of all RenameToken objects */
686 };
687 
688 /*
689 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
690 ** down into the Walker.
691 */
692 typedef struct RenameCtx RenameCtx;
693 struct RenameCtx {
694   RenameToken *pList;             /* List of tokens to overwrite */
695   int nList;                      /* Number of tokens in pList */
696   int iCol;                       /* Index of column being renamed */
697   Table *pTab;                    /* Table being ALTERed */
698   const char *zOld;               /* Old column name */
699 };
700 
701 #ifdef SQLITE_DEBUG
702 /*
703 ** This function is only for debugging. It performs two tasks:
704 **
705 **   1. Checks that pointer pPtr does not already appear in the
706 **      rename-token list.
707 **
708 **   2. Dereferences each pointer in the rename-token list.
709 **
710 ** The second is most effective when debugging under valgrind or
711 ** address-sanitizer or similar. If any of these pointers no longer
712 ** point to valid objects, an exception is raised by the memory-checking
713 ** tool.
714 **
715 ** The point of this is to prevent comparisons of invalid pointer values.
716 ** Even though this always seems to work, it is undefined according to the
717 ** C standard. Example of undefined comparison:
718 **
719 **     sqlite3_free(x);
720 **     if( x==y ) ...
721 **
722 ** Technically, as x no longer points into a valid object or to the byte
723 ** following a valid object, it may not be used in comparison operations.
724 */
725 static void renameTokenCheckAll(Parse *pParse, void *pPtr){
726   if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
727     RenameToken *p;
728     u8 i = 0;
729     for(p=pParse->pRename; p; p=p->pNext){
730       if( p->p ){
731         assert( p->p!=pPtr );
732         i += *(u8*)(p->p);
733       }
734     }
735   }
736 }
737 #else
738 # define renameTokenCheckAll(x,y)
739 #endif
740 
741 /*
742 ** Remember that the parser tree element pPtr was created using
743 ** the token pToken.
744 **
745 ** In other words, construct a new RenameToken object and add it
746 ** to the list of RenameToken objects currently being built up
747 ** in pParse->pRename.
748 **
749 ** The pPtr argument is returned so that this routine can be used
750 ** with tail recursion in tokenExpr() routine, for a small performance
751 ** improvement.
752 */
753 void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
754   RenameToken *pNew;
755   assert( pPtr || pParse->db->mallocFailed );
756   renameTokenCheckAll(pParse, pPtr);
757   if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
758     pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
759     if( pNew ){
760       pNew->p = pPtr;
761       pNew->t = *pToken;
762       pNew->pNext = pParse->pRename;
763       pParse->pRename = pNew;
764     }
765   }
766 
767   return pPtr;
768 }
769 
770 /*
771 ** It is assumed that there is already a RenameToken object associated
772 ** with parse tree element pFrom. This function remaps the associated token
773 ** to parse tree element pTo.
774 */
775 void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
776   RenameToken *p;
777   renameTokenCheckAll(pParse, pTo);
778   for(p=pParse->pRename; p; p=p->pNext){
779     if( p->p==pFrom ){
780       p->p = pTo;
781       break;
782     }
783   }
784 }
785 
786 /*
787 ** Walker callback used by sqlite3RenameExprUnmap().
788 */
789 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
790   Parse *pParse = pWalker->pParse;
791   sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
792   return WRC_Continue;
793 }
794 
795 /*
796 ** Iterate through the Select objects that are part of WITH clauses attached
797 ** to select statement pSelect.
798 */
799 static void renameWalkWith(Walker *pWalker, Select *pSelect){
800   With *pWith = pSelect->pWith;
801   if( pWith ){
802     int i;
803     for(i=0; i<pWith->nCte; i++){
804       Select *p = pWith->a[i].pSelect;
805       NameContext sNC;
806       memset(&sNC, 0, sizeof(sNC));
807       sNC.pParse = pWalker->pParse;
808       sqlite3SelectPrep(sNC.pParse, p, &sNC);
809       sqlite3WalkSelect(pWalker, p);
810       sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
811     }
812   }
813 }
814 
815 /*
816 ** Unmap all tokens in the IdList object passed as the second argument.
817 */
818 static void unmapColumnIdlistNames(
819   Parse *pParse,
820   IdList *pIdList
821 ){
822   if( pIdList ){
823     int ii;
824     for(ii=0; ii<pIdList->nId; ii++){
825       sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
826     }
827   }
828 }
829 
830 /*
831 ** Walker callback used by sqlite3RenameExprUnmap().
832 */
833 static int renameUnmapSelectCb(Walker *pWalker, Select *p){
834   Parse *pParse = pWalker->pParse;
835   int i;
836   if( pParse->nErr ) return WRC_Abort;
837   if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
838   if( ALWAYS(p->pEList) ){
839     ExprList *pList = p->pEList;
840     for(i=0; i<pList->nExpr; i++){
841       if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
842         sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
843       }
844     }
845   }
846   if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */
847     SrcList *pSrc = p->pSrc;
848     for(i=0; i<pSrc->nSrc; i++){
849       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
850       if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
851       unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
852     }
853   }
854 
855   renameWalkWith(pWalker, p);
856   return WRC_Continue;
857 }
858 
859 /*
860 ** Remove all nodes that are part of expression pExpr from the rename list.
861 */
862 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
863   u8 eMode = pParse->eParseMode;
864   Walker sWalker;
865   memset(&sWalker, 0, sizeof(Walker));
866   sWalker.pParse = pParse;
867   sWalker.xExprCallback = renameUnmapExprCb;
868   sWalker.xSelectCallback = renameUnmapSelectCb;
869   pParse->eParseMode = PARSE_MODE_UNMAP;
870   sqlite3WalkExpr(&sWalker, pExpr);
871   pParse->eParseMode = eMode;
872 }
873 
874 /*
875 ** Remove all nodes that are part of expression-list pEList from the
876 ** rename list.
877 */
878 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
879   if( pEList ){
880     int i;
881     Walker sWalker;
882     memset(&sWalker, 0, sizeof(Walker));
883     sWalker.pParse = pParse;
884     sWalker.xExprCallback = renameUnmapExprCb;
885     sqlite3WalkExprList(&sWalker, pEList);
886     for(i=0; i<pEList->nExpr; i++){
887       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
888         sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
889       }
890     }
891   }
892 }
893 
894 /*
895 ** Free the list of RenameToken objects given in the second argument
896 */
897 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
898   RenameToken *pNext;
899   RenameToken *p;
900   for(p=pToken; p; p=pNext){
901     pNext = p->pNext;
902     sqlite3DbFree(db, p);
903   }
904 }
905 
906 /*
907 ** Search the Parse object passed as the first argument for a RenameToken
908 ** object associated with parse tree element pPtr. If found, return a pointer
909 ** to it. Otherwise, return NULL.
910 **
911 ** If the second argument passed to this function is not NULL and a matching
912 ** RenameToken object is found, remove it from the Parse object and add it to
913 ** the list maintained by the RenameCtx object.
914 */
915 static RenameToken *renameTokenFind(
916   Parse *pParse,
917   struct RenameCtx *pCtx,
918   void *pPtr
919 ){
920   RenameToken **pp;
921   assert( pPtr!=0 );
922   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
923     if( (*pp)->p==pPtr ){
924       RenameToken *pToken = *pp;
925       if( pCtx ){
926         *pp = pToken->pNext;
927         pToken->pNext = pCtx->pList;
928         pCtx->pList = pToken;
929         pCtx->nList++;
930       }
931       return pToken;
932     }
933   }
934   return 0;
935 }
936 
937 /*
938 ** This is a Walker select callback. It does nothing. It is only required
939 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
940 ** descend into sub-select statements.
941 */
942 static int renameColumnSelectCb(Walker *pWalker, Select *p){
943   if( p->selFlags & SF_View ) return WRC_Prune;
944   renameWalkWith(pWalker, p);
945   return WRC_Continue;
946 }
947 
948 /*
949 ** This is a Walker expression callback.
950 **
951 ** For every TK_COLUMN node in the expression tree, search to see
952 ** if the column being references is the column being renamed by an
953 ** ALTER TABLE statement.  If it is, then attach its associated
954 ** RenameToken object to the list of RenameToken objects being
955 ** constructed in RenameCtx object at pWalker->u.pRename.
956 */
957 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
958   RenameCtx *p = pWalker->u.pRename;
959   if( pExpr->op==TK_TRIGGER
960    && pExpr->iColumn==p->iCol
961    && pWalker->pParse->pTriggerTab==p->pTab
962   ){
963     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
964   }else if( pExpr->op==TK_COLUMN
965    && pExpr->iColumn==p->iCol
966    && p->pTab==pExpr->y.pTab
967   ){
968     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
969   }
970   return WRC_Continue;
971 }
972 
973 /*
974 ** The RenameCtx contains a list of tokens that reference a column that
975 ** is being renamed by an ALTER TABLE statement.  Return the "last"
976 ** RenameToken in the RenameCtx and remove that RenameToken from the
977 ** RenameContext.  "Last" means the last RenameToken encountered when
978 ** the input SQL is parsed from left to right.  Repeated calls to this routine
979 ** return all column name tokens in the order that they are encountered
980 ** in the SQL statement.
981 */
982 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
983   RenameToken *pBest = pCtx->pList;
984   RenameToken *pToken;
985   RenameToken **pp;
986 
987   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
988     if( pToken->t.z>pBest->t.z ) pBest = pToken;
989   }
990   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
991   *pp = pBest->pNext;
992 
993   return pBest;
994 }
995 
996 /*
997 ** An error occured while parsing or otherwise processing a database
998 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
999 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1000 ** sub-routine is currently stored in pParse->zErrMsg. This function
1001 ** adds context to the error message and then stores it in pCtx.
1002 */
1003 static void renameColumnParseError(
1004   sqlite3_context *pCtx,
1005   const char *zWhen,
1006   sqlite3_value *pType,
1007   sqlite3_value *pObject,
1008   Parse *pParse
1009 ){
1010   const char *zT = (const char*)sqlite3_value_text(pType);
1011   const char *zN = (const char*)sqlite3_value_text(pObject);
1012   char *zErr;
1013 
1014   zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1015       zT, zN, (zWhen[0] ? " " : ""), zWhen,
1016       pParse->zErrMsg
1017   );
1018   sqlite3_result_error(pCtx, zErr, -1);
1019   sqlite3_free(zErr);
1020 }
1021 
1022 /*
1023 ** For each name in the the expression-list pEList (i.e. each
1024 ** pEList->a[i].zName) that matches the string in zOld, extract the
1025 ** corresponding rename-token from Parse object pParse and add it
1026 ** to the RenameCtx pCtx.
1027 */
1028 static void renameColumnElistNames(
1029   Parse *pParse,
1030   RenameCtx *pCtx,
1031   ExprList *pEList,
1032   const char *zOld
1033 ){
1034   if( pEList ){
1035     int i;
1036     for(i=0; i<pEList->nExpr; i++){
1037       char *zName = pEList->a[i].zEName;
1038       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1039        && ALWAYS(zName!=0)
1040        && 0==sqlite3_stricmp(zName, zOld)
1041       ){
1042         renameTokenFind(pParse, pCtx, (void*)zName);
1043       }
1044     }
1045   }
1046 }
1047 
1048 /*
1049 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1050 ** that matches the string in zOld, extract the corresponding rename-token
1051 ** from Parse object pParse and add it to the RenameCtx pCtx.
1052 */
1053 static void renameColumnIdlistNames(
1054   Parse *pParse,
1055   RenameCtx *pCtx,
1056   IdList *pIdList,
1057   const char *zOld
1058 ){
1059   if( pIdList ){
1060     int i;
1061     for(i=0; i<pIdList->nId; i++){
1062       char *zName = pIdList->a[i].zName;
1063       if( 0==sqlite3_stricmp(zName, zOld) ){
1064         renameTokenFind(pParse, pCtx, (void*)zName);
1065       }
1066     }
1067   }
1068 }
1069 
1070 
1071 /*
1072 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
1073 ** is initialized by this function before it is used.
1074 */
1075 static int renameParseSql(
1076   Parse *p,                       /* Memory to use for Parse object */
1077   const char *zDb,                /* Name of schema SQL belongs to */
1078   sqlite3 *db,                    /* Database handle */
1079   const char *zSql,               /* SQL to parse */
1080   int bTemp                       /* True if SQL is from temp schema */
1081 ){
1082   int rc;
1083   char *zErr = 0;
1084 
1085   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1086 
1087   /* Parse the SQL statement passed as the first argument. If no error
1088   ** occurs and the parse does not result in a new table, index or
1089   ** trigger object, the database must be corrupt. */
1090   memset(p, 0, sizeof(Parse));
1091   p->eParseMode = PARSE_MODE_RENAME;
1092   p->db = db;
1093   p->nQueryLoop = 1;
1094   rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
1095   assert( p->zErrMsg==0 );
1096   assert( rc!=SQLITE_OK || zErr==0 );
1097   p->zErrMsg = zErr;
1098   if( db->mallocFailed ) rc = SQLITE_NOMEM;
1099   if( rc==SQLITE_OK
1100    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1101   ){
1102     rc = SQLITE_CORRUPT_BKPT;
1103   }
1104 
1105 #ifdef SQLITE_DEBUG
1106   /* Ensure that all mappings in the Parse.pRename list really do map to
1107   ** a part of the input string.  */
1108   if( rc==SQLITE_OK ){
1109     int nSql = sqlite3Strlen30(zSql);
1110     RenameToken *pToken;
1111     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1112       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1113     }
1114   }
1115 #endif
1116 
1117   db->init.iDb = 0;
1118   return rc;
1119 }
1120 
1121 /*
1122 ** This function edits SQL statement zSql, replacing each token identified
1123 ** by the linked list pRename with the text of zNew. If argument bQuote is
1124 ** true, then zNew is always quoted first. If no error occurs, the result
1125 ** is loaded into context object pCtx as the result.
1126 **
1127 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1128 ** pCtx and an SQLite error code returned.
1129 */
1130 static int renameEditSql(
1131   sqlite3_context *pCtx,          /* Return result here */
1132   RenameCtx *pRename,             /* Rename context */
1133   const char *zSql,               /* SQL statement to edit */
1134   const char *zNew,               /* New token text */
1135   int bQuote                      /* True to always quote token */
1136 ){
1137   int nNew = sqlite3Strlen30(zNew);
1138   int nSql = sqlite3Strlen30(zSql);
1139   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1140   int rc = SQLITE_OK;
1141   char *zQuot = 0;
1142   char *zOut;
1143   int nQuot = 0;
1144   char *zBuf1 = 0;
1145   char *zBuf2 = 0;
1146 
1147   if( zNew ){
1148     /* Set zQuot to point to a buffer containing a quoted copy of the
1149     ** identifier zNew. If the corresponding identifier in the original
1150     ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1151     ** point to zQuot so that all substitutions are made using the
1152     ** quoted version of the new column name.  */
1153     zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
1154     if( zQuot==0 ){
1155       return SQLITE_NOMEM;
1156     }else{
1157       nQuot = sqlite3Strlen30(zQuot)-1;
1158     }
1159 
1160     assert( nQuot>=nNew );
1161     zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1162   }else{
1163     zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1164     if( zOut ){
1165       zBuf1 = &zOut[nSql*2+1];
1166       zBuf2 = &zOut[nSql*4+2];
1167     }
1168   }
1169 
1170   /* At this point pRename->pList contains a list of RenameToken objects
1171   ** corresponding to all tokens in the input SQL that must be replaced
1172   ** with the new column name, or with single-quoted versions of themselves.
1173   ** All that remains is to construct and return the edited SQL string. */
1174   if( zOut ){
1175     int nOut = nSql;
1176     memcpy(zOut, zSql, nSql);
1177     while( pRename->pList ){
1178       int iOff;                   /* Offset of token to replace in zOut */
1179       u32 nReplace;
1180       const char *zReplace;
1181       RenameToken *pBest = renameColumnTokenNext(pRename);
1182 
1183       if( zNew ){
1184         if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
1185           nReplace = nNew;
1186           zReplace = zNew;
1187         }else{
1188           nReplace = nQuot;
1189           zReplace = zQuot;
1190           if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
1191         }
1192       }else{
1193         /* Dequote the double-quoted token. Then requote it again, this time
1194         ** using single quotes. If the character immediately following the
1195         ** original token within the input SQL was a single quote ('), then
1196         ** add another space after the new, single-quoted version of the
1197         ** token. This is so that (SELECT "string"'alias') maps to
1198         ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias').  */
1199         memcpy(zBuf1, pBest->t.z, pBest->t.n);
1200         zBuf1[pBest->t.n] = 0;
1201         sqlite3Dequote(zBuf1);
1202         sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1203             pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1204         );
1205         zReplace = zBuf2;
1206         nReplace = sqlite3Strlen30(zReplace);
1207       }
1208 
1209       iOff = pBest->t.z - zSql;
1210       if( pBest->t.n!=nReplace ){
1211         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1212             nOut - (iOff + pBest->t.n)
1213         );
1214         nOut += nReplace - pBest->t.n;
1215         zOut[nOut] = '\0';
1216       }
1217       memcpy(&zOut[iOff], zReplace, nReplace);
1218       sqlite3DbFree(db, pBest);
1219     }
1220 
1221     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1222     sqlite3DbFree(db, zOut);
1223   }else{
1224     rc = SQLITE_NOMEM;
1225   }
1226 
1227   sqlite3_free(zQuot);
1228   return rc;
1229 }
1230 
1231 /*
1232 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1233 ** it was read from the schema of database zDb. Return SQLITE_OK if
1234 ** successful. Otherwise, return an SQLite error code and leave an error
1235 ** message in the Parse object.
1236 */
1237 static int renameResolveTrigger(Parse *pParse){
1238   sqlite3 *db = pParse->db;
1239   Trigger *pNew = pParse->pNewTrigger;
1240   TriggerStep *pStep;
1241   NameContext sNC;
1242   int rc = SQLITE_OK;
1243 
1244   memset(&sNC, 0, sizeof(sNC));
1245   sNC.pParse = pParse;
1246   assert( pNew->pTabSchema );
1247   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1248       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1249   );
1250   pParse->eTriggerOp = pNew->op;
1251   /* ALWAYS() because if the table of the trigger does not exist, the
1252   ** error would have been hit before this point */
1253   if( ALWAYS(pParse->pTriggerTab) ){
1254     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1255   }
1256 
1257   /* Resolve symbols in WHEN clause */
1258   if( rc==SQLITE_OK && pNew->pWhen ){
1259     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1260   }
1261 
1262   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1263     if( pStep->pSelect ){
1264       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1265       if( pParse->nErr ) rc = pParse->rc;
1266     }
1267     if( rc==SQLITE_OK && pStep->zTarget ){
1268       SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1269       if( pSrc ){
1270         int i;
1271         for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
1272           SrcItem *p = &pSrc->a[i];
1273           p->iCursor = pParse->nTab++;
1274           if( p->pSelect ){
1275             sqlite3SelectPrep(pParse, p->pSelect, 0);
1276             sqlite3ExpandSubquery(pParse, p);
1277             assert( i>0 );
1278             assert( pStep->pFrom->a[i-1].pSelect );
1279             sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
1280           }else{
1281             p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1282             if( p->pTab==0 ){
1283               rc = SQLITE_ERROR;
1284             }else{
1285               p->pTab->nTabRef++;
1286               rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1287             }
1288           }
1289         }
1290         sNC.pSrcList = pSrc;
1291         if( rc==SQLITE_OK && pStep->pWhere ){
1292           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1293         }
1294         if( rc==SQLITE_OK ){
1295           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1296         }
1297         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1298         if( pStep->pUpsert && rc==SQLITE_OK ){
1299           Upsert *pUpsert = pStep->pUpsert;
1300           pUpsert->pUpsertSrc = pSrc;
1301           sNC.uNC.pUpsert = pUpsert;
1302           sNC.ncFlags = NC_UUpsert;
1303           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1304           if( rc==SQLITE_OK ){
1305             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1306             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1307           }
1308           if( rc==SQLITE_OK ){
1309             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1310           }
1311           if( rc==SQLITE_OK ){
1312             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1313           }
1314           sNC.ncFlags = 0;
1315         }
1316         sNC.pSrcList = 0;
1317         sqlite3SrcListDelete(db, pSrc);
1318       }else{
1319         rc = SQLITE_NOMEM;
1320       }
1321     }
1322   }
1323   return rc;
1324 }
1325 
1326 /*
1327 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1328 ** objects that are part of the trigger passed as the second argument.
1329 */
1330 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1331   TriggerStep *pStep;
1332 
1333   /* Find tokens to edit in WHEN clause */
1334   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1335 
1336   /* Find tokens to edit in trigger steps */
1337   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1338     sqlite3WalkSelect(pWalker, pStep->pSelect);
1339     sqlite3WalkExpr(pWalker, pStep->pWhere);
1340     sqlite3WalkExprList(pWalker, pStep->pExprList);
1341     if( pStep->pUpsert ){
1342       Upsert *pUpsert = pStep->pUpsert;
1343       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1344       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1345       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1346       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1347     }
1348     if( pStep->pFrom ){
1349       int i;
1350       for(i=0; i<pStep->pFrom->nSrc; i++){
1351         sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1352       }
1353     }
1354   }
1355 }
1356 
1357 /*
1358 ** Free the contents of Parse object (*pParse). Do not free the memory
1359 ** occupied by the Parse object itself.
1360 */
1361 static void renameParseCleanup(Parse *pParse){
1362   sqlite3 *db = pParse->db;
1363   Index *pIdx;
1364   if( pParse->pVdbe ){
1365     sqlite3VdbeFinalize(pParse->pVdbe);
1366   }
1367   sqlite3DeleteTable(db, pParse->pNewTable);
1368   while( (pIdx = pParse->pNewIndex)!=0 ){
1369     pParse->pNewIndex = pIdx->pNext;
1370     sqlite3FreeIndex(db, pIdx);
1371   }
1372   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1373   sqlite3DbFree(db, pParse->zErrMsg);
1374   renameTokenFree(db, pParse->pRename);
1375   sqlite3ParserReset(pParse);
1376 }
1377 
1378 /*
1379 ** SQL function:
1380 **
1381 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1382 **
1383 **   0. zSql:     SQL statement to rewrite
1384 **   1. type:     Type of object ("table", "view" etc.)
1385 **   2. object:   Name of object
1386 **   3. Database: Database name (e.g. "main")
1387 **   4. Table:    Table name
1388 **   5. iCol:     Index of column to rename
1389 **   6. zNew:     New column name
1390 **   7. bQuote:   Non-zero if the new column name should be quoted.
1391 **   8. bTemp:    True if zSql comes from temp schema
1392 **
1393 ** Do a column rename operation on the CREATE statement given in zSql.
1394 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1395 ** into zNew.  The name should be quoted if bQuote is true.
1396 **
1397 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1398 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1399 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1400 */
1401 static void renameColumnFunc(
1402   sqlite3_context *context,
1403   int NotUsed,
1404   sqlite3_value **argv
1405 ){
1406   sqlite3 *db = sqlite3_context_db_handle(context);
1407   RenameCtx sCtx;
1408   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1409   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1410   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1411   int iCol = sqlite3_value_int(argv[5]);
1412   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1413   int bQuote = sqlite3_value_int(argv[7]);
1414   int bTemp = sqlite3_value_int(argv[8]);
1415   const char *zOld;
1416   int rc;
1417   Parse sParse;
1418   Walker sWalker;
1419   Index *pIdx;
1420   int i;
1421   Table *pTab;
1422 #ifndef SQLITE_OMIT_AUTHORIZATION
1423   sqlite3_xauth xAuth = db->xAuth;
1424 #endif
1425 
1426   UNUSED_PARAMETER(NotUsed);
1427   if( zSql==0 ) return;
1428   if( zTable==0 ) return;
1429   if( zNew==0 ) return;
1430   if( iCol<0 ) return;
1431   sqlite3BtreeEnterAll(db);
1432   pTab = sqlite3FindTable(db, zTable, zDb);
1433   if( pTab==0 || iCol>=pTab->nCol ){
1434     sqlite3BtreeLeaveAll(db);
1435     return;
1436   }
1437   zOld = pTab->aCol[iCol].zName;
1438   memset(&sCtx, 0, sizeof(sCtx));
1439   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1440 
1441 #ifndef SQLITE_OMIT_AUTHORIZATION
1442   db->xAuth = 0;
1443 #endif
1444   rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
1445 
1446   /* Find tokens that need to be replaced. */
1447   memset(&sWalker, 0, sizeof(Walker));
1448   sWalker.pParse = &sParse;
1449   sWalker.xExprCallback = renameColumnExprCb;
1450   sWalker.xSelectCallback = renameColumnSelectCb;
1451   sWalker.u.pRename = &sCtx;
1452 
1453   sCtx.pTab = pTab;
1454   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1455   if( sParse.pNewTable ){
1456     Select *pSelect = sParse.pNewTable->pSelect;
1457     if( pSelect ){
1458       pSelect->selFlags &= ~SF_View;
1459       sParse.rc = SQLITE_OK;
1460       sqlite3SelectPrep(&sParse, pSelect, 0);
1461       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1462       if( rc==SQLITE_OK ){
1463         sqlite3WalkSelect(&sWalker, pSelect);
1464       }
1465       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1466     }else{
1467       /* A regular table */
1468       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1469       FKey *pFKey;
1470       assert( sParse.pNewTable->pSelect==0 );
1471       sCtx.pTab = sParse.pNewTable;
1472       if( bFKOnly==0 ){
1473         renameTokenFind(
1474             &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1475         );
1476         if( sCtx.iCol<0 ){
1477           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1478         }
1479         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1480         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1481           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1482         }
1483         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1484           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1485         }
1486 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1487         for(i=0; i<sParse.pNewTable->nCol; i++){
1488           sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1489         }
1490 #endif
1491       }
1492 
1493       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1494         for(i=0; i<pFKey->nCol; i++){
1495           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1496             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1497           }
1498           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1499            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1500           ){
1501             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1502           }
1503         }
1504       }
1505     }
1506   }else if( sParse.pNewIndex ){
1507     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1508     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1509   }else{
1510     /* A trigger */
1511     TriggerStep *pStep;
1512     rc = renameResolveTrigger(&sParse);
1513     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1514 
1515     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1516       if( pStep->zTarget ){
1517         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1518         if( pTarget==pTab ){
1519           if( pStep->pUpsert ){
1520             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1521             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1522           }
1523           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1524           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1525         }
1526       }
1527     }
1528 
1529 
1530     /* Find tokens to edit in UPDATE OF clause */
1531     if( sParse.pTriggerTab==pTab ){
1532       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1533     }
1534 
1535     /* Find tokens to edit in various expressions and selects */
1536     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1537   }
1538 
1539   assert( rc==SQLITE_OK );
1540   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1541 
1542 renameColumnFunc_done:
1543   if( rc!=SQLITE_OK ){
1544     if( sParse.zErrMsg ){
1545       renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1546     }else{
1547       sqlite3_result_error_code(context, rc);
1548     }
1549   }
1550 
1551   renameParseCleanup(&sParse);
1552   renameTokenFree(db, sCtx.pList);
1553 #ifndef SQLITE_OMIT_AUTHORIZATION
1554   db->xAuth = xAuth;
1555 #endif
1556   sqlite3BtreeLeaveAll(db);
1557 }
1558 
1559 /*
1560 ** Walker expression callback used by "RENAME TABLE".
1561 */
1562 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1563   RenameCtx *p = pWalker->u.pRename;
1564   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1565     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1566   }
1567   return WRC_Continue;
1568 }
1569 
1570 /*
1571 ** Walker select callback used by "RENAME TABLE".
1572 */
1573 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1574   int i;
1575   RenameCtx *p = pWalker->u.pRename;
1576   SrcList *pSrc = pSelect->pSrc;
1577   if( pSelect->selFlags & SF_View ) return WRC_Prune;
1578   if( pSrc==0 ){
1579     assert( pWalker->pParse->db->mallocFailed );
1580     return WRC_Abort;
1581   }
1582   for(i=0; i<pSrc->nSrc; i++){
1583     SrcItem *pItem = &pSrc->a[i];
1584     if( pItem->pTab==p->pTab ){
1585       renameTokenFind(pWalker->pParse, p, pItem->zName);
1586     }
1587   }
1588   renameWalkWith(pWalker, pSelect);
1589 
1590   return WRC_Continue;
1591 }
1592 
1593 
1594 /*
1595 ** This C function implements an SQL user function that is used by SQL code
1596 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1597 ** of any foreign key constraints that use the table being renamed as the
1598 ** parent table. It is passed three arguments:
1599 **
1600 **   0: The database containing the table being renamed.
1601 **   1. type:     Type of object ("table", "view" etc.)
1602 **   2. object:   Name of object
1603 **   3: The complete text of the schema statement being modified,
1604 **   4: The old name of the table being renamed, and
1605 **   5: The new name of the table being renamed.
1606 **   6: True if the schema statement comes from the temp db.
1607 **
1608 ** It returns the new schema statement. For example:
1609 **
1610 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1611 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1612 */
1613 static void renameTableFunc(
1614   sqlite3_context *context,
1615   int NotUsed,
1616   sqlite3_value **argv
1617 ){
1618   sqlite3 *db = sqlite3_context_db_handle(context);
1619   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1620   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1621   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1622   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1623   int bTemp = sqlite3_value_int(argv[6]);
1624   UNUSED_PARAMETER(NotUsed);
1625 
1626   if( zInput && zOld && zNew ){
1627     Parse sParse;
1628     int rc;
1629     int bQuote = 1;
1630     RenameCtx sCtx;
1631     Walker sWalker;
1632 
1633 #ifndef SQLITE_OMIT_AUTHORIZATION
1634     sqlite3_xauth xAuth = db->xAuth;
1635     db->xAuth = 0;
1636 #endif
1637 
1638     sqlite3BtreeEnterAll(db);
1639 
1640     memset(&sCtx, 0, sizeof(RenameCtx));
1641     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1642     memset(&sWalker, 0, sizeof(Walker));
1643     sWalker.pParse = &sParse;
1644     sWalker.xExprCallback = renameTableExprCb;
1645     sWalker.xSelectCallback = renameTableSelectCb;
1646     sWalker.u.pRename = &sCtx;
1647 
1648     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1649 
1650     if( rc==SQLITE_OK ){
1651       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1652       if( sParse.pNewTable ){
1653         Table *pTab = sParse.pNewTable;
1654 
1655         if( pTab->pSelect ){
1656           if( isLegacy==0 ){
1657             Select *pSelect = pTab->pSelect;
1658             NameContext sNC;
1659             memset(&sNC, 0, sizeof(sNC));
1660             sNC.pParse = &sParse;
1661 
1662             assert( pSelect->selFlags & SF_View );
1663             pSelect->selFlags &= ~SF_View;
1664             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1665             if( sParse.nErr ){
1666               rc = sParse.rc;
1667             }else{
1668               sqlite3WalkSelect(&sWalker, pTab->pSelect);
1669             }
1670           }
1671         }else{
1672           /* Modify any FK definitions to point to the new table. */
1673 #ifndef SQLITE_OMIT_FOREIGN_KEY
1674           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1675             FKey *pFKey;
1676             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1677               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1678                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1679               }
1680             }
1681           }
1682 #endif
1683 
1684           /* If this is the table being altered, fix any table refs in CHECK
1685           ** expressions. Also update the name that appears right after the
1686           ** "CREATE [VIRTUAL] TABLE" bit. */
1687           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1688             sCtx.pTab = pTab;
1689             if( isLegacy==0 ){
1690               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1691             }
1692             renameTokenFind(&sParse, &sCtx, pTab->zName);
1693           }
1694         }
1695       }
1696 
1697       else if( sParse.pNewIndex ){
1698         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1699         if( isLegacy==0 ){
1700           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1701         }
1702       }
1703 
1704 #ifndef SQLITE_OMIT_TRIGGER
1705       else{
1706         Trigger *pTrigger = sParse.pNewTrigger;
1707         TriggerStep *pStep;
1708         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1709             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1710           ){
1711           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1712         }
1713 
1714         if( isLegacy==0 ){
1715           rc = renameResolveTrigger(&sParse);
1716           if( rc==SQLITE_OK ){
1717             renameWalkTrigger(&sWalker, pTrigger);
1718             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1719               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1720                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1721               }
1722             }
1723           }
1724         }
1725       }
1726 #endif
1727     }
1728 
1729     if( rc==SQLITE_OK ){
1730       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1731     }
1732     if( rc!=SQLITE_OK ){
1733       if( sParse.zErrMsg ){
1734         renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1735       }else{
1736         sqlite3_result_error_code(context, rc);
1737       }
1738     }
1739 
1740     renameParseCleanup(&sParse);
1741     renameTokenFree(db, sCtx.pList);
1742     sqlite3BtreeLeaveAll(db);
1743 #ifndef SQLITE_OMIT_AUTHORIZATION
1744     db->xAuth = xAuth;
1745 #endif
1746   }
1747 
1748   return;
1749 }
1750 
1751 static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1752   if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1753     renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1754   }
1755   return WRC_Continue;
1756 }
1757 
1758 /*
1759 ** The implementation of an SQL scalar function that rewrites DDL statements
1760 ** so that any string literals that use double-quotes are modified so that
1761 ** they use single quotes.
1762 **
1763 ** Two arguments must be passed:
1764 **
1765 **   0: Database name ("main", "temp" etc.).
1766 **   1: SQL statement to edit.
1767 **
1768 ** The returned value is the modified SQL statement. For example, given
1769 ** the database schema:
1770 **
1771 **   CREATE TABLE t1(a, b, c);
1772 **
1773 **   SELECT sqlite_rename_quotefix('main',
1774 **       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1775 **   );
1776 **
1777 ** returns the string:
1778 **
1779 **   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1780 */
1781 static void renameQuotefixFunc(
1782   sqlite3_context *context,
1783   int NotUsed,
1784   sqlite3_value **argv
1785 ){
1786   sqlite3 *db = sqlite3_context_db_handle(context);
1787   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1788   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1789 
1790 #ifndef SQLITE_OMIT_AUTHORIZATION
1791   sqlite3_xauth xAuth = db->xAuth;
1792   db->xAuth = 0;
1793 #endif
1794 
1795   sqlite3BtreeEnterAll(db);
1796 
1797   UNUSED_PARAMETER(NotUsed);
1798   if( zDb && zInput ){
1799     int rc;
1800     Parse sParse;
1801     rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1802 
1803     if( rc==SQLITE_OK ){
1804       RenameCtx sCtx;
1805       Walker sWalker;
1806 
1807       /* Walker to find tokens that need to be replaced. */
1808       memset(&sCtx, 0, sizeof(RenameCtx));
1809       memset(&sWalker, 0, sizeof(Walker));
1810       sWalker.pParse = &sParse;
1811       sWalker.xExprCallback = renameQuotefixExprCb;
1812       sWalker.xSelectCallback = renameColumnSelectCb;
1813       sWalker.u.pRename = &sCtx;
1814 
1815       if( sParse.pNewTable ){
1816         Select *pSelect = sParse.pNewTable->pSelect;
1817         if( pSelect ){
1818           pSelect->selFlags &= ~SF_View;
1819           sParse.rc = SQLITE_OK;
1820           sqlite3SelectPrep(&sParse, pSelect, 0);
1821           rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1822           if( rc==SQLITE_OK ){
1823             sqlite3WalkSelect(&sWalker, pSelect);
1824           }
1825         }else{
1826           int i;
1827           sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1828 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1829           for(i=0; i<sParse.pNewTable->nCol; i++){
1830             sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1831           }
1832 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1833         }
1834       }else if( sParse.pNewIndex ){
1835         sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1836         sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1837       }else{
1838 #ifndef SQLITE_OMIT_TRIGGER
1839         rc = renameResolveTrigger(&sParse);
1840         if( rc==SQLITE_OK ){
1841           renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1842         }
1843 #endif /* SQLITE_OMIT_TRIGGER */
1844       }
1845 
1846       if( rc==SQLITE_OK ){
1847         rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1848       }
1849       renameTokenFree(db, sCtx.pList);
1850     }
1851     if( rc!=SQLITE_OK ){
1852       sqlite3_result_error_code(context, rc);
1853     }
1854     renameParseCleanup(&sParse);
1855   }
1856 
1857 #ifndef SQLITE_OMIT_AUTHORIZATION
1858   db->xAuth = xAuth;
1859 #endif
1860 
1861   sqlite3BtreeLeaveAll(db);
1862 }
1863 
1864 /*
1865 ** An SQL user function that checks that there are no parse or symbol
1866 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1867 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1868 ** reloaded, this function is called on each SQL statement in the schema
1869 ** to ensure that it is still usable.
1870 **
1871 **   0: Database name ("main", "temp" etc.).
1872 **   1: SQL statement.
1873 **   2: Object type ("view", "table", "trigger" or "index").
1874 **   3: Object name.
1875 **   4: True if object is from temp schema.
1876 **   5: "when" part of error message.
1877 **   6: True to disable the DQS quirk when parsing SQL.
1878 **
1879 ** Unless it finds an error, this function normally returns NULL. However, it
1880 ** returns integer value 1 if:
1881 **
1882 **   * the SQL argument creates a trigger, and
1883 **   * the table that the trigger is attached to is in database zDb.
1884 */
1885 static void renameTableTest(
1886   sqlite3_context *context,
1887   int NotUsed,
1888   sqlite3_value **argv
1889 ){
1890   sqlite3 *db = sqlite3_context_db_handle(context);
1891   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1892   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1893   int bTemp = sqlite3_value_int(argv[4]);
1894   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1895   char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
1896   int bNoDQS = sqlite3_value_int(argv[6]);
1897 
1898 #ifndef SQLITE_OMIT_AUTHORIZATION
1899   sqlite3_xauth xAuth = db->xAuth;
1900   db->xAuth = 0;
1901 #endif
1902 
1903   UNUSED_PARAMETER(NotUsed);
1904 
1905   if( zDb && zInput ){
1906     int rc;
1907     Parse sParse;
1908     int flags = db->flags;
1909     if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
1910     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1911     db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
1912     if( rc==SQLITE_OK ){
1913       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1914         NameContext sNC;
1915         memset(&sNC, 0, sizeof(sNC));
1916         sNC.pParse = &sParse;
1917         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1918         if( sParse.nErr ) rc = sParse.rc;
1919       }
1920 
1921       else if( sParse.pNewTrigger ){
1922         if( isLegacy==0 ){
1923           rc = renameResolveTrigger(&sParse);
1924         }
1925         if( rc==SQLITE_OK ){
1926           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1927           int i2 = sqlite3FindDbName(db, zDb);
1928           if( i1==i2 ) sqlite3_result_int(context, 1);
1929         }
1930       }
1931     }
1932 
1933     if( rc!=SQLITE_OK && zWhen ){
1934       renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
1935     }
1936     renameParseCleanup(&sParse);
1937   }
1938 
1939 #ifndef SQLITE_OMIT_AUTHORIZATION
1940   db->xAuth = xAuth;
1941 #endif
1942 }
1943 
1944 /*
1945 ** The implementation of internal UDF sqlite_drop_column().
1946 **
1947 ** Arguments:
1948 **
1949 **  argv[0]: An integer - the index of the schema containing the table
1950 **  argv[1]: CREATE TABLE statement to modify.
1951 **  argv[2]: An integer - the index of the column to remove.
1952 **
1953 ** The value returned is a string containing the CREATE TABLE statement
1954 ** with column argv[2] removed.
1955 */
1956 static void dropColumnFunc(
1957   sqlite3_context *context,
1958   int NotUsed,
1959   sqlite3_value **argv
1960 ){
1961   sqlite3 *db = sqlite3_context_db_handle(context);
1962   int iSchema = sqlite3_value_int(argv[0]);
1963   const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1964   int iCol = sqlite3_value_int(argv[2]);
1965   const char *zDb = db->aDb[iSchema].zDbSName;
1966   int rc;
1967   Parse sParse;
1968   RenameToken *pCol;
1969   Table *pTab;
1970   const char *zEnd;
1971   char *zNew = 0;
1972 
1973 #ifndef SQLITE_OMIT_AUTHORIZATION
1974   sqlite3_xauth xAuth = db->xAuth;
1975   db->xAuth = 0;
1976 #endif
1977 
1978   UNUSED_PARAMETER(NotUsed);
1979   rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
1980   if( rc!=SQLITE_OK ) goto drop_column_done;
1981   pTab = sParse.pNewTable;
1982   if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
1983     /* This can happen if the sqlite_schema table is corrupt */
1984     rc = SQLITE_CORRUPT_BKPT;
1985     goto drop_column_done;
1986   }
1987 
1988   pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
1989   if( iCol<pTab->nCol-1 ){
1990     RenameToken *pEnd;
1991     pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
1992     zEnd = (const char*)pEnd->t.z;
1993   }else{
1994     zEnd = (const char*)&zSql[pTab->addColOffset];
1995     while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
1996   }
1997 
1998   zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
1999   sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2000   sqlite3_free(zNew);
2001 
2002 drop_column_done:
2003   renameParseCleanup(&sParse);
2004 #ifndef SQLITE_OMIT_AUTHORIZATION
2005   db->xAuth = xAuth;
2006 #endif
2007   if( rc!=SQLITE_OK ){
2008     sqlite3_result_error_code(context, rc);
2009   }
2010 }
2011 
2012 /*
2013 ** This function is called by the parser upon parsing an
2014 **
2015 **     ALTER TABLE pSrc DROP COLUMN pName
2016 **
2017 ** statement. Argument pSrc contains the possibly qualified name of the
2018 ** table being edited, and token pName the name of the column to drop.
2019 */
2020 void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
2021   sqlite3 *db = pParse->db;       /* Database handle */
2022   Table *pTab;                    /* Table to modify */
2023   int iDb;                        /* Index of db containing pTab in aDb[] */
2024   const char *zDb;                /* Database containing pTab ("main" etc.) */
2025   char *zCol = 0;                 /* Name of column to drop */
2026   int iCol;                       /* Index of column zCol in pTab->aCol[] */
2027 
2028   /* Look up the table being altered. */
2029   assert( pParse->pNewTable==0 );
2030   assert( sqlite3BtreeHoldsAllMutexes(db) );
2031   if( NEVER(db->mallocFailed) ) goto exit_drop_column;
2032   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2033   if( !pTab ) goto exit_drop_column;
2034 
2035   /* Make sure this is not an attempt to ALTER a view, virtual table or
2036   ** system table. */
2037   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2038   if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
2039 
2040   /* Find the index of the column being dropped. */
2041   zCol = sqlite3NameFromToken(db, pName);
2042   if( zCol==0 ){
2043     assert( db->mallocFailed );
2044     goto exit_drop_column;
2045   }
2046   iCol = sqlite3ColumnIndex(pTab, zCol);
2047   if( iCol<0 ){
2048     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2049     goto exit_drop_column;
2050   }
2051 
2052   /* Do not allow the user to drop a PRIMARY KEY column or a column
2053   ** constrained by a UNIQUE constraint.  */
2054   if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2055     sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2056         (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2057         zCol
2058     );
2059     goto exit_drop_column;
2060   }
2061 
2062   /* Do not allow the number of columns to go to zero */
2063   if( pTab->nCol<=1 ){
2064     sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2065     goto exit_drop_column;
2066   }
2067 
2068   /* Edit the sqlite_schema table */
2069   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2070   assert( iDb>=0 );
2071   zDb = db->aDb[iDb].zDbSName;
2072   renameTestSchema(pParse, zDb, iDb==1, "", 0);
2073   renameFixQuotes(pParse, zDb, iDb==1);
2074   sqlite3NestedParse(pParse,
2075       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
2076       "sql = sqlite_drop_column(%d, sql, %d) "
2077       "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
2078       , zDb, iDb, iCol, pTab->zName
2079   );
2080 
2081   /* Drop and reload the database schema. */
2082   renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
2083   renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
2084 
2085   /* Edit rows of table on disk */
2086   if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
2087     int i;
2088     int addr;
2089     int reg;
2090     int regRec;
2091     Index *pPk = 0;
2092     int nField = 0;               /* Number of non-virtual columns after drop */
2093     int iCur;
2094     Vdbe *v = sqlite3GetVdbe(pParse);
2095     iCur = pParse->nTab++;
2096     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
2097     addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2098     reg = ++pParse->nMem;
2099     pParse->nMem += pTab->nCol;
2100     if( HasRowid(pTab) ){
2101       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
2102     }else{
2103       pPk = sqlite3PrimaryKeyIndex(pTab);
2104     }
2105     for(i=0; i<pTab->nCol; i++){
2106       if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2107         int regOut;
2108         if( pPk ){
2109           int iPos = sqlite3TableColumnToIndex(pPk, i);
2110           int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
2111           regOut = reg+1+iPos-(iPos>iColPos);
2112         }else{
2113           regOut = reg+1+nField;
2114         }
2115         sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2116         nField++;
2117       }
2118     }
2119     regRec = reg + pTab->nCol;
2120     sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2121     if( pPk ){
2122       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2123     }else{
2124       sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2125     }
2126 
2127     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
2128     sqlite3VdbeJumpHere(v, addr);
2129   }
2130 
2131 exit_drop_column:
2132   sqlite3DbFree(db, zCol);
2133   sqlite3SrcListDelete(db, pSrc);
2134 }
2135 
2136 /*
2137 ** Register built-in functions used to help implement ALTER TABLE
2138 */
2139 void sqlite3AlterFunctions(void){
2140   static FuncDef aAlterTableFuncs[] = {
2141     INTERNAL_FUNCTION(sqlite_rename_column,  9, renameColumnFunc),
2142     INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
2143     INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
2144     INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
2145     INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
2146   };
2147   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2148 }
2149 #endif  /* SQLITE_ALTER_TABLE */
2150