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