blob: d48b5ec919ee8f53e739a66076fc80b23d7e436f [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*/
dan6a5a13d2021-02-17 20:08:22 +000080static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
dan09236502018-09-01 16:05:50 +000081 Vdbe *v = pParse->pVdbe;
82 if( v ){
83 sqlite3ChangeCookie(pParse, iDb);
dan6a5a13d2021-02-17 20:08:22 +000084 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
85 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
dan09236502018-09-01 16:05:50 +000086 }
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
dan6a5a13d2021-02-17 20:08:22 +0000253 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
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 */
dan6a5a13d2021-02-17 20:08:22 +0000416 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
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)
dan6a5a13d2021-02-17 20:08:22 +0000516static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000517 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 ){
dan6a5a13d2021-02-17 20:08:22 +0000529 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
530 (bDrop ? "drop column from" : "rename columns of"),
531 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000532 );
533 return 1;
534 }
535 return 0;
536}
537#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000538# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000539#endif
540
541/*
drh4a2c7472018-08-13 15:09:48 +0000542** Handles the following parser reduction:
543**
544** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
545*/
dancf8f2892018-08-09 20:47:01 +0000546void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000547 Parse *pParse, /* Parsing context */
548 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
549 Token *pOld, /* Name of column being changed */
550 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000551){
drh4a2c7472018-08-13 15:09:48 +0000552 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000553 Table *pTab; /* Table being updated */
554 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000555 char *zOld = 0; /* Old column name */
556 char *zNew = 0; /* New column name */
557 const char *zDb; /* Name of schema containing the table */
558 int iSchema; /* Index of the schema */
559 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000560
drh4a2c7472018-08-13 15:09:48 +0000561 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000562 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
563 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000564
565 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000566 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000567 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000568
569 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000570 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
571 assert( iSchema>=0 );
572 zDb = db->aDb[iSchema].zDbSName;
573
drh0d019b92018-08-25 16:14:46 +0000574#ifndef SQLITE_OMIT_AUTHORIZATION
575 /* Invoke the authorization callback. */
576 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
577 goto exit_rename_column;
578 }
579#endif
580
drh4a2c7472018-08-13 15:09:48 +0000581 /* Make sure the old name really is a column name in the table to be
582 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000583 zOld = sqlite3NameFromToken(db, pOld);
584 if( !zOld ) goto exit_rename_column;
585 for(iCol=0; iCol<pTab->nCol; iCol++){
586 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
587 }
588 if( iCol==pTab->nCol ){
589 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
590 goto exit_rename_column;
591 }
592
drh4a2c7472018-08-13 15:09:48 +0000593 /* Do the rename operation using a recursive UPDATE statement that
594 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000595 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000596 */
dan1f3b2842019-03-15 16:17:32 +0000597 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000598 zNew = sqlite3NameFromToken(db, pNew);
599 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000600 assert( pNew->n>0 );
601 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000602 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000603 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000604 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000605 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
606 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000607 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000608 zDb,
danb87a9a82018-09-01 20:23:28 +0000609 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000610 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000611 );
612
dan9d324822018-08-30 20:03:44 +0000613 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000614 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000615 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000616 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000617 zDb, pTab->zName, iCol, zNew, bQuote
618 );
619
dane325ffe2018-08-11 13:40:20 +0000620 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000621 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan9d324822018-08-30 20:03:44 +0000622 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000623
dancf8f2892018-08-09 20:47:01 +0000624 exit_rename_column:
625 sqlite3SrcListDelete(db, pSrc);
626 sqlite3DbFree(db, zOld);
627 sqlite3DbFree(db, zNew);
628 return;
629}
630
drh4a2c7472018-08-13 15:09:48 +0000631/*
632** Each RenameToken object maps an element of the parse tree into
633** the token that generated that element. The parse tree element
634** might be one of:
635**
636** * A pointer to an Expr that represents an ID
637** * The name of a table column in Column.zName
638**
639** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000640** Each new object is created by sqlite3RenameTokenMap().
641** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000642** routine is used to keep the mapping current.
643**
644** After the parse finishes, renameTokenFind() routine can be used
645** to look up the actual token value that created some element in
646** the parse tree.
647*/
dancf8f2892018-08-09 20:47:01 +0000648struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000649 void *p; /* Parse tree element created by token t */
650 Token t; /* The token that created parse tree element p */
651 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000652};
653
drh4a2c7472018-08-13 15:09:48 +0000654/*
655** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
656** down into the Walker.
657*/
dan5496d6a2018-08-13 17:14:26 +0000658typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000659struct RenameCtx {
660 RenameToken *pList; /* List of tokens to overwrite */
661 int nList; /* Number of tokens in pList */
662 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000663 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000664 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000665};
666
dan8900a482018-09-05 14:36:05 +0000667#ifdef SQLITE_DEBUG
668/*
669** This function is only for debugging. It performs two tasks:
670**
671** 1. Checks that pointer pPtr does not already appear in the
672** rename-token list.
673**
674** 2. Dereferences each pointer in the rename-token list.
675**
676** The second is most effective when debugging under valgrind or
677** address-sanitizer or similar. If any of these pointers no longer
678** point to valid objects, an exception is raised by the memory-checking
679** tool.
680**
681** The point of this is to prevent comparisons of invalid pointer values.
682** Even though this always seems to work, it is undefined according to the
683** C standard. Example of undefined comparison:
684**
685** sqlite3_free(x);
686** if( x==y ) ...
687**
688** Technically, as x no longer points into a valid object or to the byte
689** following a valid object, it may not be used in comparison operations.
690*/
drh16b870d2018-09-12 15:51:56 +0000691static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000692 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
693 RenameToken *p;
694 u8 i = 0;
695 for(p=pParse->pRename; p; p=p->pNext){
696 if( p->p ){
697 assert( p->p!=pPtr );
698 i += *(u8*)(p->p);
699 }
danc9461ec2018-08-29 21:00:16 +0000700 }
701 }
702}
dan8900a482018-09-05 14:36:05 +0000703#else
704# define renameTokenCheckAll(x,y)
705#endif
danc9461ec2018-08-29 21:00:16 +0000706
drh4a2c7472018-08-13 15:09:48 +0000707/*
drh49b269e2018-11-26 15:00:25 +0000708** Remember that the parser tree element pPtr was created using
709** the token pToken.
dan07e95232018-08-21 16:32:53 +0000710**
drh49b269e2018-11-26 15:00:25 +0000711** In other words, construct a new RenameToken object and add it
712** to the list of RenameToken objects currently being built up
713** in pParse->pRename.
714**
715** The pPtr argument is returned so that this routine can be used
716** with tail recursion in tokenExpr() routine, for a small performance
717** improvement.
drh4a2c7472018-08-13 15:09:48 +0000718*/
dan07e95232018-08-21 16:32:53 +0000719void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000720 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000721 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000722 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000723 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000724 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
725 if( pNew ){
726 pNew->p = pPtr;
727 pNew->t = *pToken;
728 pNew->pNext = pParse->pRename;
729 pParse->pRename = pNew;
730 }
dancf8f2892018-08-09 20:47:01 +0000731 }
danc9461ec2018-08-29 21:00:16 +0000732
dand145e5f2018-08-21 08:29:48 +0000733 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000734}
735
drh4a2c7472018-08-13 15:09:48 +0000736/*
dan07e95232018-08-21 16:32:53 +0000737** It is assumed that there is already a RenameToken object associated
738** with parse tree element pFrom. This function remaps the associated token
739** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000740*/
dan07e95232018-08-21 16:32:53 +0000741void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000742 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000743 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000744 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000745 if( p->p==pFrom ){
746 p->p = pTo;
747 break;
748 }
749 }
dancf8f2892018-08-09 20:47:01 +0000750}
751
drh4a2c7472018-08-13 15:09:48 +0000752/*
dan8900a482018-09-05 14:36:05 +0000753** Walker callback used by sqlite3RenameExprUnmap().
754*/
755static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
756 Parse *pParse = pWalker->pParse;
757 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
758 return WRC_Continue;
759}
760
761/*
dan8f407622019-12-04 14:26:38 +0000762** Iterate through the Select objects that are part of WITH clauses attached
763** to select statement pSelect.
764*/
765static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000766 With *pWith = pSelect->pWith;
767 if( pWith ){
dan8f407622019-12-04 14:26:38 +0000768 int i;
drh646975c2019-12-17 12:03:30 +0000769 for(i=0; i<pWith->nCte; i++){
770 Select *p = pWith->a[i].pSelect;
dan8f407622019-12-04 14:26:38 +0000771 NameContext sNC;
772 memset(&sNC, 0, sizeof(sNC));
773 sNC.pParse = pWalker->pParse;
774 sqlite3SelectPrep(sNC.pParse, p, &sNC);
775 sqlite3WalkSelect(pWalker, p);
drh646975c2019-12-17 12:03:30 +0000776 sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
dan8f407622019-12-04 14:26:38 +0000777 }
778 }
779}
780
781/*
danfb99e382020-04-03 11:20:40 +0000782** Unmap all tokens in the IdList object passed as the second argument.
783*/
784static void unmapColumnIdlistNames(
785 Parse *pParse,
786 IdList *pIdList
787){
788 if( pIdList ){
789 int ii;
790 for(ii=0; ii<pIdList->nId; ii++){
791 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
792 }
793 }
794}
795
796/*
dan0b277a92019-06-11 12:03:10 +0000797** Walker callback used by sqlite3RenameExprUnmap().
798*/
799static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000800 Parse *pParse = pWalker->pParse;
801 int i;
drhd63b69b2019-12-04 15:08:58 +0000802 if( pParse->nErr ) return WRC_Abort;
drh2bc5cf92019-12-09 19:29:10 +0000803 if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
drhbdf4cf02019-06-15 15:21:49 +0000804 if( ALWAYS(p->pEList) ){
805 ExprList *pList = p->pEList;
806 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000807 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000808 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000809 }
810 }
811 }
drh2c3f4652019-06-11 16:43:58 +0000812 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000813 SrcList *pSrc = p->pSrc;
814 for(i=0; i<pSrc->nSrc; i++){
815 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000816 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000817 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000818 }
819 }
dan8f407622019-12-04 14:26:38 +0000820
821 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000822 return WRC_Continue;
823}
824
825/*
dan8900a482018-09-05 14:36:05 +0000826** Remove all nodes that are part of expression pExpr from the rename list.
827*/
828void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000829 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000830 Walker sWalker;
831 memset(&sWalker, 0, sizeof(Walker));
832 sWalker.pParse = pParse;
833 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000834 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000835 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000836 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000837 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000838}
839
840/*
dane8ab40d2018-09-12 08:51:48 +0000841** Remove all nodes that are part of expression-list pEList from the
842** rename list.
843*/
844void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
845 if( pEList ){
846 int i;
847 Walker sWalker;
848 memset(&sWalker, 0, sizeof(Walker));
849 sWalker.pParse = pParse;
850 sWalker.xExprCallback = renameUnmapExprCb;
851 sqlite3WalkExprList(&sWalker, pEList);
852 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000853 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000854 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
855 }
dane8ab40d2018-09-12 08:51:48 +0000856 }
857 }
858}
859
860/*
drh4a2c7472018-08-13 15:09:48 +0000861** Free the list of RenameToken objects given in the second argument
862*/
dancf8f2892018-08-09 20:47:01 +0000863static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
864 RenameToken *pNext;
865 RenameToken *p;
866 for(p=pToken; p; p=pNext){
867 pNext = p->pNext;
868 sqlite3DbFree(db, p);
869 }
870}
871
dan987db762018-08-14 20:18:50 +0000872/*
873** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000874** object associated with parse tree element pPtr. If found, return a pointer
875** to it. Otherwise, return NULL.
876**
877** If the second argument passed to this function is not NULL and a matching
878** RenameToken object is found, remove it from the Parse object and add it to
879** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000880*/
dan6e6d9832021-02-16 20:43:36 +0000881static RenameToken *renameTokenFind(
882 Parse *pParse,
883 struct RenameCtx *pCtx,
884 void *pPtr
885){
dancf8f2892018-08-09 20:47:01 +0000886 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000887 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000888 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
889 if( (*pp)->p==pPtr ){
890 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000891 if( pCtx ){
892 *pp = pToken->pNext;
893 pToken->pNext = pCtx->pList;
894 pCtx->pList = pToken;
895 pCtx->nList++;
896 }
897 return pToken;
dancf8f2892018-08-09 20:47:01 +0000898 }
899 }
dan6e6d9832021-02-16 20:43:36 +0000900 return 0;
dancf8f2892018-08-09 20:47:01 +0000901}
902
dan24fedb92018-08-18 17:35:38 +0000903/*
904** This is a Walker select callback. It does nothing. It is only required
905** because without a dummy callback, sqlite3WalkExpr() and similar do not
906** descend into sub-select statements.
907*/
dan987db762018-08-14 20:18:50 +0000908static int renameColumnSelectCb(Walker *pWalker, Select *p){
dan38096962019-12-09 08:13:43 +0000909 if( p->selFlags & SF_View ) return WRC_Prune;
danea412512018-12-05 13:49:04 +0000910 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000911 return WRC_Continue;
912}
913
dan987db762018-08-14 20:18:50 +0000914/*
915** This is a Walker expression callback.
916**
917** For every TK_COLUMN node in the expression tree, search to see
918** if the column being references is the column being renamed by an
919** ALTER TABLE statement. If it is, then attach its associated
920** RenameToken object to the list of RenameToken objects being
921** constructed in RenameCtx object at pWalker->u.pRename.
922*/
dancf8f2892018-08-09 20:47:01 +0000923static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000924 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000925 if( pExpr->op==TK_TRIGGER
926 && pExpr->iColumn==p->iCol
927 && pWalker->pParse->pTriggerTab==p->pTab
928 ){
dan5be60c52018-08-15 20:28:39 +0000929 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000930 }else if( pExpr->op==TK_COLUMN
931 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000932 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000933 ){
dan5496d6a2018-08-13 17:14:26 +0000934 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000935 }
936 return WRC_Continue;
937}
938
dan987db762018-08-14 20:18:50 +0000939/*
940** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000941** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000942** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000943** RenameContext. "Last" means the last RenameToken encountered when
944** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000945** return all column name tokens in the order that they are encountered
946** in the SQL statement.
947*/
dan5496d6a2018-08-13 17:14:26 +0000948static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000949 RenameToken *pBest = pCtx->pList;
950 RenameToken *pToken;
951 RenameToken **pp;
952
953 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
954 if( pToken->t.z>pBest->t.z ) pBest = pToken;
955 }
956 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
957 *pp = pBest->pNext;
958
959 return pBest;
960}
961
dan6fe7f232018-08-10 19:19:33 +0000962/*
dan24fedb92018-08-18 17:35:38 +0000963** An error occured while parsing or otherwise processing a database
964** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
965** ALTER TABLE RENAME COLUMN program. The error message emitted by the
966** sub-routine is currently stored in pParse->zErrMsg. This function
967** adds context to the error message and then stores it in pCtx.
968*/
danb0137382018-08-20 20:01:01 +0000969static void renameColumnParseError(
970 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000971 int bPost,
danb0137382018-08-20 20:01:01 +0000972 sqlite3_value *pType,
973 sqlite3_value *pObject,
974 Parse *pParse
975){
drh79a5ee92018-08-23 19:32:04 +0000976 const char *zT = (const char*)sqlite3_value_text(pType);
977 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000978 char *zErr;
danb0137382018-08-20 20:01:01 +0000979
dan0d5fa6b2018-08-24 17:55:49 +0000980 zErr = sqlite3_mprintf("error in %s %s%s: %s",
981 zT, zN, (bPost ? " after rename" : ""),
982 pParse->zErrMsg
983 );
dan24fedb92018-08-18 17:35:38 +0000984 sqlite3_result_error(pCtx, zErr, -1);
985 sqlite3_free(zErr);
986}
987
988/*
dan06249392018-08-21 15:06:59 +0000989** For each name in the the expression-list pEList (i.e. each
990** pEList->a[i].zName) that matches the string in zOld, extract the
991** corresponding rename-token from Parse object pParse and add it
992** to the RenameCtx pCtx.
993*/
994static void renameColumnElistNames(
995 Parse *pParse,
996 RenameCtx *pCtx,
997 ExprList *pEList,
998 const char *zOld
999){
1000 if( pEList ){
1001 int i;
1002 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001003 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001004 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1005 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001006 && 0==sqlite3_stricmp(zName, zOld)
1007 ){
dan06249392018-08-21 15:06:59 +00001008 renameTokenFind(pParse, pCtx, (void*)zName);
1009 }
1010 }
1011 }
1012}
1013
1014/*
1015** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1016** that matches the string in zOld, extract the corresponding rename-token
1017** from Parse object pParse and add it to the RenameCtx pCtx.
1018*/
1019static void renameColumnIdlistNames(
1020 Parse *pParse,
1021 RenameCtx *pCtx,
1022 IdList *pIdList,
1023 const char *zOld
1024){
1025 if( pIdList ){
1026 int i;
1027 for(i=0; i<pIdList->nId; i++){
1028 char *zName = pIdList->a[i].zName;
1029 if( 0==sqlite3_stricmp(zName, zOld) ){
1030 renameTokenFind(pParse, pCtx, (void*)zName);
1031 }
1032 }
1033 }
1034}
1035
danfb99e382020-04-03 11:20:40 +00001036
dandd1a9c82018-09-05 08:28:30 +00001037/*
1038** Parse the SQL statement zSql using Parse object (*p). The Parse object
1039** is initialized by this function before it is used.
1040*/
danc9461ec2018-08-29 21:00:16 +00001041static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001042 Parse *p, /* Memory to use for Parse object */
1043 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001044 sqlite3 *db, /* Database handle */
1045 const char *zSql, /* SQL to parse */
1046 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001047){
1048 int rc;
1049 char *zErr = 0;
1050
1051 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1052
1053 /* Parse the SQL statement passed as the first argument. If no error
1054 ** occurs and the parse does not result in a new table, index or
1055 ** trigger object, the database must be corrupt. */
1056 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001057 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001058 p->db = db;
1059 p->nQueryLoop = 1;
1060 rc = sqlite3RunParser(p, zSql, &zErr);
1061 assert( p->zErrMsg==0 );
1062 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001063 p->zErrMsg = zErr;
1064 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1065 if( rc==SQLITE_OK
1066 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1067 ){
1068 rc = SQLITE_CORRUPT_BKPT;
1069 }
1070
1071#ifdef SQLITE_DEBUG
1072 /* Ensure that all mappings in the Parse.pRename list really do map to
1073 ** a part of the input string. */
1074 if( rc==SQLITE_OK ){
1075 int nSql = sqlite3Strlen30(zSql);
1076 RenameToken *pToken;
1077 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1078 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1079 }
1080 }
1081#endif
1082
1083 db->init.iDb = 0;
1084 return rc;
1085}
1086
dandd1a9c82018-09-05 08:28:30 +00001087/*
1088** This function edits SQL statement zSql, replacing each token identified
1089** by the linked list pRename with the text of zNew. If argument bQuote is
1090** true, then zNew is always quoted first. If no error occurs, the result
1091** is loaded into context object pCtx as the result.
1092**
1093** Or, if an error occurs (i.e. an OOM condition), an error is left in
1094** pCtx and an SQLite error code returned.
1095*/
danc9461ec2018-08-29 21:00:16 +00001096static int renameEditSql(
1097 sqlite3_context *pCtx, /* Return result here */
1098 RenameCtx *pRename, /* Rename context */
1099 const char *zSql, /* SQL statement to edit */
1100 const char *zNew, /* New token text */
1101 int bQuote /* True to always quote token */
1102){
1103 int nNew = sqlite3Strlen30(zNew);
1104 int nSql = sqlite3Strlen30(zSql);
1105 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1106 int rc = SQLITE_OK;
1107 char *zQuot;
1108 char *zOut;
1109 int nQuot;
1110
1111 /* Set zQuot to point to a buffer containing a quoted copy of the
1112 ** identifier zNew. If the corresponding identifier in the original
1113 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1114 ** point to zQuot so that all substitutions are made using the
1115 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001116 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001117 if( zQuot==0 ){
1118 return SQLITE_NOMEM;
1119 }else{
1120 nQuot = sqlite3Strlen30(zQuot);
1121 }
1122 if( bQuote ){
1123 zNew = zQuot;
1124 nNew = nQuot;
1125 }
1126
1127 /* At this point pRename->pList contains a list of RenameToken objects
1128 ** corresponding to all tokens in the input SQL that must be replaced
1129 ** with the new column name. All that remains is to construct and
1130 ** return the edited SQL string. */
1131 assert( nQuot>=nNew );
1132 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1133 if( zOut ){
1134 int nOut = nSql;
1135 memcpy(zOut, zSql, nSql);
1136 while( pRename->pList ){
1137 int iOff; /* Offset of token to replace in zOut */
1138 RenameToken *pBest = renameColumnTokenNext(pRename);
1139
1140 u32 nReplace;
1141 const char *zReplace;
1142 if( sqlite3IsIdChar(*pBest->t.z) ){
1143 nReplace = nNew;
1144 zReplace = zNew;
1145 }else{
1146 nReplace = nQuot;
1147 zReplace = zQuot;
1148 }
1149
1150 iOff = pBest->t.z - zSql;
1151 if( pBest->t.n!=nReplace ){
1152 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1153 nOut - (iOff + pBest->t.n)
1154 );
1155 nOut += nReplace - pBest->t.n;
1156 zOut[nOut] = '\0';
1157 }
1158 memcpy(&zOut[iOff], zReplace, nReplace);
1159 sqlite3DbFree(db, pBest);
1160 }
1161
1162 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1163 sqlite3DbFree(db, zOut);
1164 }else{
1165 rc = SQLITE_NOMEM;
1166 }
1167
1168 sqlite3_free(zQuot);
1169 return rc;
1170}
1171
dandd1a9c82018-09-05 08:28:30 +00001172/*
1173** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1174** it was read from the schema of database zDb. Return SQLITE_OK if
1175** successful. Otherwise, return an SQLite error code and leave an error
1176** message in the Parse object.
1177*/
drha7c74002020-07-18 18:44:59 +00001178static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001179 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001180 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001181 TriggerStep *pStep;
1182 NameContext sNC;
1183 int rc = SQLITE_OK;
1184
1185 memset(&sNC, 0, sizeof(sNC));
1186 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001187 assert( pNew->pTabSchema );
1188 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1189 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1190 );
1191 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001192 /* ALWAYS() because if the table of the trigger does not exist, the
1193 ** error would have been hit before this point */
1194 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001195 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1196 }
danc9461ec2018-08-29 21:00:16 +00001197
1198 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001199 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001200 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001201 }
1202
dand5e6fef2018-09-07 15:50:31 +00001203 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001204 if( pStep->pSelect ){
1205 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1206 if( pParse->nErr ) rc = pParse->rc;
1207 }
dand5e6fef2018-09-07 15:50:31 +00001208 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001209 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1210 if( pSrc ){
1211 int i;
drha3e64952020-08-12 16:19:12 +00001212 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
dane7877b22020-07-14 19:51:01 +00001213 struct SrcList_item *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001214 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001215 if( p->pSelect ){
1216 sqlite3SelectPrep(pParse, p->pSelect, 0);
1217 sqlite3ExpandSubquery(pParse, p);
1218 assert( i>0 );
1219 assert( pStep->pFrom->a[i-1].pSelect );
1220 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001221 }else{
dan7a39fae2020-10-31 16:33:01 +00001222 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1223 if( p->pTab==0 ){
1224 rc = SQLITE_ERROR;
1225 }else{
1226 p->pTab->nTabRef++;
1227 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1228 }
dane7877b22020-07-14 19:51:01 +00001229 }
1230 }
1231 sNC.pSrcList = pSrc;
1232 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001233 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1234 }
1235 if( rc==SQLITE_OK ){
1236 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1237 }
1238 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1239 if( pStep->pUpsert ){
1240 Upsert *pUpsert = pStep->pUpsert;
1241 assert( rc==SQLITE_OK );
dane7877b22020-07-14 19:51:01 +00001242 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001243 sNC.uNC.pUpsert = pUpsert;
1244 sNC.ncFlags = NC_UUpsert;
1245 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1246 if( rc==SQLITE_OK ){
1247 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1248 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1249 }
1250 if( rc==SQLITE_OK ){
1251 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1252 }
1253 if( rc==SQLITE_OK ){
1254 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1255 }
1256 sNC.ncFlags = 0;
1257 }
dan0e14e982019-01-18 16:06:18 +00001258 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001259 sqlite3SrcListDelete(db, pSrc);
1260 }else{
1261 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001262 }
1263 }
1264 }
1265 return rc;
1266}
1267
dandd1a9c82018-09-05 08:28:30 +00001268/*
1269** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1270** objects that are part of the trigger passed as the second argument.
1271*/
danc9461ec2018-08-29 21:00:16 +00001272static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1273 TriggerStep *pStep;
1274
1275 /* Find tokens to edit in WHEN clause */
1276 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1277
1278 /* Find tokens to edit in trigger steps */
1279 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1280 sqlite3WalkSelect(pWalker, pStep->pSelect);
1281 sqlite3WalkExpr(pWalker, pStep->pWhere);
1282 sqlite3WalkExprList(pWalker, pStep->pExprList);
1283 if( pStep->pUpsert ){
1284 Upsert *pUpsert = pStep->pUpsert;
1285 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1286 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1287 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1288 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1289 }
dan7a39fae2020-10-31 16:33:01 +00001290 if( pStep->pFrom ){
1291 int i;
1292 for(i=0; i<pStep->pFrom->nSrc; i++){
1293 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1294 }
1295 }
danc9461ec2018-08-29 21:00:16 +00001296 }
1297}
1298
dandd1a9c82018-09-05 08:28:30 +00001299/*
1300** Free the contents of Parse object (*pParse). Do not free the memory
1301** occupied by the Parse object itself.
1302*/
dan141e1192018-08-31 18:23:53 +00001303static void renameParseCleanup(Parse *pParse){
1304 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001305 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001306 if( pParse->pVdbe ){
1307 sqlite3VdbeFinalize(pParse->pVdbe);
1308 }
1309 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001310 while( (pIdx = pParse->pNewIndex)!=0 ){
1311 pParse->pNewIndex = pIdx->pNext;
1312 sqlite3FreeIndex(db, pIdx);
1313 }
dan141e1192018-08-31 18:23:53 +00001314 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1315 sqlite3DbFree(db, pParse->zErrMsg);
1316 renameTokenFree(db, pParse->pRename);
1317 sqlite3ParserReset(pParse);
1318}
1319
dan06249392018-08-21 15:06:59 +00001320/*
dan987db762018-08-14 20:18:50 +00001321** SQL function:
1322**
1323** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1324**
1325** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001326** 1. type: Type of object ("table", "view" etc.)
1327** 2. object: Name of object
1328** 3. Database: Database name (e.g. "main")
1329** 4. Table: Table name
1330** 5. iCol: Index of column to rename
1331** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001332** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001333** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001334**
1335** Do a column rename operation on the CREATE statement given in zSql.
1336** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1337** into zNew. The name should be quoted if bQuote is true.
1338**
1339** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001340** It is only accessible to SQL created using sqlite3NestedParse(). It is
1341** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001342*/
dancf8f2892018-08-09 20:47:01 +00001343static void renameColumnFunc(
1344 sqlite3_context *context,
1345 int NotUsed,
1346 sqlite3_value **argv
1347){
1348 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001349 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001350 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001351 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1352 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1353 int iCol = sqlite3_value_int(argv[5]);
1354 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001355 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001356 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001357 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001358 int rc;
dancf8f2892018-08-09 20:47:01 +00001359 Parse sParse;
1360 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001361 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001362 int i;
dan987db762018-08-14 20:18:50 +00001363 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001364#ifndef SQLITE_OMIT_AUTHORIZATION
1365 sqlite3_xauth xAuth = db->xAuth;
1366#endif
dancf8f2892018-08-09 20:47:01 +00001367
drh38d99642018-08-18 18:27:18 +00001368 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001369 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001370 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001371 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001372 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001373 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001374 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001375 if( pTab==0 || iCol>=pTab->nCol ){
1376 sqlite3BtreeLeaveAll(db);
1377 return;
1378 }
dan987db762018-08-14 20:18:50 +00001379 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001380 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001381 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001382
dan141e1192018-08-31 18:23:53 +00001383#ifndef SQLITE_OMIT_AUTHORIZATION
1384 db->xAuth = 0;
1385#endif
drhb2ab3dc2019-12-20 14:08:34 +00001386 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001387
dancf8f2892018-08-09 20:47:01 +00001388 /* Find tokens that need to be replaced. */
1389 memset(&sWalker, 0, sizeof(Walker));
1390 sWalker.pParse = &sParse;
1391 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001392 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001393 sWalker.u.pRename = &sCtx;
1394
dan0cbb0b12018-08-16 19:49:16 +00001395 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001396 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001397 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001398 Select *pSelect = sParse.pNewTable->pSelect;
1399 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001400 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001401 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001402 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001403 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1404 if( rc==SQLITE_OK ){
1405 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001406 }
dan987db762018-08-14 20:18:50 +00001407 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1408 }else{
1409 /* A regular table */
1410 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1411 FKey *pFKey;
1412 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001413 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001414 if( bFKOnly==0 ){
1415 renameTokenFind(
1416 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1417 );
1418 if( sCtx.iCol<0 ){
1419 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001420 }
dan987db762018-08-14 20:18:50 +00001421 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1422 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1423 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1424 }
drh885eeb62019-01-09 02:02:24 +00001425 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1426 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1427 }
dan987db762018-08-14 20:18:50 +00001428 }
drhb9bcf7c2019-10-19 13:29:10 +00001429#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1430 for(i=0; i<sParse.pNewTable->nCol; i++){
1431 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1432 }
1433#endif
dan987db762018-08-14 20:18:50 +00001434
1435 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1436 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001437 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001438 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1439 }
1440 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1441 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1442 ){
1443 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1444 }
dan6fe7f232018-08-10 19:19:33 +00001445 }
dancf8f2892018-08-09 20:47:01 +00001446 }
1447 }
dan5496d6a2018-08-13 17:14:26 +00001448 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001449 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1450 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001451 }else{
dan5be60c52018-08-15 20:28:39 +00001452 /* A trigger */
1453 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001454 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001455 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001456
danc9461ec2018-08-29 21:00:16 +00001457 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1458 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001459 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001460 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001461 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001462 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1463 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001464 }
danc9461ec2018-08-29 21:00:16 +00001465 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1466 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001467 }
1468 }
1469 }
1470
dan5be60c52018-08-15 20:28:39 +00001471
1472 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001473 if( sParse.pTriggerTab==pTab ){
1474 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001475 }
dan5be60c52018-08-15 20:28:39 +00001476
danc9461ec2018-08-29 21:00:16 +00001477 /* Find tokens to edit in various expressions and selects */
1478 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001479 }
1480
dan987db762018-08-14 20:18:50 +00001481 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001482 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001483
drh5fc22cd2018-08-13 13:43:11 +00001484renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001485 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001486 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001487 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001488 }else{
1489 sqlite3_result_error_code(context, rc);
1490 }
1491 }
1492
dan141e1192018-08-31 18:23:53 +00001493 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001494 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001495#ifndef SQLITE_OMIT_AUTHORIZATION
1496 db->xAuth = xAuth;
1497#endif
drhda76adc2018-08-25 02:04:05 +00001498 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001499}
1500
dandd1a9c82018-09-05 08:28:30 +00001501/*
1502** Walker expression callback used by "RENAME TABLE".
1503*/
danc9461ec2018-08-29 21:00:16 +00001504static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1505 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001506 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1507 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001508 }
1509 return WRC_Continue;
1510}
1511
1512/*
dandd1a9c82018-09-05 08:28:30 +00001513** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001514*/
1515static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1516 int i;
1517 RenameCtx *p = pWalker->u.pRename;
1518 SrcList *pSrc = pSelect->pSrc;
dan38096962019-12-09 08:13:43 +00001519 if( pSelect->selFlags & SF_View ) return WRC_Prune;
drh92a28242019-10-09 15:37:58 +00001520 if( pSrc==0 ){
1521 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001522 return WRC_Abort;
1523 }
danc9461ec2018-08-29 21:00:16 +00001524 for(i=0; i<pSrc->nSrc; i++){
1525 struct SrcList_item *pItem = &pSrc->a[i];
1526 if( pItem->pTab==p->pTab ){
1527 renameTokenFind(pWalker->pParse, p, pItem->zName);
1528 }
1529 }
danea412512018-12-05 13:49:04 +00001530 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001531
1532 return WRC_Continue;
1533}
1534
1535
1536/*
1537** This C function implements an SQL user function that is used by SQL code
1538** generated by the ALTER TABLE ... RENAME command to modify the definition
1539** of any foreign key constraints that use the table being renamed as the
1540** parent table. It is passed three arguments:
1541**
dan141e1192018-08-31 18:23:53 +00001542** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001543** 1. type: Type of object ("table", "view" etc.)
1544** 2. object: Name of object
1545** 3: The complete text of the schema statement being modified,
1546** 4: The old name of the table being renamed, and
1547** 5: The new name of the table being renamed.
1548** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001549**
dan141e1192018-08-31 18:23:53 +00001550** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001551**
dan141e1192018-08-31 18:23:53 +00001552** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001553** -> 'CREATE TABLE t1(a REFERENCES t3)'
1554*/
1555static void renameTableFunc(
1556 sqlite3_context *context,
1557 int NotUsed,
1558 sqlite3_value **argv
1559){
1560 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001561 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001562 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1563 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1564 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1565 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001566 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001567
dan141e1192018-08-31 18:23:53 +00001568 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001569 Parse sParse;
1570 int rc;
1571 int bQuote = 1;
1572 RenameCtx sCtx;
1573 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001574
dan141e1192018-08-31 18:23:53 +00001575#ifndef SQLITE_OMIT_AUTHORIZATION
1576 sqlite3_xauth xAuth = db->xAuth;
1577 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001578#endif
1579
dan141e1192018-08-31 18:23:53 +00001580 sqlite3BtreeEnterAll(db);
1581
1582 memset(&sCtx, 0, sizeof(RenameCtx));
1583 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1584 memset(&sWalker, 0, sizeof(Walker));
1585 sWalker.pParse = &sParse;
1586 sWalker.xExprCallback = renameTableExprCb;
1587 sWalker.xSelectCallback = renameTableSelectCb;
1588 sWalker.u.pRename = &sCtx;
1589
drhb2ab3dc2019-12-20 14:08:34 +00001590 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001591
1592 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001593 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001594 if( sParse.pNewTable ){
1595 Table *pTab = sParse.pNewTable;
1596
1597 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001598 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001599 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001600 NameContext sNC;
1601 memset(&sNC, 0, sizeof(sNC));
1602 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001603
dan38096962019-12-09 08:13:43 +00001604 assert( pSelect->selFlags & SF_View );
1605 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001606 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001607 if( sParse.nErr ){
1608 rc = sParse.rc;
1609 }else{
1610 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1611 }
dan674b8942018-09-20 08:28:01 +00001612 }
dan141e1192018-08-31 18:23:53 +00001613 }else{
1614 /* Modify any FK definitions to point to the new table. */
1615#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001616 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001617 FKey *pFKey;
1618 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1619 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1620 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1621 }
dan141e1192018-08-31 18:23:53 +00001622 }
1623 }
1624#endif
1625
1626 /* If this is the table being altered, fix any table refs in CHECK
1627 ** expressions. Also update the name that appears right after the
1628 ** "CREATE [VIRTUAL] TABLE" bit. */
1629 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1630 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001631 if( isLegacy==0 ){
1632 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1633 }
dan141e1192018-08-31 18:23:53 +00001634 renameTokenFind(&sParse, &sCtx, pTab->zName);
1635 }
danc9461ec2018-08-29 21:00:16 +00001636 }
1637 }
danc9461ec2018-08-29 21:00:16 +00001638
dan141e1192018-08-31 18:23:53 +00001639 else if( sParse.pNewIndex ){
1640 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001641 if( isLegacy==0 ){
1642 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1643 }
dan141e1192018-08-31 18:23:53 +00001644 }
danc9461ec2018-08-29 21:00:16 +00001645
1646#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001647 else{
dan141e1192018-08-31 18:23:53 +00001648 Trigger *pTrigger = sParse.pNewTrigger;
1649 TriggerStep *pStep;
1650 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1651 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1652 ){
1653 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1654 }
danc9461ec2018-08-29 21:00:16 +00001655
dan674b8942018-09-20 08:28:01 +00001656 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001657 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001658 if( rc==SQLITE_OK ){
1659 renameWalkTrigger(&sWalker, pTrigger);
1660 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1661 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1662 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1663 }
dan141e1192018-08-31 18:23:53 +00001664 }
dan0ccda962018-08-30 16:26:48 +00001665 }
danc9461ec2018-08-29 21:00:16 +00001666 }
1667 }
dan141e1192018-08-31 18:23:53 +00001668#endif
danc9461ec2018-08-29 21:00:16 +00001669 }
dan141e1192018-08-31 18:23:53 +00001670
1671 if( rc==SQLITE_OK ){
1672 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1673 }
1674 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001675 if( sParse.zErrMsg ){
1676 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1677 }else{
1678 sqlite3_result_error_code(context, rc);
1679 }
dan141e1192018-08-31 18:23:53 +00001680 }
1681
1682 renameParseCleanup(&sParse);
1683 renameTokenFree(db, sCtx.pList);
1684 sqlite3BtreeLeaveAll(db);
1685#ifndef SQLITE_OMIT_AUTHORIZATION
1686 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001687#endif
1688 }
1689
danc9461ec2018-08-29 21:00:16 +00001690 return;
1691}
1692
dandd1a9c82018-09-05 08:28:30 +00001693/*
1694** An SQL user function that checks that there are no parse or symbol
1695** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1696** After an ALTER TABLE .. RENAME operation is performed and the schema
1697** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001698** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001699**
1700** 0: Database name ("main", "temp" etc.).
1701** 1: SQL statement.
1702** 2: Object type ("view", "table", "trigger" or "index").
1703** 3: Object name.
1704** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001705**
1706** Unless it finds an error, this function normally returns NULL. However, it
1707** returns integer value 1 if:
1708**
1709** * the SQL argument creates a trigger, and
1710** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001711*/
dan9d324822018-08-30 20:03:44 +00001712static void renameTableTest(
1713 sqlite3_context *context,
1714 int NotUsed,
1715 sqlite3_value **argv
1716){
1717 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001718 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1719 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001720 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001721 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001722
dan141e1192018-08-31 18:23:53 +00001723#ifndef SQLITE_OMIT_AUTHORIZATION
1724 sqlite3_xauth xAuth = db->xAuth;
1725 db->xAuth = 0;
1726#endif
1727
drh5b1da302018-09-01 20:02:07 +00001728 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001729 if( zDb && zInput ){
1730 int rc;
1731 Parse sParse;
drhb2ab3dc2019-12-20 14:08:34 +00001732 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan09236502018-09-01 16:05:50 +00001733 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001734 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001735 NameContext sNC;
1736 memset(&sNC, 0, sizeof(sNC));
1737 sNC.pParse = &sParse;
1738 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1739 if( sParse.nErr ) rc = sParse.rc;
1740 }
1741
1742 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001743 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001744 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001745 }
drh3b700452018-09-07 19:12:08 +00001746 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001747 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1748 int i2 = sqlite3FindDbName(db, zDb);
1749 if( i1==i2 ) sqlite3_result_int(context, 1);
1750 }
dan09236502018-09-01 16:05:50 +00001751 }
dan9d324822018-08-30 20:03:44 +00001752 }
1753
dan09236502018-09-01 16:05:50 +00001754 if( rc!=SQLITE_OK ){
1755 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001756 }
dan09236502018-09-01 16:05:50 +00001757 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001758 }
1759
dan141e1192018-08-31 18:23:53 +00001760#ifndef SQLITE_OMIT_AUTHORIZATION
1761 db->xAuth = xAuth;
1762#endif
dan9d324822018-08-30 20:03:44 +00001763}
1764
dancf8f2892018-08-09 20:47:01 +00001765/*
dan6a5a13d2021-02-17 20:08:22 +00001766** The implementation of internal UDF sqlite_drop_column().
1767**
dan6e6d9832021-02-16 20:43:36 +00001768** Arguments:
1769**
1770** argv[0]: An integer - the index of the schema containing the table
1771** argv[1]: CREATE TABLE statement to modify.
1772** argv[2]: An integer - the index of the column to remove.
1773** argv[3]: Byte offset of first byte after last column definition in argv[1]
dan6a5a13d2021-02-17 20:08:22 +00001774**
1775** The value returned is a string containing the CREATE TABLE statement
1776** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00001777*/
1778static void dropColumnFunc(
1779 sqlite3_context *context,
1780 int NotUsed,
1781 sqlite3_value **argv
1782){
1783 sqlite3 *db = sqlite3_context_db_handle(context);
1784 int iSchema = sqlite3_value_int(argv[0]);
1785 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1786 int iCol = sqlite3_value_int(argv[2]);
1787 int iAddColOffset = sqlite3_value_int(argv[3]);
1788 const char *zDb = db->aDb[iSchema].zDbSName;
1789 int rc;
1790 Parse sParse;
1791 RenameToken *pCol;
1792 Table *pTab;
1793 const char *zEnd;
1794 char *zNew = 0;
1795
1796 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
1797 if( rc!=SQLITE_OK ) goto drop_column_done;
1798 pTab = sParse.pNewTable;
1799
1800 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
1801 if( iCol<pTab->nCol-1 ){
1802 RenameToken *pEnd;
1803 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
1804 zEnd = (const char*)pEnd->t.z;
1805 }else{
1806 zEnd = (const char*)&zSql[iAddColOffset];
1807 while( pCol->t.z[0]!=',' && pCol->t.z[1]!='(' ) pCol->t.z--;
1808 }
1809
danc2a878e2021-02-17 20:46:44 +00001810 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00001811 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
1812 sqlite3_free(zNew);
1813
1814drop_column_done:
1815 renameParseCleanup(&sParse);
1816}
1817
dan6a5a13d2021-02-17 20:08:22 +00001818/*
1819** This function is called by the parser upon parsing an
1820**
1821** ALTER TABLE pSrc DROP COLUMN pName
1822**
1823** statement. Argument pSrc contains the possibly qualified name of the
1824** table being edited, and token pName the name of the column to drop.
1825*/
dan6e6d9832021-02-16 20:43:36 +00001826void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00001827 sqlite3 *db = pParse->db; /* Database handle */
1828 Table *pTab; /* Table to modify */
1829 int iDb; /* Index of db containing pTab in aDb[] */
1830 const char *zDb; /* Database containing pTab ("main" etc.) */
1831 char *zCol = 0; /* Name of column to drop */
1832 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00001833
1834 /* Look up the table being altered. */
1835 assert( pParse->pNewTable==0 );
1836 assert( sqlite3BtreeHoldsAllMutexes(db) );
1837 if( db->mallocFailed ) goto exit_drop_column;
1838 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
1839 if( !pTab ) goto exit_drop_column;
1840
dan6a5a13d2021-02-17 20:08:22 +00001841 /* Make sure this is not an attempt to ALTER a view, virtual table or
1842 ** system table. */
1843 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
1844 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00001845
1846 /* Find the index of the column being dropped. */
1847 zCol = sqlite3NameFromToken(db, pName);
1848 if( zCol==0 ){
1849 assert( db->mallocFailed );
1850 goto exit_drop_column;
1851 }
1852 iCol = sqlite3ColumnIndex(pTab, zCol);
1853 if( iCol<0 ){
1854 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
1855 goto exit_drop_column;
1856 }
1857
1858 /* Do not allow the user to drop a PRIMARY KEY column or a column
1859 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00001860 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
1861 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
1862 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
1863 zCol
1864 );
dan6e6d9832021-02-16 20:43:36 +00001865 goto exit_drop_column;
1866 }
dan6e6d9832021-02-16 20:43:36 +00001867
dan6a5a13d2021-02-17 20:08:22 +00001868 /* Edit the sqlite_schema table */
1869 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1870 assert( iDb>=0 );
1871 zDb = db->aDb[iDb].zDbSName;
dan6e6d9832021-02-16 20:43:36 +00001872 sqlite3NestedParse(pParse,
1873 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
1874 "sql = sqlite_drop_column(%d, sql, %d, %d) "
1875 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan6a5a13d2021-02-17 20:08:22 +00001876 , zDb, iDb, iCol, pTab->addColOffset, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00001877 );
1878
1879 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00001880 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
1881 renameTestSchema(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00001882
1883 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00001884 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00001885 int i;
1886 int addr;
1887 int reg;
1888 int regRec;
1889 Index *pPk = 0;
1890 int nField = 0; /* Number of non-virtual columns after drop */
1891 int iCur;
1892 Vdbe *v = sqlite3GetVdbe(pParse);
1893 iCur = pParse->nTab++;
1894 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
1895 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur);
1896 reg = ++pParse->nMem;
1897 pParse->nMem += pTab->nCol;
1898 if( HasRowid(pTab) ){
1899 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
1900 }else{
1901 pPk = sqlite3PrimaryKeyIndex(pTab);
dan6e6d9832021-02-16 20:43:36 +00001902 }
dan6a5a13d2021-02-17 20:08:22 +00001903 for(i=0; i<pTab->nCol; i++){
1904 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
1905 int regOut;
1906 if( pPk ){
1907 int iPos = sqlite3TableColumnToIndex(pPk, i);
1908 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
1909 regOut = reg+1+iPos-(iPos>iColPos);
1910 }else{
1911 regOut = reg+1+nField;
1912 }
1913 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
1914 nField++;
1915 }
1916 }
1917 regRec = reg + pTab->nCol;
1918 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
1919 if( pPk ){
1920 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
1921 }else{
1922 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
1923 }
dan6e6d9832021-02-16 20:43:36 +00001924
dan6a5a13d2021-02-17 20:08:22 +00001925 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1);
1926 sqlite3VdbeJumpHere(v, addr);
1927 }
dan6e6d9832021-02-16 20:43:36 +00001928
1929exit_drop_column:
1930 sqlite3DbFree(db, zCol);
1931 sqlite3SrcListDelete(db, pSrc);
1932 return;
1933}
1934
1935/*
dancf8f2892018-08-09 20:47:01 +00001936** Register built-in functions used to help implement ALTER TABLE
1937*/
1938void sqlite3AlterFunctions(void){
1939 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00001940 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1941 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1942 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
1943 INTERNAL_FUNCTION(sqlite_drop_column, 4, dropColumnFunc),
dancf8f2892018-08-09 20:47:01 +00001944 };
1945 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1946}
drhd0e4a6c2005-02-15 20:47:57 +00001947#endif /* SQLITE_ALTER_TABLE */