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