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