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