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