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