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