xref: /sqlite-3.40.0/src/alter.c (revision 8d889afc)
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     int i;
804     for(i=0; i<pWith->nCte; i++){
805       Select *p = pWith->a[i].pSelect;
806       NameContext sNC;
807       memset(&sNC, 0, sizeof(sNC));
808       sNC.pParse = pWalker->pParse;
809       sqlite3SelectPrep(sNC.pParse, p, &sNC);
810       sqlite3WalkSelect(pWalker, p);
811       sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
812     }
813   }
814 }
815 
816 /*
817 ** Unmap all tokens in the IdList object passed as the second argument.
818 */
819 static void unmapColumnIdlistNames(
820   Parse *pParse,
821   IdList *pIdList
822 ){
823   if( pIdList ){
824     int ii;
825     for(ii=0; ii<pIdList->nId; ii++){
826       sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
827     }
828   }
829 }
830 
831 /*
832 ** Walker callback used by sqlite3RenameExprUnmap().
833 */
834 static int renameUnmapSelectCb(Walker *pWalker, Select *p){
835   Parse *pParse = pWalker->pParse;
836   int i;
837   if( pParse->nErr ) return WRC_Abort;
838   if( p->selFlags & SF_View ) return WRC_Prune;
839   if( ALWAYS(p->pEList) ){
840     ExprList *pList = p->pEList;
841     for(i=0; i<pList->nExpr; i++){
842       if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
843         sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
844       }
845     }
846   }
847   if( ALWAYS(p->pSrc) ){  /* Every Select as a SrcList, even if it is empty */
848     SrcList *pSrc = p->pSrc;
849     for(i=0; i<pSrc->nSrc; i++){
850       sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
851       if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
852       unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
853     }
854   }
855 
856   renameWalkWith(pWalker, p);
857   return WRC_Continue;
858 }
859 
860 /*
861 ** Remove all nodes that are part of expression pExpr from the rename list.
862 */
863 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
864   u8 eMode = pParse->eParseMode;
865   Walker sWalker;
866   memset(&sWalker, 0, sizeof(Walker));
867   sWalker.pParse = pParse;
868   sWalker.xExprCallback = renameUnmapExprCb;
869   sWalker.xSelectCallback = renameUnmapSelectCb;
870   pParse->eParseMode = PARSE_MODE_UNMAP;
871   sqlite3WalkExpr(&sWalker, pExpr);
872   pParse->eParseMode = eMode;
873 }
874 
875 /*
876 ** Remove all nodes that are part of expression-list pEList from the
877 ** rename list.
878 */
879 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
880   if( pEList ){
881     int i;
882     Walker sWalker;
883     memset(&sWalker, 0, sizeof(Walker));
884     sWalker.pParse = pParse;
885     sWalker.xExprCallback = renameUnmapExprCb;
886     sqlite3WalkExprList(&sWalker, pEList);
887     for(i=0; i<pEList->nExpr; i++){
888       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
889         sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
890       }
891     }
892   }
893 }
894 
895 /*
896 ** Free the list of RenameToken objects given in the second argument
897 */
898 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
899   RenameToken *pNext;
900   RenameToken *p;
901   for(p=pToken; p; p=pNext){
902     pNext = p->pNext;
903     sqlite3DbFree(db, p);
904   }
905 }
906 
907 /*
908 ** Search the Parse object passed as the first argument for a RenameToken
909 ** object associated with parse tree element pPtr. If found, return a pointer
910 ** to it. Otherwise, return NULL.
911 **
912 ** If the second argument passed to this function is not NULL and a matching
913 ** RenameToken object is found, remove it from the Parse object and add it to
914 ** the list maintained by the RenameCtx object.
915 */
916 static RenameToken *renameTokenFind(
917   Parse *pParse,
918   struct RenameCtx *pCtx,
919   void *pPtr
920 ){
921   RenameToken **pp;
922   if( NEVER(pPtr==0) ){
923     return 0;
924   }
925   for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
926     if( (*pp)->p==pPtr ){
927       RenameToken *pToken = *pp;
928       if( pCtx ){
929         *pp = pToken->pNext;
930         pToken->pNext = pCtx->pList;
931         pCtx->pList = pToken;
932         pCtx->nList++;
933       }
934       return pToken;
935     }
936   }
937   return 0;
938 }
939 
940 /*
941 ** This is a Walker select callback. It does nothing. It is only required
942 ** because without a dummy callback, sqlite3WalkExpr() and similar do not
943 ** descend into sub-select statements.
944 */
945 static int renameColumnSelectCb(Walker *pWalker, Select *p){
946   if( p->selFlags & SF_View ) return WRC_Prune;
947   renameWalkWith(pWalker, p);
948   return WRC_Continue;
949 }
950 
951 /*
952 ** This is a Walker expression callback.
953 **
954 ** For every TK_COLUMN node in the expression tree, search to see
955 ** if the column being references is the column being renamed by an
956 ** ALTER TABLE statement.  If it is, then attach its associated
957 ** RenameToken object to the list of RenameToken objects being
958 ** constructed in RenameCtx object at pWalker->u.pRename.
959 */
960 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
961   RenameCtx *p = pWalker->u.pRename;
962   if( pExpr->op==TK_TRIGGER
963    && pExpr->iColumn==p->iCol
964    && pWalker->pParse->pTriggerTab==p->pTab
965   ){
966     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
967   }else if( pExpr->op==TK_COLUMN
968    && pExpr->iColumn==p->iCol
969    && p->pTab==pExpr->y.pTab
970   ){
971     renameTokenFind(pWalker->pParse, p, (void*)pExpr);
972   }
973   return WRC_Continue;
974 }
975 
976 /*
977 ** The RenameCtx contains a list of tokens that reference a column that
978 ** is being renamed by an ALTER TABLE statement.  Return the "last"
979 ** RenameToken in the RenameCtx and remove that RenameToken from the
980 ** RenameContext.  "Last" means the last RenameToken encountered when
981 ** the input SQL is parsed from left to right.  Repeated calls to this routine
982 ** return all column name tokens in the order that they are encountered
983 ** in the SQL statement.
984 */
985 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
986   RenameToken *pBest = pCtx->pList;
987   RenameToken *pToken;
988   RenameToken **pp;
989 
990   for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
991     if( pToken->t.z>pBest->t.z ) pBest = pToken;
992   }
993   for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
994   *pp = pBest->pNext;
995 
996   return pBest;
997 }
998 
999 /*
1000 ** An error occured while parsing or otherwise processing a database
1001 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1002 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1003 ** sub-routine is currently stored in pParse->zErrMsg. This function
1004 ** adds context to the error message and then stores it in pCtx.
1005 */
1006 static void renameColumnParseError(
1007   sqlite3_context *pCtx,
1008   const char *zWhen,
1009   sqlite3_value *pType,
1010   sqlite3_value *pObject,
1011   Parse *pParse
1012 ){
1013   const char *zT = (const char*)sqlite3_value_text(pType);
1014   const char *zN = (const char*)sqlite3_value_text(pObject);
1015   char *zErr;
1016 
1017   zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1018       zT, zN, (zWhen[0] ? " " : ""), zWhen,
1019       pParse->zErrMsg
1020   );
1021   sqlite3_result_error(pCtx, zErr, -1);
1022   sqlite3_free(zErr);
1023 }
1024 
1025 /*
1026 ** For each name in the the expression-list pEList (i.e. each
1027 ** pEList->a[i].zName) that matches the string in zOld, extract the
1028 ** corresponding rename-token from Parse object pParse and add it
1029 ** to the RenameCtx pCtx.
1030 */
1031 static void renameColumnElistNames(
1032   Parse *pParse,
1033   RenameCtx *pCtx,
1034   ExprList *pEList,
1035   const char *zOld
1036 ){
1037   if( pEList ){
1038     int i;
1039     for(i=0; i<pEList->nExpr; i++){
1040       char *zName = pEList->a[i].zEName;
1041       if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1042        && ALWAYS(zName!=0)
1043        && 0==sqlite3_stricmp(zName, zOld)
1044       ){
1045         renameTokenFind(pParse, pCtx, (void*)zName);
1046       }
1047     }
1048   }
1049 }
1050 
1051 /*
1052 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1053 ** that matches the string in zOld, extract the corresponding rename-token
1054 ** from Parse object pParse and add it to the RenameCtx pCtx.
1055 */
1056 static void renameColumnIdlistNames(
1057   Parse *pParse,
1058   RenameCtx *pCtx,
1059   IdList *pIdList,
1060   const char *zOld
1061 ){
1062   if( pIdList ){
1063     int i;
1064     for(i=0; i<pIdList->nId; i++){
1065       char *zName = pIdList->a[i].zName;
1066       if( 0==sqlite3_stricmp(zName, zOld) ){
1067         renameTokenFind(pParse, pCtx, (void*)zName);
1068       }
1069     }
1070   }
1071 }
1072 
1073 
1074 /*
1075 ** Parse the SQL statement zSql using Parse object (*p). The Parse object
1076 ** is initialized by this function before it is used.
1077 */
1078 static int renameParseSql(
1079   Parse *p,                       /* Memory to use for Parse object */
1080   const char *zDb,                /* Name of schema SQL belongs to */
1081   sqlite3 *db,                    /* Database handle */
1082   const char *zSql,               /* SQL to parse */
1083   int bTemp                       /* True if SQL is from temp schema */
1084 ){
1085   int rc;
1086   char *zErr = 0;
1087 
1088   db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1089 
1090   /* Parse the SQL statement passed as the first argument. If no error
1091   ** occurs and the parse does not result in a new table, index or
1092   ** trigger object, the database must be corrupt. */
1093   memset(p, 0, sizeof(Parse));
1094   p->eParseMode = PARSE_MODE_RENAME;
1095   p->db = db;
1096   p->nQueryLoop = 1;
1097   rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
1098   assert( p->zErrMsg==0 );
1099   assert( rc!=SQLITE_OK || zErr==0 );
1100   p->zErrMsg = zErr;
1101   if( db->mallocFailed ) rc = SQLITE_NOMEM;
1102   if( rc==SQLITE_OK
1103    && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1104   ){
1105     rc = SQLITE_CORRUPT_BKPT;
1106   }
1107 
1108 #ifdef SQLITE_DEBUG
1109   /* Ensure that all mappings in the Parse.pRename list really do map to
1110   ** a part of the input string.  */
1111   if( rc==SQLITE_OK ){
1112     int nSql = sqlite3Strlen30(zSql);
1113     RenameToken *pToken;
1114     for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1115       assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1116     }
1117   }
1118 #endif
1119 
1120   db->init.iDb = 0;
1121   return rc;
1122 }
1123 
1124 /*
1125 ** This function edits SQL statement zSql, replacing each token identified
1126 ** by the linked list pRename with the text of zNew. If argument bQuote is
1127 ** true, then zNew is always quoted first. If no error occurs, the result
1128 ** is loaded into context object pCtx as the result.
1129 **
1130 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
1131 ** pCtx and an SQLite error code returned.
1132 */
1133 static int renameEditSql(
1134   sqlite3_context *pCtx,          /* Return result here */
1135   RenameCtx *pRename,             /* Rename context */
1136   const char *zSql,               /* SQL statement to edit */
1137   const char *zNew,               /* New token text */
1138   int bQuote                      /* True to always quote token */
1139 ){
1140   int nNew = sqlite3Strlen30(zNew);
1141   int nSql = sqlite3Strlen30(zSql);
1142   sqlite3 *db = sqlite3_context_db_handle(pCtx);
1143   int rc = SQLITE_OK;
1144   char *zQuot = 0;
1145   char *zOut;
1146   int nQuot = 0;
1147   char *zBuf1 = 0;
1148   char *zBuf2 = 0;
1149 
1150   if( zNew ){
1151     /* Set zQuot to point to a buffer containing a quoted copy of the
1152     ** identifier zNew. If the corresponding identifier in the original
1153     ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1154     ** point to zQuot so that all substitutions are made using the
1155     ** quoted version of the new column name.  */
1156     zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
1157     if( zQuot==0 ){
1158       return SQLITE_NOMEM;
1159     }else{
1160       nQuot = sqlite3Strlen30(zQuot)-1;
1161     }
1162 
1163     assert( nQuot>=nNew );
1164     zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1165   }else{
1166     zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1167     if( zOut ){
1168       zBuf1 = &zOut[nSql*2+1];
1169       zBuf2 = &zOut[nSql*4+2];
1170     }
1171   }
1172 
1173   /* At this point pRename->pList contains a list of RenameToken objects
1174   ** corresponding to all tokens in the input SQL that must be replaced
1175   ** with the new column name, or with single-quoted versions of themselves.
1176   ** All that remains is to construct and return the edited SQL string. */
1177   if( zOut ){
1178     int nOut = nSql;
1179     memcpy(zOut, zSql, nSql);
1180     while( pRename->pList ){
1181       int iOff;                   /* Offset of token to replace in zOut */
1182       u32 nReplace;
1183       const char *zReplace;
1184       RenameToken *pBest = renameColumnTokenNext(pRename);
1185 
1186       if( zNew ){
1187         if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
1188           nReplace = nNew;
1189           zReplace = zNew;
1190         }else{
1191           nReplace = nQuot;
1192           zReplace = zQuot;
1193           if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
1194         }
1195       }else{
1196         /* Dequote the double-quoted token. Then requote it again, this time
1197         ** using single quotes. If the character immediately following the
1198         ** original token within the input SQL was a single quote ('), then
1199         ** add another space after the new, single-quoted version of the
1200         ** token. This is so that (SELECT "string"'alias') maps to
1201         ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias').  */
1202         memcpy(zBuf1, pBest->t.z, pBest->t.n);
1203         zBuf1[pBest->t.n] = 0;
1204         sqlite3Dequote(zBuf1);
1205         sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1206             pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1207         );
1208         zReplace = zBuf2;
1209         nReplace = sqlite3Strlen30(zReplace);
1210       }
1211 
1212       iOff = pBest->t.z - zSql;
1213       if( pBest->t.n!=nReplace ){
1214         memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1215             nOut - (iOff + pBest->t.n)
1216         );
1217         nOut += nReplace - pBest->t.n;
1218         zOut[nOut] = '\0';
1219       }
1220       memcpy(&zOut[iOff], zReplace, nReplace);
1221       sqlite3DbFree(db, pBest);
1222     }
1223 
1224     sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1225     sqlite3DbFree(db, zOut);
1226   }else{
1227     rc = SQLITE_NOMEM;
1228   }
1229 
1230   sqlite3_free(zQuot);
1231   return rc;
1232 }
1233 
1234 /*
1235 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1236 ** it was read from the schema of database zDb. Return SQLITE_OK if
1237 ** successful. Otherwise, return an SQLite error code and leave an error
1238 ** message in the Parse object.
1239 */
1240 static int renameResolveTrigger(Parse *pParse){
1241   sqlite3 *db = pParse->db;
1242   Trigger *pNew = pParse->pNewTrigger;
1243   TriggerStep *pStep;
1244   NameContext sNC;
1245   int rc = SQLITE_OK;
1246 
1247   memset(&sNC, 0, sizeof(sNC));
1248   sNC.pParse = pParse;
1249   assert( pNew->pTabSchema );
1250   pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1251       db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1252   );
1253   pParse->eTriggerOp = pNew->op;
1254   /* ALWAYS() because if the table of the trigger does not exist, the
1255   ** error would have been hit before this point */
1256   if( ALWAYS(pParse->pTriggerTab) ){
1257     rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1258   }
1259 
1260   /* Resolve symbols in WHEN clause */
1261   if( rc==SQLITE_OK && pNew->pWhen ){
1262     rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
1263   }
1264 
1265   for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
1266     if( pStep->pSelect ){
1267       sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1268       if( pParse->nErr ) rc = pParse->rc;
1269     }
1270     if( rc==SQLITE_OK && pStep->zTarget ){
1271       SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1272       if( pSrc ){
1273         int i;
1274         for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
1275           SrcItem *p = &pSrc->a[i];
1276           p->iCursor = pParse->nTab++;
1277           if( p->pSelect ){
1278             sqlite3SelectPrep(pParse, p->pSelect, 0);
1279             sqlite3ExpandSubquery(pParse, p);
1280             assert( i>0 );
1281             assert( pStep->pFrom->a[i-1].pSelect );
1282             sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
1283           }else{
1284             p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1285             if( p->pTab==0 ){
1286               rc = SQLITE_ERROR;
1287             }else{
1288               p->pTab->nTabRef++;
1289               rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1290             }
1291           }
1292         }
1293         sNC.pSrcList = pSrc;
1294         if( rc==SQLITE_OK && pStep->pWhere ){
1295           rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1296         }
1297         if( rc==SQLITE_OK ){
1298           rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1299         }
1300         assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1301         if( pStep->pUpsert && rc==SQLITE_OK ){
1302           Upsert *pUpsert = pStep->pUpsert;
1303           pUpsert->pUpsertSrc = pSrc;
1304           sNC.uNC.pUpsert = pUpsert;
1305           sNC.ncFlags = NC_UUpsert;
1306           rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1307           if( rc==SQLITE_OK ){
1308             ExprList *pUpsertSet = pUpsert->pUpsertSet;
1309             rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1310           }
1311           if( rc==SQLITE_OK ){
1312             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1313           }
1314           if( rc==SQLITE_OK ){
1315             rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1316           }
1317           sNC.ncFlags = 0;
1318         }
1319         sNC.pSrcList = 0;
1320         sqlite3SrcListDelete(db, pSrc);
1321       }else{
1322         rc = SQLITE_NOMEM;
1323       }
1324     }
1325   }
1326   return rc;
1327 }
1328 
1329 /*
1330 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1331 ** objects that are part of the trigger passed as the second argument.
1332 */
1333 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1334   TriggerStep *pStep;
1335 
1336   /* Find tokens to edit in WHEN clause */
1337   sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1338 
1339   /* Find tokens to edit in trigger steps */
1340   for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1341     sqlite3WalkSelect(pWalker, pStep->pSelect);
1342     sqlite3WalkExpr(pWalker, pStep->pWhere);
1343     sqlite3WalkExprList(pWalker, pStep->pExprList);
1344     if( pStep->pUpsert ){
1345       Upsert *pUpsert = pStep->pUpsert;
1346       sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1347       sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1348       sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1349       sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1350     }
1351     if( pStep->pFrom ){
1352       int i;
1353       for(i=0; i<pStep->pFrom->nSrc; i++){
1354         sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1355       }
1356     }
1357   }
1358 }
1359 
1360 /*
1361 ** Free the contents of Parse object (*pParse). Do not free the memory
1362 ** occupied by the Parse object itself.
1363 */
1364 static void renameParseCleanup(Parse *pParse){
1365   sqlite3 *db = pParse->db;
1366   Index *pIdx;
1367   if( pParse->pVdbe ){
1368     sqlite3VdbeFinalize(pParse->pVdbe);
1369   }
1370   sqlite3DeleteTable(db, pParse->pNewTable);
1371   while( (pIdx = pParse->pNewIndex)!=0 ){
1372     pParse->pNewIndex = pIdx->pNext;
1373     sqlite3FreeIndex(db, pIdx);
1374   }
1375   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1376   sqlite3DbFree(db, pParse->zErrMsg);
1377   renameTokenFree(db, pParse->pRename);
1378   sqlite3ParserReset(pParse);
1379 }
1380 
1381 /*
1382 ** SQL function:
1383 **
1384 **     sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1385 **
1386 **   0. zSql:     SQL statement to rewrite
1387 **   1. type:     Type of object ("table", "view" etc.)
1388 **   2. object:   Name of object
1389 **   3. Database: Database name (e.g. "main")
1390 **   4. Table:    Table name
1391 **   5. iCol:     Index of column to rename
1392 **   6. zNew:     New column name
1393 **   7. bQuote:   Non-zero if the new column name should be quoted.
1394 **   8. bTemp:    True if zSql comes from temp schema
1395 **
1396 ** Do a column rename operation on the CREATE statement given in zSql.
1397 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1398 ** into zNew.  The name should be quoted if bQuote is true.
1399 **
1400 ** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1401 ** It is only accessible to SQL created using sqlite3NestedParse().  It is
1402 ** not reachable from ordinary SQL passed into sqlite3_prepare().
1403 */
1404 static void renameColumnFunc(
1405   sqlite3_context *context,
1406   int NotUsed,
1407   sqlite3_value **argv
1408 ){
1409   sqlite3 *db = sqlite3_context_db_handle(context);
1410   RenameCtx sCtx;
1411   const char *zSql = (const char*)sqlite3_value_text(argv[0]);
1412   const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1413   const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1414   int iCol = sqlite3_value_int(argv[5]);
1415   const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1416   int bQuote = sqlite3_value_int(argv[7]);
1417   int bTemp = sqlite3_value_int(argv[8]);
1418   const char *zOld;
1419   int rc;
1420   Parse sParse;
1421   Walker sWalker;
1422   Index *pIdx;
1423   int i;
1424   Table *pTab;
1425 #ifndef SQLITE_OMIT_AUTHORIZATION
1426   sqlite3_xauth xAuth = db->xAuth;
1427 #endif
1428 
1429   UNUSED_PARAMETER(NotUsed);
1430   if( zSql==0 ) return;
1431   if( zTable==0 ) return;
1432   if( zNew==0 ) return;
1433   if( iCol<0 ) return;
1434   sqlite3BtreeEnterAll(db);
1435   pTab = sqlite3FindTable(db, zTable, zDb);
1436   if( pTab==0 || iCol>=pTab->nCol ){
1437     sqlite3BtreeLeaveAll(db);
1438     return;
1439   }
1440   zOld = pTab->aCol[iCol].zName;
1441   memset(&sCtx, 0, sizeof(sCtx));
1442   sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
1443 
1444 #ifndef SQLITE_OMIT_AUTHORIZATION
1445   db->xAuth = 0;
1446 #endif
1447   rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
1448 
1449   /* Find tokens that need to be replaced. */
1450   memset(&sWalker, 0, sizeof(Walker));
1451   sWalker.pParse = &sParse;
1452   sWalker.xExprCallback = renameColumnExprCb;
1453   sWalker.xSelectCallback = renameColumnSelectCb;
1454   sWalker.u.pRename = &sCtx;
1455 
1456   sCtx.pTab = pTab;
1457   if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1458   if( sParse.pNewTable ){
1459     Select *pSelect = sParse.pNewTable->pSelect;
1460     if( pSelect ){
1461       pSelect->selFlags &= ~SF_View;
1462       sParse.rc = SQLITE_OK;
1463       sqlite3SelectPrep(&sParse, pSelect, 0);
1464       rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1465       if( rc==SQLITE_OK ){
1466         sqlite3WalkSelect(&sWalker, pSelect);
1467       }
1468       if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1469     }else{
1470       /* A regular table */
1471       int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1472       FKey *pFKey;
1473       assert( sParse.pNewTable->pSelect==0 );
1474       sCtx.pTab = sParse.pNewTable;
1475       if( bFKOnly==0 ){
1476         renameTokenFind(
1477             &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1478         );
1479         if( sCtx.iCol<0 ){
1480           renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
1481         }
1482         sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1483         for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1484           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1485         }
1486         for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1487           sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1488         }
1489 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1490         for(i=0; i<sParse.pNewTable->nCol; i++){
1491           sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1492         }
1493 #endif
1494       }
1495 
1496       for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1497         for(i=0; i<pFKey->nCol; i++){
1498           if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
1499             renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1500           }
1501           if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1502            && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1503           ){
1504             renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1505           }
1506         }
1507       }
1508     }
1509   }else if( sParse.pNewIndex ){
1510     sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1511     sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1512   }else{
1513     /* A trigger */
1514     TriggerStep *pStep;
1515     rc = renameResolveTrigger(&sParse);
1516     if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1517 
1518     for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1519       if( pStep->zTarget ){
1520         Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
1521         if( pTarget==pTab ){
1522           if( pStep->pUpsert ){
1523             ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1524             renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
1525           }
1526           renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1527           renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
1528         }
1529       }
1530     }
1531 
1532 
1533     /* Find tokens to edit in UPDATE OF clause */
1534     if( sParse.pTriggerTab==pTab ){
1535       renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
1536     }
1537 
1538     /* Find tokens to edit in various expressions and selects */
1539     renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1540   }
1541 
1542   assert( rc==SQLITE_OK );
1543   rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
1544 
1545 renameColumnFunc_done:
1546   if( rc!=SQLITE_OK ){
1547     if( sParse.zErrMsg ){
1548       renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1549     }else{
1550       sqlite3_result_error_code(context, rc);
1551     }
1552   }
1553 
1554   renameParseCleanup(&sParse);
1555   renameTokenFree(db, sCtx.pList);
1556 #ifndef SQLITE_OMIT_AUTHORIZATION
1557   db->xAuth = xAuth;
1558 #endif
1559   sqlite3BtreeLeaveAll(db);
1560 }
1561 
1562 /*
1563 ** Walker expression callback used by "RENAME TABLE".
1564 */
1565 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1566   RenameCtx *p = pWalker->u.pRename;
1567   if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1568     renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
1569   }
1570   return WRC_Continue;
1571 }
1572 
1573 /*
1574 ** Walker select callback used by "RENAME TABLE".
1575 */
1576 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1577   int i;
1578   RenameCtx *p = pWalker->u.pRename;
1579   SrcList *pSrc = pSelect->pSrc;
1580   if( pSelect->selFlags & SF_View ) return WRC_Prune;
1581   if( NEVER(pSrc==0) ){
1582     assert( pWalker->pParse->db->mallocFailed );
1583     return WRC_Abort;
1584   }
1585   for(i=0; i<pSrc->nSrc; i++){
1586     SrcItem *pItem = &pSrc->a[i];
1587     if( pItem->pTab==p->pTab ){
1588       renameTokenFind(pWalker->pParse, p, pItem->zName);
1589     }
1590   }
1591   renameWalkWith(pWalker, pSelect);
1592 
1593   return WRC_Continue;
1594 }
1595 
1596 
1597 /*
1598 ** This C function implements an SQL user function that is used by SQL code
1599 ** generated by the ALTER TABLE ... RENAME command to modify the definition
1600 ** of any foreign key constraints that use the table being renamed as the
1601 ** parent table. It is passed three arguments:
1602 **
1603 **   0: The database containing the table being renamed.
1604 **   1. type:     Type of object ("table", "view" etc.)
1605 **   2. object:   Name of object
1606 **   3: The complete text of the schema statement being modified,
1607 **   4: The old name of the table being renamed, and
1608 **   5: The new name of the table being renamed.
1609 **   6: True if the schema statement comes from the temp db.
1610 **
1611 ** It returns the new schema statement. For example:
1612 **
1613 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
1614 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
1615 */
1616 static void renameTableFunc(
1617   sqlite3_context *context,
1618   int NotUsed,
1619   sqlite3_value **argv
1620 ){
1621   sqlite3 *db = sqlite3_context_db_handle(context);
1622   const char *zDb = (const char*)sqlite3_value_text(argv[0]);
1623   const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1624   const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1625   const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1626   int bTemp = sqlite3_value_int(argv[6]);
1627   UNUSED_PARAMETER(NotUsed);
1628 
1629   if( zInput && zOld && zNew ){
1630     Parse sParse;
1631     int rc;
1632     int bQuote = 1;
1633     RenameCtx sCtx;
1634     Walker sWalker;
1635 
1636 #ifndef SQLITE_OMIT_AUTHORIZATION
1637     sqlite3_xauth xAuth = db->xAuth;
1638     db->xAuth = 0;
1639 #endif
1640 
1641     sqlite3BtreeEnterAll(db);
1642 
1643     memset(&sCtx, 0, sizeof(RenameCtx));
1644     sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1645     memset(&sWalker, 0, sizeof(Walker));
1646     sWalker.pParse = &sParse;
1647     sWalker.xExprCallback = renameTableExprCb;
1648     sWalker.xSelectCallback = renameTableSelectCb;
1649     sWalker.u.pRename = &sCtx;
1650 
1651     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1652 
1653     if( rc==SQLITE_OK ){
1654       int isLegacy = (db->flags & SQLITE_LegacyAlter);
1655       if( sParse.pNewTable ){
1656         Table *pTab = sParse.pNewTable;
1657 
1658         if( pTab->pSelect ){
1659           if( isLegacy==0 ){
1660             Select *pSelect = pTab->pSelect;
1661             NameContext sNC;
1662             memset(&sNC, 0, sizeof(sNC));
1663             sNC.pParse = &sParse;
1664 
1665             assert( pSelect->selFlags & SF_View );
1666             pSelect->selFlags &= ~SF_View;
1667             sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1668             if( sParse.nErr ){
1669               rc = sParse.rc;
1670             }else{
1671               sqlite3WalkSelect(&sWalker, pTab->pSelect);
1672             }
1673           }
1674         }else{
1675           /* Modify any FK definitions to point to the new table. */
1676 #ifndef SQLITE_OMIT_FOREIGN_KEY
1677           if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
1678             FKey *pFKey;
1679             for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1680               if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1681                 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1682               }
1683             }
1684           }
1685 #endif
1686 
1687           /* If this is the table being altered, fix any table refs in CHECK
1688           ** expressions. Also update the name that appears right after the
1689           ** "CREATE [VIRTUAL] TABLE" bit. */
1690           if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1691             sCtx.pTab = pTab;
1692             if( isLegacy==0 ){
1693               sqlite3WalkExprList(&sWalker, pTab->pCheck);
1694             }
1695             renameTokenFind(&sParse, &sCtx, pTab->zName);
1696           }
1697         }
1698       }
1699 
1700       else if( sParse.pNewIndex ){
1701         renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1702         if( isLegacy==0 ){
1703           sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1704         }
1705       }
1706 
1707 #ifndef SQLITE_OMIT_TRIGGER
1708       else{
1709         Trigger *pTrigger = sParse.pNewTrigger;
1710         TriggerStep *pStep;
1711         if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1712             && sCtx.pTab->pSchema==pTrigger->pTabSchema
1713           ){
1714           renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1715         }
1716 
1717         if( isLegacy==0 ){
1718           rc = renameResolveTrigger(&sParse);
1719           if( rc==SQLITE_OK ){
1720             renameWalkTrigger(&sWalker, pTrigger);
1721             for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1722               if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1723                 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1724               }
1725             }
1726           }
1727         }
1728       }
1729 #endif
1730     }
1731 
1732     if( rc==SQLITE_OK ){
1733       rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1734     }
1735     if( rc!=SQLITE_OK ){
1736       if( sParse.zErrMsg ){
1737         renameColumnParseError(context, "", argv[1], argv[2], &sParse);
1738       }else{
1739         sqlite3_result_error_code(context, rc);
1740       }
1741     }
1742 
1743     renameParseCleanup(&sParse);
1744     renameTokenFree(db, sCtx.pList);
1745     sqlite3BtreeLeaveAll(db);
1746 #ifndef SQLITE_OMIT_AUTHORIZATION
1747     db->xAuth = xAuth;
1748 #endif
1749   }
1750 
1751   return;
1752 }
1753 
1754 static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1755   if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1756     renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1757   }
1758   return WRC_Continue;
1759 }
1760 
1761 /*
1762 ** The implementation of an SQL scalar function that rewrites DDL statements
1763 ** so that any string literals that use double-quotes are modified so that
1764 ** they use single quotes.
1765 **
1766 ** Two arguments must be passed:
1767 **
1768 **   0: Database name ("main", "temp" etc.).
1769 **   1: SQL statement to edit.
1770 **
1771 ** The returned value is the modified SQL statement. For example, given
1772 ** the database schema:
1773 **
1774 **   CREATE TABLE t1(a, b, c);
1775 **
1776 **   SELECT sqlite_rename_quotefix('main',
1777 **       'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1778 **   );
1779 **
1780 ** returns the string:
1781 **
1782 **   CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1783 */
1784 static void renameQuotefixFunc(
1785   sqlite3_context *context,
1786   int NotUsed,
1787   sqlite3_value **argv
1788 ){
1789   sqlite3 *db = sqlite3_context_db_handle(context);
1790   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1791   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1792 
1793 #ifndef SQLITE_OMIT_AUTHORIZATION
1794   sqlite3_xauth xAuth = db->xAuth;
1795   db->xAuth = 0;
1796 #endif
1797 
1798   sqlite3BtreeEnterAll(db);
1799 
1800   UNUSED_PARAMETER(NotUsed);
1801   if( zDb && zInput ){
1802     int rc;
1803     Parse sParse;
1804     rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1805 
1806     if( rc==SQLITE_OK ){
1807       RenameCtx sCtx;
1808       Walker sWalker;
1809 
1810       /* Walker to find tokens that need to be replaced. */
1811       memset(&sCtx, 0, sizeof(RenameCtx));
1812       memset(&sWalker, 0, sizeof(Walker));
1813       sWalker.pParse = &sParse;
1814       sWalker.xExprCallback = renameQuotefixExprCb;
1815       sWalker.xSelectCallback = renameColumnSelectCb;
1816       sWalker.u.pRename = &sCtx;
1817 
1818       if( sParse.pNewTable ){
1819         Select *pSelect = sParse.pNewTable->pSelect;
1820         if( pSelect ){
1821           pSelect->selFlags &= ~SF_View;
1822           sParse.rc = SQLITE_OK;
1823           sqlite3SelectPrep(&sParse, pSelect, 0);
1824           rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1825           if( rc==SQLITE_OK ){
1826             sqlite3WalkSelect(&sWalker, pSelect);
1827           }
1828         }else{
1829           int i;
1830           sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1831 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
1832           for(i=0; i<sParse.pNewTable->nCol; i++){
1833             sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1834           }
1835 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1836         }
1837       }else if( sParse.pNewIndex ){
1838         sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1839         sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1840       }else{
1841 #ifndef SQLITE_OMIT_TRIGGER
1842         rc = renameResolveTrigger(&sParse);
1843         if( rc==SQLITE_OK ){
1844           renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1845         }
1846 #endif /* SQLITE_OMIT_TRIGGER */
1847       }
1848 
1849       if( rc==SQLITE_OK ){
1850         rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1851       }
1852       renameTokenFree(db, sCtx.pList);
1853     }
1854     if( rc!=SQLITE_OK ){
1855       sqlite3_result_error_code(context, rc);
1856     }
1857     renameParseCleanup(&sParse);
1858   }
1859 
1860 #ifndef SQLITE_OMIT_AUTHORIZATION
1861   db->xAuth = xAuth;
1862 #endif
1863 
1864   sqlite3BtreeLeaveAll(db);
1865 }
1866 
1867 /*
1868 ** An SQL user function that checks that there are no parse or symbol
1869 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1870 ** After an ALTER TABLE .. RENAME operation is performed and the schema
1871 ** reloaded, this function is called on each SQL statement in the schema
1872 ** to ensure that it is still usable.
1873 **
1874 **   0: Database name ("main", "temp" etc.).
1875 **   1: SQL statement.
1876 **   2: Object type ("view", "table", "trigger" or "index").
1877 **   3: Object name.
1878 **   4: True if object is from temp schema.
1879 **   5: "when" part of error message.
1880 **   6: True to disable the DQS quirk when parsing SQL.
1881 **
1882 ** Unless it finds an error, this function normally returns NULL. However, it
1883 ** returns integer value 1 if:
1884 **
1885 **   * the SQL argument creates a trigger, and
1886 **   * the table that the trigger is attached to is in database zDb.
1887 */
1888 static void renameTableTest(
1889   sqlite3_context *context,
1890   int NotUsed,
1891   sqlite3_value **argv
1892 ){
1893   sqlite3 *db = sqlite3_context_db_handle(context);
1894   char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1895   char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1896   int bTemp = sqlite3_value_int(argv[4]);
1897   int isLegacy = (db->flags & SQLITE_LegacyAlter);
1898   char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
1899   int bNoDQS = sqlite3_value_int(argv[6]);
1900 
1901 #ifndef SQLITE_OMIT_AUTHORIZATION
1902   sqlite3_xauth xAuth = db->xAuth;
1903   db->xAuth = 0;
1904 #endif
1905 
1906   UNUSED_PARAMETER(NotUsed);
1907 
1908   if( zDb && zInput ){
1909     int rc;
1910     Parse sParse;
1911     int flags = db->flags;
1912     if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
1913     rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
1914     db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
1915     if( rc==SQLITE_OK ){
1916       if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
1917         NameContext sNC;
1918         memset(&sNC, 0, sizeof(sNC));
1919         sNC.pParse = &sParse;
1920         sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1921         if( sParse.nErr ) rc = sParse.rc;
1922       }
1923 
1924       else if( sParse.pNewTrigger ){
1925         if( isLegacy==0 ){
1926           rc = renameResolveTrigger(&sParse);
1927         }
1928         if( rc==SQLITE_OK ){
1929           int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1930           int i2 = sqlite3FindDbName(db, zDb);
1931           if( i1==i2 ) sqlite3_result_int(context, 1);
1932         }
1933       }
1934     }
1935 
1936     if( rc!=SQLITE_OK && zWhen ){
1937       renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
1938     }
1939     renameParseCleanup(&sParse);
1940   }
1941 
1942 #ifndef SQLITE_OMIT_AUTHORIZATION
1943   db->xAuth = xAuth;
1944 #endif
1945 }
1946 
1947 /*
1948 ** The implementation of internal UDF sqlite_drop_column().
1949 **
1950 ** Arguments:
1951 **
1952 **  argv[0]: An integer - the index of the schema containing the table
1953 **  argv[1]: CREATE TABLE statement to modify.
1954 **  argv[2]: An integer - the index of the column to remove.
1955 **
1956 ** The value returned is a string containing the CREATE TABLE statement
1957 ** with column argv[2] removed.
1958 */
1959 static void dropColumnFunc(
1960   sqlite3_context *context,
1961   int NotUsed,
1962   sqlite3_value **argv
1963 ){
1964   sqlite3 *db = sqlite3_context_db_handle(context);
1965   int iSchema = sqlite3_value_int(argv[0]);
1966   const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1967   int iCol = sqlite3_value_int(argv[2]);
1968   const char *zDb = db->aDb[iSchema].zDbSName;
1969   int rc;
1970   Parse sParse;
1971   RenameToken *pCol;
1972   Table *pTab;
1973   const char *zEnd;
1974   char *zNew = 0;
1975 
1976 #ifndef SQLITE_OMIT_AUTHORIZATION
1977   sqlite3_xauth xAuth = db->xAuth;
1978   db->xAuth = 0;
1979 #endif
1980 
1981   UNUSED_PARAMETER(NotUsed);
1982   rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
1983   if( rc!=SQLITE_OK ) goto drop_column_done;
1984   pTab = sParse.pNewTable;
1985   if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
1986     /* This can happen if the sqlite_schema table is corrupt */
1987     rc = SQLITE_CORRUPT_BKPT;
1988     goto drop_column_done;
1989   }
1990 
1991   pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
1992   if( iCol<pTab->nCol-1 ){
1993     RenameToken *pEnd;
1994     pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
1995     zEnd = (const char*)pEnd->t.z;
1996   }else{
1997     zEnd = (const char*)&zSql[pTab->addColOffset];
1998     while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
1999   }
2000 
2001   zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
2002   sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2003   sqlite3_free(zNew);
2004 
2005 drop_column_done:
2006   renameParseCleanup(&sParse);
2007 #ifndef SQLITE_OMIT_AUTHORIZATION
2008   db->xAuth = xAuth;
2009 #endif
2010   if( rc!=SQLITE_OK ){
2011     sqlite3_result_error_code(context, rc);
2012   }
2013 }
2014 
2015 /*
2016 ** This function is called by the parser upon parsing an
2017 **
2018 **     ALTER TABLE pSrc DROP COLUMN pName
2019 **
2020 ** statement. Argument pSrc contains the possibly qualified name of the
2021 ** table being edited, and token pName the name of the column to drop.
2022 */
2023 void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
2024   sqlite3 *db = pParse->db;       /* Database handle */
2025   Table *pTab;                    /* Table to modify */
2026   int iDb;                        /* Index of db containing pTab in aDb[] */
2027   const char *zDb;                /* Database containing pTab ("main" etc.) */
2028   char *zCol = 0;                 /* Name of column to drop */
2029   int iCol;                       /* Index of column zCol in pTab->aCol[] */
2030 
2031   /* Look up the table being altered. */
2032   assert( pParse->pNewTable==0 );
2033   assert( sqlite3BtreeHoldsAllMutexes(db) );
2034   if( NEVER(db->mallocFailed) ) goto exit_drop_column;
2035   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2036   if( !pTab ) goto exit_drop_column;
2037 
2038   /* Make sure this is not an attempt to ALTER a view, virtual table or
2039   ** system table. */
2040   if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2041   if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
2042 
2043   /* Find the index of the column being dropped. */
2044   zCol = sqlite3NameFromToken(db, pName);
2045   if( zCol==0 ){
2046     assert( db->mallocFailed );
2047     goto exit_drop_column;
2048   }
2049   iCol = sqlite3ColumnIndex(pTab, zCol);
2050   if( iCol<0 ){
2051     sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2052     goto exit_drop_column;
2053   }
2054 
2055   /* Do not allow the user to drop a PRIMARY KEY column or a column
2056   ** constrained by a UNIQUE constraint.  */
2057   if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2058     sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2059         (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2060         zCol
2061     );
2062     goto exit_drop_column;
2063   }
2064 
2065   /* Do not allow the number of columns to go to zero */
2066   if( pTab->nCol<=1 ){
2067     sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2068     goto exit_drop_column;
2069   }
2070 
2071   /* Edit the sqlite_schema table */
2072   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2073   assert( iDb>=0 );
2074   zDb = db->aDb[iDb].zDbSName;
2075   renameTestSchema(pParse, zDb, iDb==1, "", 0);
2076   renameFixQuotes(pParse, zDb, iDb==1);
2077   sqlite3NestedParse(pParse,
2078       "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
2079       "sql = sqlite_drop_column(%d, sql, %d) "
2080       "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
2081       , zDb, iDb, iCol, pTab->zName
2082   );
2083 
2084   /* Drop and reload the database schema. */
2085   renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
2086   renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
2087 
2088   /* Edit rows of table on disk */
2089   if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
2090     int i;
2091     int addr;
2092     int reg;
2093     int regRec;
2094     Index *pPk = 0;
2095     int nField = 0;               /* Number of non-virtual columns after drop */
2096     int iCur;
2097     Vdbe *v = sqlite3GetVdbe(pParse);
2098     iCur = pParse->nTab++;
2099     sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
2100     addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2101     reg = ++pParse->nMem;
2102     if( HasRowid(pTab) ){
2103       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
2104       pParse->nMem += pTab->nCol;
2105     }else{
2106       pPk = sqlite3PrimaryKeyIndex(pTab);
2107       pParse->nMem += pPk->nColumn;
2108       for(i=0; i<pPk->nKeyCol; i++){
2109         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2110       }
2111       nField = pPk->nKeyCol;
2112     }
2113     regRec = ++pParse->nMem;
2114     for(i=0; i<pTab->nCol; i++){
2115       if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2116         int regOut;
2117         if( pPk ){
2118           int iPos = sqlite3TableColumnToIndex(pPk, i);
2119           int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
2120           if( iPos<pPk->nKeyCol ) continue;
2121           regOut = reg+1+iPos-(iPos>iColPos);
2122         }else{
2123           regOut = reg+1+nField;
2124         }
2125         if( i==pTab->iPKey ){
2126           sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2127         }else{
2128           sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2129         }
2130         nField++;
2131       }
2132     }
2133     sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2134     if( pPk ){
2135       sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2136     }else{
2137       sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2138     }
2139     sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
2140 
2141     sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
2142     sqlite3VdbeJumpHere(v, addr);
2143   }
2144 
2145 exit_drop_column:
2146   sqlite3DbFree(db, zCol);
2147   sqlite3SrcListDelete(db, pSrc);
2148 }
2149 
2150 /*
2151 ** Register built-in functions used to help implement ALTER TABLE
2152 */
2153 void sqlite3AlterFunctions(void){
2154   static FuncDef aAlterTableFuncs[] = {
2155     INTERNAL_FUNCTION(sqlite_rename_column,  9, renameColumnFunc),
2156     INTERNAL_FUNCTION(sqlite_rename_table,   7, renameTableFunc),
2157     INTERNAL_FUNCTION(sqlite_rename_test,    7, renameTableTest),
2158     INTERNAL_FUNCTION(sqlite_drop_column,    3, dropColumnFunc),
2159     INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
2160   };
2161   sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2162 }
2163 #endif  /* SQLITE_ALTER_TABLE */
2164