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