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