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