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