blob: 0f50f195e73e372a133cfe845ea519135a3cd5bd [file] [log] [blame]
drhd0e4a6c2005-02-15 20:47:57 +00001/*
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.
drhd0e4a6c2005-02-15 20:47:57 +000014*/
15#include "sqliteInt.h"
16
drh1f01ec12005-02-15 21:36:18 +000017/*
18** The code in this file only exists if we are not omitting the
19** ALTER TABLE logic from the build.
20*/
drhd0e4a6c2005-02-15 20:47:57 +000021#ifndef SQLITE_OMIT_ALTERTABLE
drh1f01ec12005-02-15 21:36:18 +000022
drh1f01ec12005-02-15 21:36:18 +000023/*
danbe535002011-04-01 15:15:58 +000024** 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*/
dan397a78d2018-12-18 20:31:14 +000031static int isAlterableTable(Parse *pParse, Table *pTab){
32 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
33#ifndef SQLITE_OMIT_VIRTUALTABLE
drh070ae3b2019-11-16 13:51:31 +000034 || ( (pTab->tabFlags & TF_Shadow)!=0
35 && sqlite3ReadOnlyShadowTables(pParse->db)
dan397a78d2018-12-18 20:31:14 +000036 )
37#endif
38 ){
39 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danbe535002011-04-01 15:15:58 +000040 return 1;
41 }
42 return 0;
43}
44
dan09236502018-09-01 16:05:50 +000045/*
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*/
drh16b870d2018-09-12 15:51:56 +000052static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
drh351ae772021-02-15 13:17:19 +000053 pParse->colNamesSet = 1;
dan9d324822018-08-30 20:03:44 +000054 sqlite3NestedParse(pParse,
55 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000056 "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000057 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000058 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000059 " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
drh346a70c2020-06-15 20:27:35 +000060 zDb,
dan9d324822018-08-30 20:03:44 +000061 zDb, bTemp
62 );
63
64 if( bTemp==0 ){
65 sqlite3NestedParse(pParse,
66 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000067 "FROM temp." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000068 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000069 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000070 " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
drh346a70c2020-06-15 20:27:35 +000071 zDb
dan9d324822018-08-30 20:03:44 +000072 );
73 }
74}
75
danbe535002011-04-01 15:15:58 +000076/*
dan09236502018-09-01 16:05:50 +000077** Generate code to reload the schema for database iDb. And, if iDb!=1, for
78** the temp database as well.
79*/
drh16b870d2018-09-12 15:51:56 +000080static void renameReloadSchema(Parse *pParse, int iDb){
dan09236502018-09-01 16:05:50 +000081 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/*
drhd0e4a6c2005-02-15 20:47:57 +000090** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
91** command.
92*/
93void 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 */
drhd0e4a6c2005-02-15 20:47:57 +0000102 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000103 int nTabName; /* Number of UTF-8 characters in zTabName */
104 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000105 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000106 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000107 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000108
drh8257aa82017-07-26 19:59:13 +0000109 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000110 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000111 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000112 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000113
dan41fb5cd2012-10-04 19:33:00 +0000114 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000115 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000116 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000117 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000118 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000119
120 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000121 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000122 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 */
drh3d863b52020-05-14 21:16:52 +0000127 if( sqlite3FindTable(db, zName, zDb)
128 || sqlite3FindIndex(db, zName, zDb)
129 || sqlite3IsShadowTableOf(db, pTab, zName)
130 ){
drhd0e4a6c2005-02-15 20:47:57 +0000131 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 */
dan397a78d2018-12-18 20:31:14 +0000139 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000140 goto exit_rename_table;
141 }
drhc5a93d42019-08-12 00:08:07 +0000142 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
143 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000144 }
145
danielk197761116ae2007-12-13 08:15:30 +0000146#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
drhd0e4a6c2005-02-15 20:47:57 +0000153#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
danielk1977182c4ba2007-06-27 15:53:34 +0000160#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000161 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
162 goto exit_rename_table;
163 }
danielk1977595a5232009-07-24 17:58:53 +0000164 if( IsVirtual(pTab) ){
165 pVTab = sqlite3GetVTable(db, pTab);
166 if( pVTab->pVtab->pModule->xRename==0 ){
167 pVTab = 0;
168 }
danielk1977182c4ba2007-06-27 15:53:34 +0000169 }
170#endif
171
dan1f3b2842019-03-15 16:17:32 +0000172 /* 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. */
drhd0e4a6c2005-02-15 20:47:57 +0000176 v = sqlite3GetVdbe(pParse);
177 if( v==0 ){
178 goto exit_rename_table;
179 }
dan1f3b2842019-03-15 16:17:32 +0000180 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000181
drh4e5dd852007-05-15 03:56:49 +0000182 /* figure out how many UTF-8 characters are in zName */
183 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000184 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000185
danc9461ec2018-08-29 21:00:16 +0000186 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
187 ** the schema to use the new table name. */
188 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000189 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan65372fa2018-09-03 20:05:15 +0000190 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000191 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000192 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
drh346a70c2020-06-15 20:27:35 +0000193 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000194 );
dan432cc5b2009-09-26 17:51:48 +0000195
drh1e32bed2020-06-19 13:33:53 +0000196 /* Update the tbl_name and name columns of the sqlite_schema table
danc9461ec2018-08-29 21:00:16 +0000197 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000198 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000199 "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
drhd0e4a6c2005-02-15 20:47:57 +0000200 "tbl_name = %Q, "
201 "name = CASE "
202 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000203 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
204 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000205 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000206 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000207 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000208 "(type='table' OR type='index' OR type='trigger');",
drh346a70c2020-06-15 20:27:35 +0000209 zDb,
danc9461ec2018-08-29 21:00:16 +0000210 zName, zName, zName,
211 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000212 );
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,
drh8e5b5f82008-02-09 14:30:29 +0000220 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000221 zDb, zName, pTab->zName);
222 }
223#endif
224
danc9461ec2018-08-29 21:00:16 +0000225 /* 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 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000229 sqlite3NestedParse(pParse,
drh1e32bed2020-06-19 13:33:53 +0000230 "UPDATE sqlite_temp_schema SET "
dan65372fa2018-09-03 20:05:15 +0000231 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000232 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000233 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
234 " sqlite_rename_test(%Q, sql, type, name, 1) "
235 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000236 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000237 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000238 }
drhd0e4a6c2005-02-15 20:47:57 +0000239
dan34566c42018-09-20 17:21:21 +0000240 /* 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);
dan34566c42018-09-20 17:21:21 +0000250 }
251#endif
252
dan09236502018-09-01 16:05:50 +0000253 renameReloadSchema(pParse, iDb);
dan9d324822018-08-30 20:03:44 +0000254 renameTestSchema(pParse, zDb, iDb==1);
255
drhd0e4a6c2005-02-15 20:47:57 +0000256exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000257 sqlite3SrcListDelete(db, pSrc);
258 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000259 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000260}
danielk197719a8e7e2005-03-17 05:03:38 +0000261
drhd3001712009-05-12 17:46:53 +0000262/*
drh9e5fdc42020-05-08 19:02:21 +0000263** Write code that will raise an error if the table described by
264** zDb and zTab is not empty.
265*/
266static 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/*
danielk197719a8e7e2005-03-17 05:03:38 +0000279** 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*/
286void 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 */
drh17435752007-08-16 04:30:38 +0000295 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000296 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000297 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000298
danielk1977f150c9d2008-10-30 17:21:12 +0000299 db = pParse->db;
300 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000301 pNew = pParse->pNewTable;
302 assert( pNew );
303
drh1fee73e2007-08-29 04:00:57 +0000304 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000305 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000306 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000307 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000308 pCol = &pNew->aCol[pNew->nCol-1];
309 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000310 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000311 assert( pTab );
312
drh81f2ccd2006-01-31 14:28:44 +0000313#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
danielk197719a8e7e2005-03-17 05:03:38 +0000320
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 */
drha371ace2012-09-13 14:22:47 +0000325 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000326 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
327 return;
328 }
329 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000330 sqlite3ErrorMsg(pParse,
331 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000332 return;
333 }
drhc27ea2a2019-10-16 20:05:56 +0000334 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 ){
drh9e5fdc42020-05-08 19:02:21 +0000344 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000345 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000346 }
347 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000348 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000349 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000350 }
351
drh9e5fdc42020-05-08 19:02:21 +0000352
drhc27ea2a2019-10-16 20:05:56 +0000353 /* 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 ){
drh9e5fdc42020-05-08 19:02:21 +0000366 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
367 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000368 }
369 sqlite3ValueFree(pVal);
370 }
drh035f6d92019-10-24 01:04:10 +0000371 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000372 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000373 }
374
danielk197719a8e7e2005-03-17 05:03:38 +0000375
376 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000377 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000378 if( zCol ){
379 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000380 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000381 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000382 *zEnd-- = '\0';
383 }
drh8257aa82017-07-26 19:59:13 +0000384 db->mDbFlags |= DBFLAG_PreferBuiltin;
drh37114fb2021-01-01 20:04:34 +0000385 /* substr() operations on characters, but addColOffset is in bytes. So we
386 ** have to use printf() to translate between these units: */
danielk197719a8e7e2005-03-17 05:03:38 +0000387 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000388 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000389 "sql = printf('%%.%ds, ',sql) || %Q"
390 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000391 "WHERE type = 'table' AND name = %Q",
drh37114fb2021-01-01 20:04:34 +0000392 zDb, pNew->addColOffset, zCol, pNew->addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000393 zTab
394 );
drh633e6d52008-07-28 19:34:53 +0000395 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000396 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000397 }
398
drh86396212016-07-14 19:13:11 +0000399 /* 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.
danielk197719a8e7e2005-03-17 05:03:38 +0000402 */
dan09236502018-09-01 16:05:50 +0000403 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 }
danielk197719a8e7e2005-03-17 05:03:38 +0000414
dan09236502018-09-01 16:05:50 +0000415 /* Reload the table definition */
416 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000417}
418
drhfdd6e852005-12-16 01:06:16 +0000419/*
danielk197719a8e7e2005-03-17 05:03:38 +0000420** 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*/
434void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
435 Table *pNew;
436 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000437 int iDb;
438 int i;
439 int nAlloc;
drh17435752007-08-16 04:30:38 +0000440 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000441
442 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000443 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000444 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000445 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000446 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000447 if( !pTab ) goto exit_begin_add_column;
448
danielk19775ee9d692006-06-21 12:36:25 +0000449#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
danielk197719a8e7e2005-03-17 05:03:38 +0000456 /* 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 }
dan397a78d2018-12-18 20:31:14 +0000461 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000462 goto exit_begin_add_column;
463 }
danielk197719a8e7e2005-03-17 05:03:38 +0000464
dan03e025e2019-10-07 18:43:21 +0000465 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000466 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000467 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000468
469 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000470 ** 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.
danielk197719a8e7e2005-03-17 05:03:38 +0000475 */
drh17435752007-08-16 04:30:38 +0000476 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000477 if( !pNew ) goto exit_begin_add_column;
478 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000479 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000480 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000481 assert( pNew->nCol>0 );
482 nAlloc = (((pNew->nCol-1)/8)*8)+8;
483 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000484 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000485 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000486 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000487 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000488 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];
drh17435752007-08-16 04:30:38 +0000493 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000494 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000495 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000496 pCol->pDflt = 0;
497 }
drh17435752007-08-16 04:30:38 +0000498 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000499 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000500 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000501
danielk197719a8e7e2005-03-17 05:03:38 +0000502exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000503 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000504 return;
505}
dancf8f2892018-08-09 20:47:01 +0000506
drh4a2c7472018-08-13 15:09:48 +0000507/*
dan9d705572018-08-20 16:16:05 +0000508** 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)
516static int isRealTable(Parse *pParse, Table *pTab){
517 const char *zType = 0;
518#ifndef SQLITE_OMIT_VIEW
519 if( pTab->pSelect ){
520 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000521 }
dan9d705572018-08-20 16:16:05 +0000522#endif
523#ifndef SQLITE_OMIT_VIRTUALTABLE
524 if( IsVirtual(pTab) ){
525 zType = "virtual table";
526 }
527#endif
528 if( zType ){
529 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000530 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000531 );
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/*
drh4a2c7472018-08-13 15:09:48 +0000541** Handles the following parser reduction:
542**
543** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
544*/
dancf8f2892018-08-09 20:47:01 +0000545void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000546 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 */
dancf8f2892018-08-09 20:47:01 +0000550){
drh4a2c7472018-08-13 15:09:48 +0000551 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000552 Table *pTab; /* Table being updated */
553 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000554 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 */
dancf8f2892018-08-09 20:47:01 +0000559
drh4a2c7472018-08-13 15:09:48 +0000560 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000561 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
562 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000563
564 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000565 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000566 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000567
568 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000569 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
570 assert( iSchema>=0 );
571 zDb = db->aDb[iSchema].zDbSName;
572
drh0d019b92018-08-25 16:14:46 +0000573#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
drh4a2c7472018-08-13 15:09:48 +0000580 /* 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 */
dancf8f2892018-08-09 20:47:01 +0000582 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
drh4a2c7472018-08-13 15:09:48 +0000592 /* Do the rename operation using a recursive UPDATE statement that
593 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000594 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000595 */
dan1f3b2842019-03-15 16:17:32 +0000596 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000597 zNew = sqlite3NameFromToken(db, pNew);
598 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000599 assert( pNew->n>0 );
600 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000601 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000602 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000603 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000604 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
605 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000606 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000607 zDb,
danb87a9a82018-09-01 20:23:28 +0000608 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000609 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000610 );
611
dan9d324822018-08-30 20:03:44 +0000612 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000613 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000614 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000615 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000616 zDb, pTab->zName, iCol, zNew, bQuote
617 );
618
dane325ffe2018-08-11 13:40:20 +0000619 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000620 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000621 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000622
dancf8f2892018-08-09 20:47:01 +0000623 exit_rename_column:
624 sqlite3SrcListDelete(db, pSrc);
625 sqlite3DbFree(db, zOld);
626 sqlite3DbFree(db, zNew);
627 return;
628}
629
drh4a2c7472018-08-13 15:09:48 +0000630/*
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.
dan07e95232018-08-21 16:32:53 +0000639** Each new object is created by sqlite3RenameTokenMap().
640** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000641** 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*/
dancf8f2892018-08-09 20:47:01 +0000647struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000648 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 */
dancf8f2892018-08-09 20:47:01 +0000651};
652
drh4a2c7472018-08-13 15:09:48 +0000653/*
654** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
655** down into the Walker.
656*/
dan5496d6a2018-08-13 17:14:26 +0000657typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000658struct 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 */
dan987db762018-08-14 20:18:50 +0000662 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000663 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000664};
665
dan8900a482018-09-05 14:36:05 +0000666#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*/
drh16b870d2018-09-12 15:51:56 +0000690static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000691 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 }
danc9461ec2018-08-29 21:00:16 +0000699 }
700 }
701}
dan8900a482018-09-05 14:36:05 +0000702#else
703# define renameTokenCheckAll(x,y)
704#endif
danc9461ec2018-08-29 21:00:16 +0000705
drh4a2c7472018-08-13 15:09:48 +0000706/*
drh49b269e2018-11-26 15:00:25 +0000707** Remember that the parser tree element pPtr was created using
708** the token pToken.
dan07e95232018-08-21 16:32:53 +0000709**
drh49b269e2018-11-26 15:00:25 +0000710** 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.
drh4a2c7472018-08-13 15:09:48 +0000717*/
dan07e95232018-08-21 16:32:53 +0000718void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000719 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000720 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000721 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000722 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000723 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 }
dancf8f2892018-08-09 20:47:01 +0000730 }
danc9461ec2018-08-29 21:00:16 +0000731
dand145e5f2018-08-21 08:29:48 +0000732 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000733}
734
drh4a2c7472018-08-13 15:09:48 +0000735/*
dan07e95232018-08-21 16:32:53 +0000736** 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.
drh4a2c7472018-08-13 15:09:48 +0000739*/
dan07e95232018-08-21 16:32:53 +0000740void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000741 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000742 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000743 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000744 if( p->p==pFrom ){
745 p->p = pTo;
746 break;
747 }
748 }
dancf8f2892018-08-09 20:47:01 +0000749}
750
drh4a2c7472018-08-13 15:09:48 +0000751/*
dan8900a482018-09-05 14:36:05 +0000752** Walker callback used by sqlite3RenameExprUnmap().
753*/
754static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
755 Parse *pParse = pWalker->pParse;
756 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
757 return WRC_Continue;
758}
759
760/*
dan8f407622019-12-04 14:26:38 +0000761** Iterate through the Select objects that are part of WITH clauses attached
762** to select statement pSelect.
763*/
764static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000765 With *pWith = pSelect->pWith;
766 if( pWith ){
dan8f407622019-12-04 14:26:38 +0000767 int i;
drh646975c2019-12-17 12:03:30 +0000768 for(i=0; i<pWith->nCte; i++){
769 Select *p = pWith->a[i].pSelect;
dan8f407622019-12-04 14:26:38 +0000770 NameContext sNC;
771 memset(&sNC, 0, sizeof(sNC));
772 sNC.pParse = pWalker->pParse;
773 sqlite3SelectPrep(sNC.pParse, p, &sNC);
774 sqlite3WalkSelect(pWalker, p);
drh646975c2019-12-17 12:03:30 +0000775 sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
dan8f407622019-12-04 14:26:38 +0000776 }
777 }
778}
779
780/*
danfb99e382020-04-03 11:20:40 +0000781** Unmap all tokens in the IdList object passed as the second argument.
782*/
783static 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/*
dan0b277a92019-06-11 12:03:10 +0000796** Walker callback used by sqlite3RenameExprUnmap().
797*/
798static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000799 Parse *pParse = pWalker->pParse;
800 int i;
drhd63b69b2019-12-04 15:08:58 +0000801 if( pParse->nErr ) return WRC_Abort;
drh2bc5cf92019-12-09 19:29:10 +0000802 if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
drhbdf4cf02019-06-15 15:21:49 +0000803 if( ALWAYS(p->pEList) ){
804 ExprList *pList = p->pEList;
805 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000806 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000807 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000808 }
809 }
810 }
drh2c3f4652019-06-11 16:43:58 +0000811 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000812 SrcList *pSrc = p->pSrc;
813 for(i=0; i<pSrc->nSrc; i++){
814 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000815 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000816 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000817 }
818 }
dan8f407622019-12-04 14:26:38 +0000819
820 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000821 return WRC_Continue;
822}
823
824/*
dan8900a482018-09-05 14:36:05 +0000825** Remove all nodes that are part of expression pExpr from the rename list.
826*/
827void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000828 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000829 Walker sWalker;
830 memset(&sWalker, 0, sizeof(Walker));
831 sWalker.pParse = pParse;
832 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000833 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000834 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000835 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000836 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000837}
838
839/*
dane8ab40d2018-09-12 08:51:48 +0000840** Remove all nodes that are part of expression-list pEList from the
841** rename list.
842*/
843void 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++){
drh9fc1b9a2020-01-02 22:23:01 +0000852 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000853 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
854 }
dane8ab40d2018-09-12 08:51:48 +0000855 }
856 }
857}
858
859/*
drh4a2c7472018-08-13 15:09:48 +0000860** Free the list of RenameToken objects given in the second argument
861*/
dancf8f2892018-08-09 20:47:01 +0000862static 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
dan987db762018-08-14 20:18:50 +0000871/*
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*/
877static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000878 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000879 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000880 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
881 if( (*pp)->p==pPtr ){
882 RenameToken *pToken = *pp;
883 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000884 pToken->pNext = pCtx->pList;
885 pCtx->pList = pToken;
886 pCtx->nList++;
887 break;
dancf8f2892018-08-09 20:47:01 +0000888 }
889 }
dancf8f2892018-08-09 20:47:01 +0000890}
891
dan24fedb92018-08-18 17:35:38 +0000892/*
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*/
dan987db762018-08-14 20:18:50 +0000897static int renameColumnSelectCb(Walker *pWalker, Select *p){
dan38096962019-12-09 08:13:43 +0000898 if( p->selFlags & SF_View ) return WRC_Prune;
danea412512018-12-05 13:49:04 +0000899 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000900 return WRC_Continue;
901}
902
dan987db762018-08-14 20:18:50 +0000903/*
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*/
dancf8f2892018-08-09 20:47:01 +0000912static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000913 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000914 if( pExpr->op==TK_TRIGGER
915 && pExpr->iColumn==p->iCol
916 && pWalker->pParse->pTriggerTab==p->pTab
917 ){
dan5be60c52018-08-15 20:28:39 +0000918 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000919 }else if( pExpr->op==TK_COLUMN
920 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000921 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000922 ){
dan5496d6a2018-08-13 17:14:26 +0000923 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000924 }
925 return WRC_Continue;
926}
927
dan987db762018-08-14 20:18:50 +0000928/*
929** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000930** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000931** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000932** RenameContext. "Last" means the last RenameToken encountered when
933** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000934** return all column name tokens in the order that they are encountered
935** in the SQL statement.
936*/
dan5496d6a2018-08-13 17:14:26 +0000937static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000938 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
dan6fe7f232018-08-10 19:19:33 +0000951/*
dan24fedb92018-08-18 17:35:38 +0000952** 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*/
danb0137382018-08-20 20:01:01 +0000958static void renameColumnParseError(
959 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000960 int bPost,
danb0137382018-08-20 20:01:01 +0000961 sqlite3_value *pType,
962 sqlite3_value *pObject,
963 Parse *pParse
964){
drh79a5ee92018-08-23 19:32:04 +0000965 const char *zT = (const char*)sqlite3_value_text(pType);
966 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000967 char *zErr;
danb0137382018-08-20 20:01:01 +0000968
dan0d5fa6b2018-08-24 17:55:49 +0000969 zErr = sqlite3_mprintf("error in %s %s%s: %s",
970 zT, zN, (bPost ? " after rename" : ""),
971 pParse->zErrMsg
972 );
dan24fedb92018-08-18 17:35:38 +0000973 sqlite3_result_error(pCtx, zErr, -1);
974 sqlite3_free(zErr);
975}
976
977/*
dan06249392018-08-21 15:06:59 +0000978** 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*/
983static 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++){
drh41cee662019-12-12 20:22:34 +0000992 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +0000993 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
994 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +0000995 && 0==sqlite3_stricmp(zName, zOld)
996 ){
dan06249392018-08-21 15:06:59 +0000997 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*/
1008static 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
danfb99e382020-04-03 11:20:40 +00001025
dandd1a9c82018-09-05 08:28:30 +00001026/*
1027** Parse the SQL statement zSql using Parse object (*p). The Parse object
1028** is initialized by this function before it is used.
1029*/
danc9461ec2018-08-29 21:00:16 +00001030static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001031 Parse *p, /* Memory to use for Parse object */
1032 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001033 sqlite3 *db, /* Database handle */
1034 const char *zSql, /* SQL to parse */
1035 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001036){
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));
dane6dc1e52019-12-05 14:31:43 +00001046 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001047 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 );
danc9461ec2018-08-29 21:00:16 +00001052 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
dandd1a9c82018-09-05 08:28:30 +00001076/*
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*/
danc9461ec2018-08-29 21:00:16 +00001085static 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. */
drhc753c212018-09-01 16:55:36 +00001105 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001106 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
dandd1a9c82018-09-05 08:28:30 +00001161/*
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*/
drha7c74002020-07-18 18:44:59 +00001167static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001168 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001169 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001170 TriggerStep *pStep;
1171 NameContext sNC;
1172 int rc = SQLITE_OK;
1173
1174 memset(&sNC, 0, sizeof(sNC));
1175 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001176 assert( pNew->pTabSchema );
1177 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1178 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1179 );
1180 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001181 /* 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) ){
dan5351e882018-10-01 07:04:12 +00001184 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1185 }
danc9461ec2018-08-29 21:00:16 +00001186
1187 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001188 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001189 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001190 }
1191
dand5e6fef2018-09-07 15:50:31 +00001192 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001193 if( pStep->pSelect ){
1194 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1195 if( pParse->nErr ) rc = pParse->rc;
1196 }
dand5e6fef2018-09-07 15:50:31 +00001197 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001198 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1199 if( pSrc ){
1200 int i;
drha3e64952020-08-12 16:19:12 +00001201 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
dane7877b22020-07-14 19:51:01 +00001202 struct SrcList_item *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001203 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001204 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);
dane7877b22020-07-14 19:51:01 +00001210 }else{
dan7a39fae2020-10-31 16:33:01 +00001211 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 }
dane7877b22020-07-14 19:51:01 +00001218 }
1219 }
1220 sNC.pSrcList = pSrc;
1221 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001222 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 );
dane7877b22020-07-14 19:51:01 +00001231 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001232 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 }
dan0e14e982019-01-18 16:06:18 +00001247 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001248 sqlite3SrcListDelete(db, pSrc);
1249 }else{
1250 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001251 }
1252 }
1253 }
1254 return rc;
1255}
1256
dandd1a9c82018-09-05 08:28:30 +00001257/*
1258** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1259** objects that are part of the trigger passed as the second argument.
1260*/
danc9461ec2018-08-29 21:00:16 +00001261static 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 }
dan7a39fae2020-10-31 16:33:01 +00001279 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 }
danc9461ec2018-08-29 21:00:16 +00001285 }
1286}
1287
dandd1a9c82018-09-05 08:28:30 +00001288/*
1289** Free the contents of Parse object (*pParse). Do not free the memory
1290** occupied by the Parse object itself.
1291*/
dan141e1192018-08-31 18:23:53 +00001292static void renameParseCleanup(Parse *pParse){
1293 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001294 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001295 if( pParse->pVdbe ){
1296 sqlite3VdbeFinalize(pParse->pVdbe);
1297 }
1298 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001299 while( (pIdx = pParse->pNewIndex)!=0 ){
1300 pParse->pNewIndex = pIdx->pNext;
1301 sqlite3FreeIndex(db, pIdx);
1302 }
dan141e1192018-08-31 18:23:53 +00001303 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1304 sqlite3DbFree(db, pParse->zErrMsg);
1305 renameTokenFree(db, pParse->pRename);
1306 sqlite3ParserReset(pParse);
1307}
1308
dan06249392018-08-21 15:06:59 +00001309/*
dan987db762018-08-14 20:18:50 +00001310** SQL function:
1311**
1312** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1313**
1314** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001315** 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
dan9d324822018-08-30 20:03:44 +00001321** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001322** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001323**
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.
drheea8eb62018-11-26 18:09:15 +00001329** It is only accessible to SQL created using sqlite3NestedParse(). It is
1330** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001331*/
dancf8f2892018-08-09 20:47:01 +00001332static void renameColumnFunc(
1333 sqlite3_context *context,
1334 int NotUsed,
1335 sqlite3_value **argv
1336){
1337 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001338 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001339 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001340 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]);
danb0137382018-08-20 20:01:01 +00001344 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001345 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001346 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001347 int rc;
dancf8f2892018-08-09 20:47:01 +00001348 Parse sParse;
1349 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001350 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001351 int i;
dan987db762018-08-14 20:18:50 +00001352 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001353#ifndef SQLITE_OMIT_AUTHORIZATION
1354 sqlite3_xauth xAuth = db->xAuth;
1355#endif
dancf8f2892018-08-09 20:47:01 +00001356
drh38d99642018-08-18 18:27:18 +00001357 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001358 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001359 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001360 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001361 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001362 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001363 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001364 if( pTab==0 || iCol>=pTab->nCol ){
1365 sqlite3BtreeLeaveAll(db);
1366 return;
1367 }
dan987db762018-08-14 20:18:50 +00001368 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001369 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001370 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001371
dan141e1192018-08-31 18:23:53 +00001372#ifndef SQLITE_OMIT_AUTHORIZATION
1373 db->xAuth = 0;
1374#endif
drhb2ab3dc2019-12-20 14:08:34 +00001375 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001376
dancf8f2892018-08-09 20:47:01 +00001377 /* Find tokens that need to be replaced. */
1378 memset(&sWalker, 0, sizeof(Walker));
1379 sWalker.pParse = &sParse;
1380 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001381 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001382 sWalker.u.pRename = &sCtx;
1383
dan0cbb0b12018-08-16 19:49:16 +00001384 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001385 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001386 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001387 Select *pSelect = sParse.pNewTable->pSelect;
1388 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001389 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001390 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001391 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001392 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1393 if( rc==SQLITE_OK ){
1394 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001395 }
dan987db762018-08-14 20:18:50 +00001396 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 );
dan0cbb0b12018-08-16 19:49:16 +00001402 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001403 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);
dancf8f2892018-08-09 20:47:01 +00001409 }
dan987db762018-08-14 20:18:50 +00001410 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1411 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1412 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1413 }
drh885eeb62019-01-09 02:02:24 +00001414 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1415 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1416 }
dan987db762018-08-14 20:18:50 +00001417 }
drhb9bcf7c2019-10-19 13:29:10 +00001418#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
dan987db762018-08-14 20:18:50 +00001423
1424 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1425 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001426 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001427 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 }
dan6fe7f232018-08-10 19:19:33 +00001434 }
dancf8f2892018-08-09 20:47:01 +00001435 }
1436 }
dan5496d6a2018-08-13 17:14:26 +00001437 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001438 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1439 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001440 }else{
dan5be60c52018-08-15 20:28:39 +00001441 /* A trigger */
1442 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001443 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001444 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001445
danc9461ec2018-08-29 21:00:16 +00001446 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1447 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001448 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001449 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001450 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001451 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1452 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001453 }
danc9461ec2018-08-29 21:00:16 +00001454 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1455 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001456 }
1457 }
1458 }
1459
dan5be60c52018-08-15 20:28:39 +00001460
1461 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001462 if( sParse.pTriggerTab==pTab ){
1463 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001464 }
dan5be60c52018-08-15 20:28:39 +00001465
danc9461ec2018-08-29 21:00:16 +00001466 /* Find tokens to edit in various expressions and selects */
1467 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001468 }
1469
dan987db762018-08-14 20:18:50 +00001470 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001471 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001472
drh5fc22cd2018-08-13 13:43:11 +00001473renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001474 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001475 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001476 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001477 }else{
1478 sqlite3_result_error_code(context, rc);
1479 }
1480 }
1481
dan141e1192018-08-31 18:23:53 +00001482 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001483 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001484#ifndef SQLITE_OMIT_AUTHORIZATION
1485 db->xAuth = xAuth;
1486#endif
drhda76adc2018-08-25 02:04:05 +00001487 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001488}
1489
dandd1a9c82018-09-05 08:28:30 +00001490/*
1491** Walker expression callback used by "RENAME TABLE".
1492*/
danc9461ec2018-08-29 21:00:16 +00001493static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1494 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001495 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1496 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001497 }
1498 return WRC_Continue;
1499}
1500
1501/*
dandd1a9c82018-09-05 08:28:30 +00001502** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001503*/
1504static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1505 int i;
1506 RenameCtx *p = pWalker->u.pRename;
1507 SrcList *pSrc = pSelect->pSrc;
dan38096962019-12-09 08:13:43 +00001508 if( pSelect->selFlags & SF_View ) return WRC_Prune;
drh92a28242019-10-09 15:37:58 +00001509 if( pSrc==0 ){
1510 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001511 return WRC_Abort;
1512 }
danc9461ec2018-08-29 21:00:16 +00001513 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 }
danea412512018-12-05 13:49:04 +00001519 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001520
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**
dan141e1192018-08-31 18:23:53 +00001531** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001532** 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.
danc9461ec2018-08-29 21:00:16 +00001538**
dan141e1192018-08-31 18:23:53 +00001539** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001540**
dan141e1192018-08-31 18:23:53 +00001541** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001542** -> 'CREATE TABLE t1(a REFERENCES t3)'
1543*/
1544static void renameTableFunc(
1545 sqlite3_context *context,
1546 int NotUsed,
1547 sqlite3_value **argv
1548){
1549 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001550 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001551 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]);
drh5b1da302018-09-01 20:02:07 +00001555 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001556
dan141e1192018-08-31 18:23:53 +00001557 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001558 Parse sParse;
1559 int rc;
1560 int bQuote = 1;
1561 RenameCtx sCtx;
1562 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001563
dan141e1192018-08-31 18:23:53 +00001564#ifndef SQLITE_OMIT_AUTHORIZATION
1565 sqlite3_xauth xAuth = db->xAuth;
1566 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001567#endif
1568
dan141e1192018-08-31 18:23:53 +00001569 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
drhb2ab3dc2019-12-20 14:08:34 +00001579 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001580
1581 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001582 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001583 if( sParse.pNewTable ){
1584 Table *pTab = sParse.pNewTable;
1585
1586 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001587 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001588 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001589 NameContext sNC;
1590 memset(&sNC, 0, sizeof(sNC));
1591 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001592
dan38096962019-12-09 08:13:43 +00001593 assert( pSelect->selFlags & SF_View );
1594 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001595 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001596 if( sParse.nErr ){
1597 rc = sParse.rc;
1598 }else{
1599 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1600 }
dan674b8942018-09-20 08:28:01 +00001601 }
dan141e1192018-08-31 18:23:53 +00001602 }else{
1603 /* Modify any FK definitions to point to the new table. */
1604#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001605 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001606 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 }
dan141e1192018-08-31 18:23:53 +00001611 }
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;
dan674b8942018-09-20 08:28:01 +00001620 if( isLegacy==0 ){
1621 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1622 }
dan141e1192018-08-31 18:23:53 +00001623 renameTokenFind(&sParse, &sCtx, pTab->zName);
1624 }
danc9461ec2018-08-29 21:00:16 +00001625 }
1626 }
danc9461ec2018-08-29 21:00:16 +00001627
dan141e1192018-08-31 18:23:53 +00001628 else if( sParse.pNewIndex ){
1629 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001630 if( isLegacy==0 ){
1631 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1632 }
dan141e1192018-08-31 18:23:53 +00001633 }
danc9461ec2018-08-29 21:00:16 +00001634
1635#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001636 else{
dan141e1192018-08-31 18:23:53 +00001637 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 }
danc9461ec2018-08-29 21:00:16 +00001644
dan674b8942018-09-20 08:28:01 +00001645 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001646 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001647 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 }
dan141e1192018-08-31 18:23:53 +00001653 }
dan0ccda962018-08-30 16:26:48 +00001654 }
danc9461ec2018-08-29 21:00:16 +00001655 }
1656 }
dan141e1192018-08-31 18:23:53 +00001657#endif
danc9461ec2018-08-29 21:00:16 +00001658 }
dan141e1192018-08-31 18:23:53 +00001659
1660 if( rc==SQLITE_OK ){
1661 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1662 }
1663 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001664 if( sParse.zErrMsg ){
1665 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1666 }else{
1667 sqlite3_result_error_code(context, rc);
1668 }
dan141e1192018-08-31 18:23:53 +00001669 }
1670
1671 renameParseCleanup(&sParse);
1672 renameTokenFree(db, sCtx.pList);
1673 sqlite3BtreeLeaveAll(db);
1674#ifndef SQLITE_OMIT_AUTHORIZATION
1675 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001676#endif
1677 }
1678
danc9461ec2018-08-29 21:00:16 +00001679 return;
1680}
1681
dandd1a9c82018-09-05 08:28:30 +00001682/*
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
dan1d85c6b2018-09-06 16:01:37 +00001687** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001688**
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.
dan1d85c6b2018-09-06 16:01:37 +00001694**
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.
dandd1a9c82018-09-05 08:28:30 +00001700*/
dan9d324822018-08-30 20:03:44 +00001701static void renameTableTest(
1702 sqlite3_context *context,
1703 int NotUsed,
1704 sqlite3_value **argv
1705){
1706 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001707 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1708 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001709 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001710 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001711
dan141e1192018-08-31 18:23:53 +00001712#ifndef SQLITE_OMIT_AUTHORIZATION
1713 sqlite3_xauth xAuth = db->xAuth;
1714 db->xAuth = 0;
1715#endif
1716
drh5b1da302018-09-01 20:02:07 +00001717 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001718 if( zDb && zInput ){
1719 int rc;
1720 Parse sParse;
drhb2ab3dc2019-12-20 14:08:34 +00001721 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan09236502018-09-01 16:05:50 +00001722 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001723 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001724 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 ){
dan674b8942018-09-20 08:28:01 +00001732 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001733 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001734 }
drh3b700452018-09-07 19:12:08 +00001735 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001736 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1737 int i2 = sqlite3FindDbName(db, zDb);
1738 if( i1==i2 ) sqlite3_result_int(context, 1);
1739 }
dan09236502018-09-01 16:05:50 +00001740 }
dan9d324822018-08-30 20:03:44 +00001741 }
1742
dan09236502018-09-01 16:05:50 +00001743 if( rc!=SQLITE_OK ){
1744 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001745 }
dan09236502018-09-01 16:05:50 +00001746 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001747 }
1748
dan141e1192018-08-31 18:23:53 +00001749#ifndef SQLITE_OMIT_AUTHORIZATION
1750 db->xAuth = xAuth;
1751#endif
dan9d324822018-08-30 20:03:44 +00001752}
1753
dancf8f2892018-08-09 20:47:01 +00001754/*
1755** Register built-in functions used to help implement ALTER TABLE
1756*/
1757void sqlite3AlterFunctions(void){
1758 static FuncDef aAlterTableFuncs[] = {
drheea8eb62018-11-26 18:09:15 +00001759 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1760 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1761 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001762 };
1763 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1764}
drhd0e4a6c2005-02-15 20:47:57 +00001765#endif /* SQLITE_ALTER_TABLE */