blob: a4caf715983d6b495d5ba8ae5255c7e2768518a8 [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*/
dan16953462021-02-18 19:25:44 +000052static void renameTestSchema(
53 Parse *pParse, /* Parse context */
54 const char *zDb, /* Name of db to verify schema of */
55 int bTemp, /* True if this is the temp db */
56 const char *zWhen /* "when" part of error message */
57){
drh351ae772021-02-15 13:17:19 +000058 pParse->colNamesSet = 1;
dan9d324822018-08-30 20:03:44 +000059 sqlite3NestedParse(pParse,
60 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000061 "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000062 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000063 " AND sql NOT LIKE 'create virtual%%'"
dan16953462021-02-18 19:25:44 +000064 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q)=NULL ",
drh346a70c2020-06-15 20:27:35 +000065 zDb,
dan16953462021-02-18 19:25:44 +000066 zDb, bTemp, zWhen
dan9d324822018-08-30 20:03:44 +000067 );
68
69 if( bTemp==0 ){
70 sqlite3NestedParse(pParse,
71 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000072 "FROM temp." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000073 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000074 " AND sql NOT LIKE 'create virtual%%'"
dan16953462021-02-18 19:25:44 +000075 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q)=NULL ",
76 zDb, zWhen
dan9d324822018-08-30 20:03:44 +000077 );
78 }
79}
80
danbe535002011-04-01 15:15:58 +000081/*
dan09236502018-09-01 16:05:50 +000082** Generate code to reload the schema for database iDb. And, if iDb!=1, for
83** the temp database as well.
84*/
dan6a5a13d2021-02-17 20:08:22 +000085static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
dan09236502018-09-01 16:05:50 +000086 Vdbe *v = pParse->pVdbe;
87 if( v ){
88 sqlite3ChangeCookie(pParse, iDb);
dan6a5a13d2021-02-17 20:08:22 +000089 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
90 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
dan09236502018-09-01 16:05:50 +000091 }
92}
93
94/*
drhd0e4a6c2005-02-15 20:47:57 +000095** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
96** command.
97*/
98void sqlite3AlterRenameTable(
99 Parse *pParse, /* Parser context. */
100 SrcList *pSrc, /* The table to rename. */
101 Token *pName /* The new table name. */
102){
103 int iDb; /* Database that contains the table */
104 char *zDb; /* Name of database iDb */
105 Table *pTab; /* Table being renamed */
106 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000107 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000108 int nTabName; /* Number of UTF-8 characters in zTabName */
109 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000110 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000111 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000112 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000113
drh8257aa82017-07-26 19:59:13 +0000114 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000115 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000116 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000117 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000118
dan41fb5cd2012-10-04 19:33:00 +0000119 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000120 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000121 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000122 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000123 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000124
125 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000126 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000127 if( !zName ) goto exit_rename_table;
128
129 /* Check that a table or index named 'zName' does not already exist
130 ** in database iDb. If so, this is an error.
131 */
drh3d863b52020-05-14 21:16:52 +0000132 if( sqlite3FindTable(db, zName, zDb)
133 || sqlite3FindIndex(db, zName, zDb)
134 || sqlite3IsShadowTableOf(db, pTab, zName)
135 ){
drhd0e4a6c2005-02-15 20:47:57 +0000136 sqlite3ErrorMsg(pParse,
137 "there is already another table or index with this name: %s", zName);
138 goto exit_rename_table;
139 }
140
141 /* Make sure it is not a system table being altered, or a reserved name
142 ** that the table is being renamed to.
143 */
dan397a78d2018-12-18 20:31:14 +0000144 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000145 goto exit_rename_table;
146 }
drhc5a93d42019-08-12 00:08:07 +0000147 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
148 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000149 }
150
danielk197761116ae2007-12-13 08:15:30 +0000151#ifndef SQLITE_OMIT_VIEW
152 if( pTab->pSelect ){
153 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
154 goto exit_rename_table;
155 }
156#endif
157
drhd0e4a6c2005-02-15 20:47:57 +0000158#ifndef SQLITE_OMIT_AUTHORIZATION
159 /* Invoke the authorization callback. */
160 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
161 goto exit_rename_table;
162 }
163#endif
164
danielk1977182c4ba2007-06-27 15:53:34 +0000165#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000166 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
167 goto exit_rename_table;
168 }
danielk1977595a5232009-07-24 17:58:53 +0000169 if( IsVirtual(pTab) ){
170 pVTab = sqlite3GetVTable(db, pTab);
171 if( pVTab->pVtab->pModule->xRename==0 ){
172 pVTab = 0;
173 }
danielk1977182c4ba2007-06-27 15:53:34 +0000174 }
175#endif
176
dan1f3b2842019-03-15 16:17:32 +0000177 /* Begin a transaction for database iDb. Then modify the schema cookie
178 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
179 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
180 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000181 v = sqlite3GetVdbe(pParse);
182 if( v==0 ){
183 goto exit_rename_table;
184 }
dan1f3b2842019-03-15 16:17:32 +0000185 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000186
drh4e5dd852007-05-15 03:56:49 +0000187 /* figure out how many UTF-8 characters are in zName */
188 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000189 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000190
danc9461ec2018-08-29 21:00:16 +0000191 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
192 ** the schema to use the new table name. */
193 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000194 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan65372fa2018-09-03 20:05:15 +0000195 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000196 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000197 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
drh346a70c2020-06-15 20:27:35 +0000198 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000199 );
dan432cc5b2009-09-26 17:51:48 +0000200
drh1e32bed2020-06-19 13:33:53 +0000201 /* Update the tbl_name and name columns of the sqlite_schema table
danc9461ec2018-08-29 21:00:16 +0000202 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000203 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000204 "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
drhd0e4a6c2005-02-15 20:47:57 +0000205 "tbl_name = %Q, "
206 "name = CASE "
207 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000208 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
209 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000210 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000211 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000212 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000213 "(type='table' OR type='index' OR type='trigger');",
drh346a70c2020-06-15 20:27:35 +0000214 zDb,
danc9461ec2018-08-29 21:00:16 +0000215 zName, zName, zName,
216 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000217 );
218
219#ifndef SQLITE_OMIT_AUTOINCREMENT
220 /* If the sqlite_sequence table exists in this database, then update
221 ** it with the new table name.
222 */
223 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
224 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000225 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000226 zDb, zName, pTab->zName);
227 }
228#endif
229
danc9461ec2018-08-29 21:00:16 +0000230 /* If the table being renamed is not itself part of the temp database,
231 ** edit view and trigger definitions within the temp database
232 ** as required. */
233 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000234 sqlite3NestedParse(pParse,
drh1e32bed2020-06-19 13:33:53 +0000235 "UPDATE sqlite_temp_schema SET "
dan65372fa2018-09-03 20:05:15 +0000236 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000237 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000238 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
dan16953462021-02-18 19:25:44 +0000239 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename') "
dan1d85c6b2018-09-06 16:01:37 +0000240 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000241 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000242 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000243 }
drhd0e4a6c2005-02-15 20:47:57 +0000244
dan34566c42018-09-20 17:21:21 +0000245 /* If this is a virtual table, invoke the xRename() function if
246 ** one is defined. The xRename() callback will modify the names
247 ** of any resources used by the v-table implementation (including other
248 ** SQLite tables) that are identified by the name of the virtual table.
249 */
250#ifndef SQLITE_OMIT_VIRTUALTABLE
251 if( pVTab ){
252 int i = ++pParse->nMem;
253 sqlite3VdbeLoadString(v, i, zName);
254 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000255 }
256#endif
257
dan6a5a13d2021-02-17 20:08:22 +0000258 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
dan16953462021-02-18 19:25:44 +0000259 renameTestSchema(pParse, zDb, iDb==1, "after rename");
dan9d324822018-08-30 20:03:44 +0000260
drhd0e4a6c2005-02-15 20:47:57 +0000261exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000262 sqlite3SrcListDelete(db, pSrc);
263 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000264 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000265}
danielk197719a8e7e2005-03-17 05:03:38 +0000266
drhd3001712009-05-12 17:46:53 +0000267/*
drh9e5fdc42020-05-08 19:02:21 +0000268** Write code that will raise an error if the table described by
269** zDb and zTab is not empty.
270*/
271static void sqlite3ErrorIfNotEmpty(
272 Parse *pParse, /* Parsing context */
273 const char *zDb, /* Schema holding the table */
274 const char *zTab, /* Table to check for empty */
275 const char *zErr /* Error message text */
276){
277 sqlite3NestedParse(pParse,
278 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
279 zErr, zDb, zTab
280 );
281}
282
283/*
danielk197719a8e7e2005-03-17 05:03:38 +0000284** This function is called after an "ALTER TABLE ... ADD" statement
285** has been parsed. Argument pColDef contains the text of the new
286** column definition.
287**
288** The Table structure pParse->pNewTable was extended to include
289** the new column during parsing.
290*/
291void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
292 Table *pNew; /* Copy of pParse->pNewTable */
293 Table *pTab; /* Table being altered */
294 int iDb; /* Database number */
295 const char *zDb; /* Database name */
296 const char *zTab; /* Table name */
297 char *zCol; /* Null-terminated column definition */
298 Column *pCol; /* The new column */
299 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000300 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000301 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000302 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000303
danielk1977f150c9d2008-10-30 17:21:12 +0000304 db = pParse->db;
305 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000306 pNew = pParse->pNewTable;
307 assert( pNew );
308
drh1fee73e2007-08-29 04:00:57 +0000309 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000310 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000311 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000312 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000313 pCol = &pNew->aCol[pNew->nCol-1];
314 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000315 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000316 assert( pTab );
317
drh81f2ccd2006-01-31 14:28:44 +0000318#ifndef SQLITE_OMIT_AUTHORIZATION
319 /* Invoke the authorization callback. */
320 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
321 return;
322 }
323#endif
324
danielk197719a8e7e2005-03-17 05:03:38 +0000325
326 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
327 ** If there is a NOT NULL constraint, then the default value for the
328 ** column must not be NULL.
329 */
drha371ace2012-09-13 14:22:47 +0000330 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000331 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
332 return;
333 }
334 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000335 sqlite3ErrorMsg(pParse,
336 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000337 return;
338 }
drhc27ea2a2019-10-16 20:05:56 +0000339 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
340 /* If the default value for the new column was specified with a
341 ** literal NULL, then set pDflt to 0. This simplifies checking
342 ** for an SQL NULL default below.
343 */
344 assert( pDflt==0 || pDflt->op==TK_SPAN );
345 if( pDflt && pDflt->pLeft->op==TK_NULL ){
346 pDflt = 0;
347 }
348 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000349 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000350 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000351 }
352 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000353 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000354 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000355 }
356
drh9e5fdc42020-05-08 19:02:21 +0000357
drhc27ea2a2019-10-16 20:05:56 +0000358 /* Ensure the default expression is something that sqlite3ValueFromExpr()
359 ** can handle (i.e. not CURRENT_TIME etc.)
360 */
361 if( pDflt ){
362 sqlite3_value *pVal = 0;
363 int rc;
364 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
365 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
366 if( rc!=SQLITE_OK ){
367 assert( db->mallocFailed == 1 );
368 return;
369 }
370 if( !pVal ){
drh9e5fdc42020-05-08 19:02:21 +0000371 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
372 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000373 }
374 sqlite3ValueFree(pVal);
375 }
drh035f6d92019-10-24 01:04:10 +0000376 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000377 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000378 }
379
danielk197719a8e7e2005-03-17 05:03:38 +0000380
381 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000382 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000383 if( zCol ){
384 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000385 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000386 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000387 *zEnd-- = '\0';
388 }
drh8257aa82017-07-26 19:59:13 +0000389 db->mDbFlags |= DBFLAG_PreferBuiltin;
drh37114fb2021-01-01 20:04:34 +0000390 /* substr() operations on characters, but addColOffset is in bytes. So we
391 ** have to use printf() to translate between these units: */
danielk197719a8e7e2005-03-17 05:03:38 +0000392 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000393 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000394 "sql = printf('%%.%ds, ',sql) || %Q"
395 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000396 "WHERE type = 'table' AND name = %Q",
drh37114fb2021-01-01 20:04:34 +0000397 zDb, pNew->addColOffset, zCol, pNew->addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000398 zTab
399 );
drh633e6d52008-07-28 19:34:53 +0000400 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000401 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000402 }
403
drh86396212016-07-14 19:13:11 +0000404 /* Make sure the schema version is at least 3. But do not upgrade
405 ** from less than 3 to 4, as that will corrupt any preexisting DESC
406 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000407 */
dan09236502018-09-01 16:05:50 +0000408 v = sqlite3GetVdbe(pParse);
409 if( v ){
410 r1 = sqlite3GetTempReg(pParse);
411 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
412 sqlite3VdbeUsesBtree(v, iDb);
413 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
414 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
415 VdbeCoverage(v);
416 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
417 sqlite3ReleaseTempReg(pParse, r1);
418 }
danielk197719a8e7e2005-03-17 05:03:38 +0000419
dan09236502018-09-01 16:05:50 +0000420 /* Reload the table definition */
dan6a5a13d2021-02-17 20:08:22 +0000421 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
danielk197719a8e7e2005-03-17 05:03:38 +0000422}
423
drhfdd6e852005-12-16 01:06:16 +0000424/*
danielk197719a8e7e2005-03-17 05:03:38 +0000425** This function is called by the parser after the table-name in
426** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
427** pSrc is the full-name of the table being altered.
428**
429** This routine makes a (partial) copy of the Table structure
430** for the table being altered and sets Parse.pNewTable to point
431** to it. Routines called by the parser as the column definition
432** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
433** the copy. The copy of the Table structure is deleted by tokenize.c
434** after parsing is finished.
435**
436** Routine sqlite3AlterFinishAddColumn() will be called to complete
437** coding the "ALTER TABLE ... ADD" statement.
438*/
439void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
440 Table *pNew;
441 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000442 int iDb;
443 int i;
444 int nAlloc;
drh17435752007-08-16 04:30:38 +0000445 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000446
447 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000448 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000449 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000450 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000451 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000452 if( !pTab ) goto exit_begin_add_column;
453
danielk19775ee9d692006-06-21 12:36:25 +0000454#ifndef SQLITE_OMIT_VIRTUALTABLE
455 if( IsVirtual(pTab) ){
456 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
457 goto exit_begin_add_column;
458 }
459#endif
460
danielk197719a8e7e2005-03-17 05:03:38 +0000461 /* Make sure this is not an attempt to ALTER a view. */
462 if( pTab->pSelect ){
463 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
464 goto exit_begin_add_column;
465 }
dan397a78d2018-12-18 20:31:14 +0000466 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000467 goto exit_begin_add_column;
468 }
danielk197719a8e7e2005-03-17 05:03:38 +0000469
dan03e025e2019-10-07 18:43:21 +0000470 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000471 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000472 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000473
474 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000475 ** sqlite3AddColumn() function and friends to modify. But modify
476 ** the name by adding an "sqlite_altertab_" prefix. By adding this
477 ** prefix, we insure that the name will not collide with an existing
478 ** table because user table are not allowed to have the "sqlite_"
479 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000480 */
drh17435752007-08-16 04:30:38 +0000481 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000482 if( !pNew ) goto exit_begin_add_column;
483 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000484 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000485 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000486 assert( pNew->nCol>0 );
487 nAlloc = (((pNew->nCol-1)/8)*8)+8;
488 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000489 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000490 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000491 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000492 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000493 goto exit_begin_add_column;
494 }
495 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
496 for(i=0; i<pNew->nCol; i++){
497 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000498 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000499 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000500 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000501 pCol->pDflt = 0;
502 }
drh17435752007-08-16 04:30:38 +0000503 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000504 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000505 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000506
danielk197719a8e7e2005-03-17 05:03:38 +0000507exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000508 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000509 return;
510}
dancf8f2892018-08-09 20:47:01 +0000511
drh4a2c7472018-08-13 15:09:48 +0000512/*
dan9d705572018-08-20 16:16:05 +0000513** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
514** command. This function checks if the table is a view or virtual
515** table (columns of views or virtual tables may not be renamed). If so,
516** it loads an error message into pParse and returns non-zero.
517**
518** Or, if pTab is not a view or virtual table, zero is returned.
519*/
520#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000521static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000522 const char *zType = 0;
523#ifndef SQLITE_OMIT_VIEW
524 if( pTab->pSelect ){
525 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000526 }
dan9d705572018-08-20 16:16:05 +0000527#endif
528#ifndef SQLITE_OMIT_VIRTUALTABLE
529 if( IsVirtual(pTab) ){
530 zType = "virtual table";
531 }
532#endif
533 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000534 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
535 (bDrop ? "drop column from" : "rename columns of"),
536 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000537 );
538 return 1;
539 }
540 return 0;
541}
542#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000543# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000544#endif
545
546/*
drh4a2c7472018-08-13 15:09:48 +0000547** Handles the following parser reduction:
548**
549** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
550*/
dancf8f2892018-08-09 20:47:01 +0000551void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000552 Parse *pParse, /* Parsing context */
553 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
554 Token *pOld, /* Name of column being changed */
555 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000556){
drh4a2c7472018-08-13 15:09:48 +0000557 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000558 Table *pTab; /* Table being updated */
559 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000560 char *zOld = 0; /* Old column name */
561 char *zNew = 0; /* New column name */
562 const char *zDb; /* Name of schema containing the table */
563 int iSchema; /* Index of the schema */
564 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000565
drh4a2c7472018-08-13 15:09:48 +0000566 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000567 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
568 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000569
570 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000571 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000572 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000573
574 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000575 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
576 assert( iSchema>=0 );
577 zDb = db->aDb[iSchema].zDbSName;
578
drh0d019b92018-08-25 16:14:46 +0000579#ifndef SQLITE_OMIT_AUTHORIZATION
580 /* Invoke the authorization callback. */
581 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
582 goto exit_rename_column;
583 }
584#endif
585
drh4a2c7472018-08-13 15:09:48 +0000586 /* Make sure the old name really is a column name in the table to be
587 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000588 zOld = sqlite3NameFromToken(db, pOld);
589 if( !zOld ) goto exit_rename_column;
590 for(iCol=0; iCol<pTab->nCol; iCol++){
591 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
592 }
593 if( iCol==pTab->nCol ){
594 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
595 goto exit_rename_column;
596 }
597
drh4a2c7472018-08-13 15:09:48 +0000598 /* Do the rename operation using a recursive UPDATE statement that
599 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000600 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000601 */
dan1f3b2842019-03-15 16:17:32 +0000602 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000603 zNew = sqlite3NameFromToken(db, pNew);
604 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000605 assert( pNew->n>0 );
606 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000607 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000608 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000609 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000610 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
611 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000612 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000613 zDb,
danb87a9a82018-09-01 20:23:28 +0000614 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000615 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000616 );
617
dan9d324822018-08-30 20:03:44 +0000618 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000619 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000620 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000621 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000622 zDb, pTab->zName, iCol, zNew, bQuote
623 );
624
dane325ffe2018-08-11 13:40:20 +0000625 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000626 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan16953462021-02-18 19:25:44 +0000627 renameTestSchema(pParse, zDb, iSchema==1, "after rename");
dan0d5fa6b2018-08-24 17:55:49 +0000628
dancf8f2892018-08-09 20:47:01 +0000629 exit_rename_column:
630 sqlite3SrcListDelete(db, pSrc);
631 sqlite3DbFree(db, zOld);
632 sqlite3DbFree(db, zNew);
633 return;
634}
635
drh4a2c7472018-08-13 15:09:48 +0000636/*
637** Each RenameToken object maps an element of the parse tree into
638** the token that generated that element. The parse tree element
639** might be one of:
640**
641** * A pointer to an Expr that represents an ID
642** * The name of a table column in Column.zName
643**
644** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000645** Each new object is created by sqlite3RenameTokenMap().
646** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000647** routine is used to keep the mapping current.
648**
649** After the parse finishes, renameTokenFind() routine can be used
650** to look up the actual token value that created some element in
651** the parse tree.
652*/
dancf8f2892018-08-09 20:47:01 +0000653struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000654 void *p; /* Parse tree element created by token t */
655 Token t; /* The token that created parse tree element p */
656 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000657};
658
drh4a2c7472018-08-13 15:09:48 +0000659/*
660** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
661** down into the Walker.
662*/
dan5496d6a2018-08-13 17:14:26 +0000663typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000664struct RenameCtx {
665 RenameToken *pList; /* List of tokens to overwrite */
666 int nList; /* Number of tokens in pList */
667 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000668 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000669 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000670};
671
dan8900a482018-09-05 14:36:05 +0000672#ifdef SQLITE_DEBUG
673/*
674** This function is only for debugging. It performs two tasks:
675**
676** 1. Checks that pointer pPtr does not already appear in the
677** rename-token list.
678**
679** 2. Dereferences each pointer in the rename-token list.
680**
681** The second is most effective when debugging under valgrind or
682** address-sanitizer or similar. If any of these pointers no longer
683** point to valid objects, an exception is raised by the memory-checking
684** tool.
685**
686** The point of this is to prevent comparisons of invalid pointer values.
687** Even though this always seems to work, it is undefined according to the
688** C standard. Example of undefined comparison:
689**
690** sqlite3_free(x);
691** if( x==y ) ...
692**
693** Technically, as x no longer points into a valid object or to the byte
694** following a valid object, it may not be used in comparison operations.
695*/
drh16b870d2018-09-12 15:51:56 +0000696static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000697 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
698 RenameToken *p;
699 u8 i = 0;
700 for(p=pParse->pRename; p; p=p->pNext){
701 if( p->p ){
702 assert( p->p!=pPtr );
703 i += *(u8*)(p->p);
704 }
danc9461ec2018-08-29 21:00:16 +0000705 }
706 }
707}
dan8900a482018-09-05 14:36:05 +0000708#else
709# define renameTokenCheckAll(x,y)
710#endif
danc9461ec2018-08-29 21:00:16 +0000711
drh4a2c7472018-08-13 15:09:48 +0000712/*
drh49b269e2018-11-26 15:00:25 +0000713** Remember that the parser tree element pPtr was created using
714** the token pToken.
dan07e95232018-08-21 16:32:53 +0000715**
drh49b269e2018-11-26 15:00:25 +0000716** In other words, construct a new RenameToken object and add it
717** to the list of RenameToken objects currently being built up
718** in pParse->pRename.
719**
720** The pPtr argument is returned so that this routine can be used
721** with tail recursion in tokenExpr() routine, for a small performance
722** improvement.
drh4a2c7472018-08-13 15:09:48 +0000723*/
dan07e95232018-08-21 16:32:53 +0000724void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000725 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000726 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000727 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000728 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000729 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
730 if( pNew ){
731 pNew->p = pPtr;
732 pNew->t = *pToken;
733 pNew->pNext = pParse->pRename;
734 pParse->pRename = pNew;
735 }
dancf8f2892018-08-09 20:47:01 +0000736 }
danc9461ec2018-08-29 21:00:16 +0000737
dand145e5f2018-08-21 08:29:48 +0000738 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000739}
740
drh4a2c7472018-08-13 15:09:48 +0000741/*
dan07e95232018-08-21 16:32:53 +0000742** It is assumed that there is already a RenameToken object associated
743** with parse tree element pFrom. This function remaps the associated token
744** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000745*/
dan07e95232018-08-21 16:32:53 +0000746void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000747 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000748 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000749 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000750 if( p->p==pFrom ){
751 p->p = pTo;
752 break;
753 }
754 }
dancf8f2892018-08-09 20:47:01 +0000755}
756
drh4a2c7472018-08-13 15:09:48 +0000757/*
dan8900a482018-09-05 14:36:05 +0000758** Walker callback used by sqlite3RenameExprUnmap().
759*/
760static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
761 Parse *pParse = pWalker->pParse;
762 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
763 return WRC_Continue;
764}
765
766/*
dan8f407622019-12-04 14:26:38 +0000767** Iterate through the Select objects that are part of WITH clauses attached
768** to select statement pSelect.
769*/
770static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000771 With *pWith = pSelect->pWith;
772 if( pWith ){
dan8f407622019-12-04 14:26:38 +0000773 int i;
drh646975c2019-12-17 12:03:30 +0000774 for(i=0; i<pWith->nCte; i++){
775 Select *p = pWith->a[i].pSelect;
dan8f407622019-12-04 14:26:38 +0000776 NameContext sNC;
777 memset(&sNC, 0, sizeof(sNC));
778 sNC.pParse = pWalker->pParse;
779 sqlite3SelectPrep(sNC.pParse, p, &sNC);
780 sqlite3WalkSelect(pWalker, p);
drh646975c2019-12-17 12:03:30 +0000781 sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
dan8f407622019-12-04 14:26:38 +0000782 }
783 }
784}
785
786/*
danfb99e382020-04-03 11:20:40 +0000787** Unmap all tokens in the IdList object passed as the second argument.
788*/
789static void unmapColumnIdlistNames(
790 Parse *pParse,
791 IdList *pIdList
792){
793 if( pIdList ){
794 int ii;
795 for(ii=0; ii<pIdList->nId; ii++){
796 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
797 }
798 }
799}
800
801/*
dan0b277a92019-06-11 12:03:10 +0000802** Walker callback used by sqlite3RenameExprUnmap().
803*/
804static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000805 Parse *pParse = pWalker->pParse;
806 int i;
drhd63b69b2019-12-04 15:08:58 +0000807 if( pParse->nErr ) return WRC_Abort;
drh2bc5cf92019-12-09 19:29:10 +0000808 if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
drhbdf4cf02019-06-15 15:21:49 +0000809 if( ALWAYS(p->pEList) ){
810 ExprList *pList = p->pEList;
811 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000812 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000813 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000814 }
815 }
816 }
drh2c3f4652019-06-11 16:43:58 +0000817 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000818 SrcList *pSrc = p->pSrc;
819 for(i=0; i<pSrc->nSrc; i++){
820 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000821 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000822 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000823 }
824 }
dan8f407622019-12-04 14:26:38 +0000825
826 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000827 return WRC_Continue;
828}
829
830/*
dan8900a482018-09-05 14:36:05 +0000831** Remove all nodes that are part of expression pExpr from the rename list.
832*/
833void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000834 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000835 Walker sWalker;
836 memset(&sWalker, 0, sizeof(Walker));
837 sWalker.pParse = pParse;
838 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000839 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000840 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000841 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000842 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000843}
844
845/*
dane8ab40d2018-09-12 08:51:48 +0000846** Remove all nodes that are part of expression-list pEList from the
847** rename list.
848*/
849void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
850 if( pEList ){
851 int i;
852 Walker sWalker;
853 memset(&sWalker, 0, sizeof(Walker));
854 sWalker.pParse = pParse;
855 sWalker.xExprCallback = renameUnmapExprCb;
856 sqlite3WalkExprList(&sWalker, pEList);
857 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000858 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000859 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
860 }
dane8ab40d2018-09-12 08:51:48 +0000861 }
862 }
863}
864
865/*
drh4a2c7472018-08-13 15:09:48 +0000866** Free the list of RenameToken objects given in the second argument
867*/
dancf8f2892018-08-09 20:47:01 +0000868static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
869 RenameToken *pNext;
870 RenameToken *p;
871 for(p=pToken; p; p=pNext){
872 pNext = p->pNext;
873 sqlite3DbFree(db, p);
874 }
875}
876
dan987db762018-08-14 20:18:50 +0000877/*
878** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000879** object associated with parse tree element pPtr. If found, return a pointer
880** to it. Otherwise, return NULL.
881**
882** If the second argument passed to this function is not NULL and a matching
883** RenameToken object is found, remove it from the Parse object and add it to
884** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000885*/
dan6e6d9832021-02-16 20:43:36 +0000886static RenameToken *renameTokenFind(
887 Parse *pParse,
888 struct RenameCtx *pCtx,
889 void *pPtr
890){
dancf8f2892018-08-09 20:47:01 +0000891 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000892 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000893 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
894 if( (*pp)->p==pPtr ){
895 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000896 if( pCtx ){
897 *pp = pToken->pNext;
898 pToken->pNext = pCtx->pList;
899 pCtx->pList = pToken;
900 pCtx->nList++;
901 }
902 return pToken;
dancf8f2892018-08-09 20:47:01 +0000903 }
904 }
dan6e6d9832021-02-16 20:43:36 +0000905 return 0;
dancf8f2892018-08-09 20:47:01 +0000906}
907
dan24fedb92018-08-18 17:35:38 +0000908/*
909** This is a Walker select callback. It does nothing. It is only required
910** because without a dummy callback, sqlite3WalkExpr() and similar do not
911** descend into sub-select statements.
912*/
dan987db762018-08-14 20:18:50 +0000913static int renameColumnSelectCb(Walker *pWalker, Select *p){
dan38096962019-12-09 08:13:43 +0000914 if( p->selFlags & SF_View ) return WRC_Prune;
danea412512018-12-05 13:49:04 +0000915 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000916 return WRC_Continue;
917}
918
dan987db762018-08-14 20:18:50 +0000919/*
920** This is a Walker expression callback.
921**
922** For every TK_COLUMN node in the expression tree, search to see
923** if the column being references is the column being renamed by an
924** ALTER TABLE statement. If it is, then attach its associated
925** RenameToken object to the list of RenameToken objects being
926** constructed in RenameCtx object at pWalker->u.pRename.
927*/
dancf8f2892018-08-09 20:47:01 +0000928static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000929 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000930 if( pExpr->op==TK_TRIGGER
931 && pExpr->iColumn==p->iCol
932 && pWalker->pParse->pTriggerTab==p->pTab
933 ){
dan5be60c52018-08-15 20:28:39 +0000934 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000935 }else if( pExpr->op==TK_COLUMN
936 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000937 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000938 ){
dan5496d6a2018-08-13 17:14:26 +0000939 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000940 }
941 return WRC_Continue;
942}
943
dan987db762018-08-14 20:18:50 +0000944/*
945** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000946** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000947** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000948** RenameContext. "Last" means the last RenameToken encountered when
949** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000950** return all column name tokens in the order that they are encountered
951** in the SQL statement.
952*/
dan5496d6a2018-08-13 17:14:26 +0000953static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000954 RenameToken *pBest = pCtx->pList;
955 RenameToken *pToken;
956 RenameToken **pp;
957
958 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
959 if( pToken->t.z>pBest->t.z ) pBest = pToken;
960 }
961 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
962 *pp = pBest->pNext;
963
964 return pBest;
965}
966
dan6fe7f232018-08-10 19:19:33 +0000967/*
dan24fedb92018-08-18 17:35:38 +0000968** An error occured while parsing or otherwise processing a database
969** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
970** ALTER TABLE RENAME COLUMN program. The error message emitted by the
971** sub-routine is currently stored in pParse->zErrMsg. This function
972** adds context to the error message and then stores it in pCtx.
973*/
danb0137382018-08-20 20:01:01 +0000974static void renameColumnParseError(
975 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +0000976 const char *zWhen,
danb0137382018-08-20 20:01:01 +0000977 sqlite3_value *pType,
978 sqlite3_value *pObject,
979 Parse *pParse
980){
drh79a5ee92018-08-23 19:32:04 +0000981 const char *zT = (const char*)sqlite3_value_text(pType);
982 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000983 char *zErr;
danb0137382018-08-20 20:01:01 +0000984
dan16953462021-02-18 19:25:44 +0000985 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
986 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +0000987 pParse->zErrMsg
988 );
dan24fedb92018-08-18 17:35:38 +0000989 sqlite3_result_error(pCtx, zErr, -1);
990 sqlite3_free(zErr);
991}
992
993/*
dan06249392018-08-21 15:06:59 +0000994** For each name in the the expression-list pEList (i.e. each
995** pEList->a[i].zName) that matches the string in zOld, extract the
996** corresponding rename-token from Parse object pParse and add it
997** to the RenameCtx pCtx.
998*/
999static void renameColumnElistNames(
1000 Parse *pParse,
1001 RenameCtx *pCtx,
1002 ExprList *pEList,
1003 const char *zOld
1004){
1005 if( pEList ){
1006 int i;
1007 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001008 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001009 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1010 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001011 && 0==sqlite3_stricmp(zName, zOld)
1012 ){
dan06249392018-08-21 15:06:59 +00001013 renameTokenFind(pParse, pCtx, (void*)zName);
1014 }
1015 }
1016 }
1017}
1018
1019/*
1020** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1021** that matches the string in zOld, extract the corresponding rename-token
1022** from Parse object pParse and add it to the RenameCtx pCtx.
1023*/
1024static void renameColumnIdlistNames(
1025 Parse *pParse,
1026 RenameCtx *pCtx,
1027 IdList *pIdList,
1028 const char *zOld
1029){
1030 if( pIdList ){
1031 int i;
1032 for(i=0; i<pIdList->nId; i++){
1033 char *zName = pIdList->a[i].zName;
1034 if( 0==sqlite3_stricmp(zName, zOld) ){
1035 renameTokenFind(pParse, pCtx, (void*)zName);
1036 }
1037 }
1038 }
1039}
1040
danfb99e382020-04-03 11:20:40 +00001041
dandd1a9c82018-09-05 08:28:30 +00001042/*
1043** Parse the SQL statement zSql using Parse object (*p). The Parse object
1044** is initialized by this function before it is used.
1045*/
danc9461ec2018-08-29 21:00:16 +00001046static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001047 Parse *p, /* Memory to use for Parse object */
1048 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001049 sqlite3 *db, /* Database handle */
1050 const char *zSql, /* SQL to parse */
1051 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001052){
1053 int rc;
1054 char *zErr = 0;
1055
1056 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1057
1058 /* Parse the SQL statement passed as the first argument. If no error
1059 ** occurs and the parse does not result in a new table, index or
1060 ** trigger object, the database must be corrupt. */
1061 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001062 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001063 p->db = db;
1064 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001065 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001066 assert( p->zErrMsg==0 );
1067 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001068 p->zErrMsg = zErr;
1069 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1070 if( rc==SQLITE_OK
1071 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1072 ){
1073 rc = SQLITE_CORRUPT_BKPT;
1074 }
1075
1076#ifdef SQLITE_DEBUG
1077 /* Ensure that all mappings in the Parse.pRename list really do map to
1078 ** a part of the input string. */
1079 if( rc==SQLITE_OK ){
1080 int nSql = sqlite3Strlen30(zSql);
1081 RenameToken *pToken;
1082 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1083 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1084 }
1085 }
1086#endif
1087
1088 db->init.iDb = 0;
1089 return rc;
1090}
1091
dandd1a9c82018-09-05 08:28:30 +00001092/*
1093** This function edits SQL statement zSql, replacing each token identified
1094** by the linked list pRename with the text of zNew. If argument bQuote is
1095** true, then zNew is always quoted first. If no error occurs, the result
1096** is loaded into context object pCtx as the result.
1097**
1098** Or, if an error occurs (i.e. an OOM condition), an error is left in
1099** pCtx and an SQLite error code returned.
1100*/
danc9461ec2018-08-29 21:00:16 +00001101static int renameEditSql(
1102 sqlite3_context *pCtx, /* Return result here */
1103 RenameCtx *pRename, /* Rename context */
1104 const char *zSql, /* SQL statement to edit */
1105 const char *zNew, /* New token text */
1106 int bQuote /* True to always quote token */
1107){
1108 int nNew = sqlite3Strlen30(zNew);
1109 int nSql = sqlite3Strlen30(zSql);
1110 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1111 int rc = SQLITE_OK;
1112 char *zQuot;
1113 char *zOut;
1114 int nQuot;
1115
1116 /* Set zQuot to point to a buffer containing a quoted copy of the
1117 ** identifier zNew. If the corresponding identifier in the original
1118 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1119 ** point to zQuot so that all substitutions are made using the
1120 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001121 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001122 if( zQuot==0 ){
1123 return SQLITE_NOMEM;
1124 }else{
1125 nQuot = sqlite3Strlen30(zQuot);
1126 }
1127 if( bQuote ){
1128 zNew = zQuot;
1129 nNew = nQuot;
1130 }
1131
1132 /* At this point pRename->pList contains a list of RenameToken objects
1133 ** corresponding to all tokens in the input SQL that must be replaced
1134 ** with the new column name. All that remains is to construct and
1135 ** return the edited SQL string. */
1136 assert( nQuot>=nNew );
1137 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1138 if( zOut ){
1139 int nOut = nSql;
1140 memcpy(zOut, zSql, nSql);
1141 while( pRename->pList ){
1142 int iOff; /* Offset of token to replace in zOut */
1143 RenameToken *pBest = renameColumnTokenNext(pRename);
1144
1145 u32 nReplace;
1146 const char *zReplace;
1147 if( sqlite3IsIdChar(*pBest->t.z) ){
1148 nReplace = nNew;
1149 zReplace = zNew;
1150 }else{
1151 nReplace = nQuot;
1152 zReplace = zQuot;
1153 }
1154
1155 iOff = pBest->t.z - zSql;
1156 if( pBest->t.n!=nReplace ){
1157 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1158 nOut - (iOff + pBest->t.n)
1159 );
1160 nOut += nReplace - pBest->t.n;
1161 zOut[nOut] = '\0';
1162 }
1163 memcpy(&zOut[iOff], zReplace, nReplace);
1164 sqlite3DbFree(db, pBest);
1165 }
1166
1167 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1168 sqlite3DbFree(db, zOut);
1169 }else{
1170 rc = SQLITE_NOMEM;
1171 }
1172
1173 sqlite3_free(zQuot);
1174 return rc;
1175}
1176
dandd1a9c82018-09-05 08:28:30 +00001177/*
1178** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1179** it was read from the schema of database zDb. Return SQLITE_OK if
1180** successful. Otherwise, return an SQLite error code and leave an error
1181** message in the Parse object.
1182*/
drha7c74002020-07-18 18:44:59 +00001183static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001184 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001185 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001186 TriggerStep *pStep;
1187 NameContext sNC;
1188 int rc = SQLITE_OK;
1189
1190 memset(&sNC, 0, sizeof(sNC));
1191 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001192 assert( pNew->pTabSchema );
1193 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1194 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1195 );
1196 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001197 /* ALWAYS() because if the table of the trigger does not exist, the
1198 ** error would have been hit before this point */
1199 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001200 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1201 }
danc9461ec2018-08-29 21:00:16 +00001202
1203 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001204 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001205 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001206 }
1207
dand5e6fef2018-09-07 15:50:31 +00001208 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001209 if( pStep->pSelect ){
1210 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1211 if( pParse->nErr ) rc = pParse->rc;
1212 }
dand5e6fef2018-09-07 15:50:31 +00001213 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001214 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1215 if( pSrc ){
1216 int i;
drha3e64952020-08-12 16:19:12 +00001217 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
dane7877b22020-07-14 19:51:01 +00001218 struct SrcList_item *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001219 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001220 if( p->pSelect ){
1221 sqlite3SelectPrep(pParse, p->pSelect, 0);
1222 sqlite3ExpandSubquery(pParse, p);
1223 assert( i>0 );
1224 assert( pStep->pFrom->a[i-1].pSelect );
1225 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001226 }else{
dan7a39fae2020-10-31 16:33:01 +00001227 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1228 if( p->pTab==0 ){
1229 rc = SQLITE_ERROR;
1230 }else{
1231 p->pTab->nTabRef++;
1232 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1233 }
dane7877b22020-07-14 19:51:01 +00001234 }
1235 }
1236 sNC.pSrcList = pSrc;
1237 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001238 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1239 }
1240 if( rc==SQLITE_OK ){
1241 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1242 }
1243 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1244 if( pStep->pUpsert ){
1245 Upsert *pUpsert = pStep->pUpsert;
1246 assert( rc==SQLITE_OK );
dane7877b22020-07-14 19:51:01 +00001247 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001248 sNC.uNC.pUpsert = pUpsert;
1249 sNC.ncFlags = NC_UUpsert;
1250 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1251 if( rc==SQLITE_OK ){
1252 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1253 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1254 }
1255 if( rc==SQLITE_OK ){
1256 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1257 }
1258 if( rc==SQLITE_OK ){
1259 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1260 }
1261 sNC.ncFlags = 0;
1262 }
dan0e14e982019-01-18 16:06:18 +00001263 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001264 sqlite3SrcListDelete(db, pSrc);
1265 }else{
1266 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001267 }
1268 }
1269 }
1270 return rc;
1271}
1272
dandd1a9c82018-09-05 08:28:30 +00001273/*
1274** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1275** objects that are part of the trigger passed as the second argument.
1276*/
danc9461ec2018-08-29 21:00:16 +00001277static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1278 TriggerStep *pStep;
1279
1280 /* Find tokens to edit in WHEN clause */
1281 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1282
1283 /* Find tokens to edit in trigger steps */
1284 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1285 sqlite3WalkSelect(pWalker, pStep->pSelect);
1286 sqlite3WalkExpr(pWalker, pStep->pWhere);
1287 sqlite3WalkExprList(pWalker, pStep->pExprList);
1288 if( pStep->pUpsert ){
1289 Upsert *pUpsert = pStep->pUpsert;
1290 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1291 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1292 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1293 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1294 }
dan7a39fae2020-10-31 16:33:01 +00001295 if( pStep->pFrom ){
1296 int i;
1297 for(i=0; i<pStep->pFrom->nSrc; i++){
1298 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1299 }
1300 }
danc9461ec2018-08-29 21:00:16 +00001301 }
1302}
1303
dandd1a9c82018-09-05 08:28:30 +00001304/*
1305** Free the contents of Parse object (*pParse). Do not free the memory
1306** occupied by the Parse object itself.
1307*/
dan141e1192018-08-31 18:23:53 +00001308static void renameParseCleanup(Parse *pParse){
1309 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001310 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001311 if( pParse->pVdbe ){
1312 sqlite3VdbeFinalize(pParse->pVdbe);
1313 }
1314 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001315 while( (pIdx = pParse->pNewIndex)!=0 ){
1316 pParse->pNewIndex = pIdx->pNext;
1317 sqlite3FreeIndex(db, pIdx);
1318 }
dan141e1192018-08-31 18:23:53 +00001319 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1320 sqlite3DbFree(db, pParse->zErrMsg);
1321 renameTokenFree(db, pParse->pRename);
1322 sqlite3ParserReset(pParse);
1323}
1324
dan06249392018-08-21 15:06:59 +00001325/*
dan987db762018-08-14 20:18:50 +00001326** SQL function:
1327**
1328** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1329**
1330** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001331** 1. type: Type of object ("table", "view" etc.)
1332** 2. object: Name of object
1333** 3. Database: Database name (e.g. "main")
1334** 4. Table: Table name
1335** 5. iCol: Index of column to rename
1336** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001337** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001338** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001339**
1340** Do a column rename operation on the CREATE statement given in zSql.
1341** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1342** into zNew. The name should be quoted if bQuote is true.
1343**
1344** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001345** It is only accessible to SQL created using sqlite3NestedParse(). It is
1346** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001347*/
dancf8f2892018-08-09 20:47:01 +00001348static void renameColumnFunc(
1349 sqlite3_context *context,
1350 int NotUsed,
1351 sqlite3_value **argv
1352){
1353 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001354 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001355 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001356 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1357 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1358 int iCol = sqlite3_value_int(argv[5]);
1359 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001360 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001361 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001362 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001363 int rc;
dancf8f2892018-08-09 20:47:01 +00001364 Parse sParse;
1365 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001366 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001367 int i;
dan987db762018-08-14 20:18:50 +00001368 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001369#ifndef SQLITE_OMIT_AUTHORIZATION
1370 sqlite3_xauth xAuth = db->xAuth;
1371#endif
dancf8f2892018-08-09 20:47:01 +00001372
drh38d99642018-08-18 18:27:18 +00001373 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001374 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001375 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001376 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001377 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001378 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001379 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001380 if( pTab==0 || iCol>=pTab->nCol ){
1381 sqlite3BtreeLeaveAll(db);
1382 return;
1383 }
dan987db762018-08-14 20:18:50 +00001384 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001385 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001386 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001387
dan141e1192018-08-31 18:23:53 +00001388#ifndef SQLITE_OMIT_AUTHORIZATION
1389 db->xAuth = 0;
1390#endif
drhb2ab3dc2019-12-20 14:08:34 +00001391 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001392
dancf8f2892018-08-09 20:47:01 +00001393 /* Find tokens that need to be replaced. */
1394 memset(&sWalker, 0, sizeof(Walker));
1395 sWalker.pParse = &sParse;
1396 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001397 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001398 sWalker.u.pRename = &sCtx;
1399
dan0cbb0b12018-08-16 19:49:16 +00001400 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001401 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001402 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001403 Select *pSelect = sParse.pNewTable->pSelect;
1404 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001405 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001406 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001407 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001408 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1409 if( rc==SQLITE_OK ){
1410 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001411 }
dan987db762018-08-14 20:18:50 +00001412 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1413 }else{
1414 /* A regular table */
1415 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1416 FKey *pFKey;
1417 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001418 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001419 if( bFKOnly==0 ){
1420 renameTokenFind(
1421 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1422 );
1423 if( sCtx.iCol<0 ){
1424 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001425 }
dan987db762018-08-14 20:18:50 +00001426 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1427 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1428 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1429 }
drh885eeb62019-01-09 02:02:24 +00001430 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1431 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1432 }
dan987db762018-08-14 20:18:50 +00001433 }
drhb9bcf7c2019-10-19 13:29:10 +00001434#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1435 for(i=0; i<sParse.pNewTable->nCol; i++){
1436 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1437 }
1438#endif
dan987db762018-08-14 20:18:50 +00001439
1440 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1441 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001442 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001443 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1444 }
1445 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1446 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1447 ){
1448 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1449 }
dan6fe7f232018-08-10 19:19:33 +00001450 }
dancf8f2892018-08-09 20:47:01 +00001451 }
1452 }
dan5496d6a2018-08-13 17:14:26 +00001453 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001454 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1455 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001456 }else{
dan5be60c52018-08-15 20:28:39 +00001457 /* A trigger */
1458 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001459 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001460 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001461
danc9461ec2018-08-29 21:00:16 +00001462 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1463 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001464 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001465 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001466 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001467 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1468 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001469 }
danc9461ec2018-08-29 21:00:16 +00001470 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1471 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001472 }
1473 }
1474 }
1475
dan5be60c52018-08-15 20:28:39 +00001476
1477 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001478 if( sParse.pTriggerTab==pTab ){
1479 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001480 }
dan5be60c52018-08-15 20:28:39 +00001481
danc9461ec2018-08-29 21:00:16 +00001482 /* Find tokens to edit in various expressions and selects */
1483 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001484 }
1485
dan987db762018-08-14 20:18:50 +00001486 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001487 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001488
drh5fc22cd2018-08-13 13:43:11 +00001489renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001490 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001491 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001492 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001493 }else{
1494 sqlite3_result_error_code(context, rc);
1495 }
1496 }
1497
dan141e1192018-08-31 18:23:53 +00001498 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001499 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001500#ifndef SQLITE_OMIT_AUTHORIZATION
1501 db->xAuth = xAuth;
1502#endif
drhda76adc2018-08-25 02:04:05 +00001503 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001504}
1505
dandd1a9c82018-09-05 08:28:30 +00001506/*
1507** Walker expression callback used by "RENAME TABLE".
1508*/
danc9461ec2018-08-29 21:00:16 +00001509static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1510 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001511 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1512 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001513 }
1514 return WRC_Continue;
1515}
1516
1517/*
dandd1a9c82018-09-05 08:28:30 +00001518** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001519*/
1520static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1521 int i;
1522 RenameCtx *p = pWalker->u.pRename;
1523 SrcList *pSrc = pSelect->pSrc;
dan38096962019-12-09 08:13:43 +00001524 if( pSelect->selFlags & SF_View ) return WRC_Prune;
drh92a28242019-10-09 15:37:58 +00001525 if( pSrc==0 ){
1526 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001527 return WRC_Abort;
1528 }
danc9461ec2018-08-29 21:00:16 +00001529 for(i=0; i<pSrc->nSrc; i++){
1530 struct SrcList_item *pItem = &pSrc->a[i];
1531 if( pItem->pTab==p->pTab ){
1532 renameTokenFind(pWalker->pParse, p, pItem->zName);
1533 }
1534 }
danea412512018-12-05 13:49:04 +00001535 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001536
1537 return WRC_Continue;
1538}
1539
1540
1541/*
1542** This C function implements an SQL user function that is used by SQL code
1543** generated by the ALTER TABLE ... RENAME command to modify the definition
1544** of any foreign key constraints that use the table being renamed as the
1545** parent table. It is passed three arguments:
1546**
dan141e1192018-08-31 18:23:53 +00001547** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001548** 1. type: Type of object ("table", "view" etc.)
1549** 2. object: Name of object
1550** 3: The complete text of the schema statement being modified,
1551** 4: The old name of the table being renamed, and
1552** 5: The new name of the table being renamed.
1553** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001554**
dan141e1192018-08-31 18:23:53 +00001555** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001556**
dan141e1192018-08-31 18:23:53 +00001557** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001558** -> 'CREATE TABLE t1(a REFERENCES t3)'
1559*/
1560static void renameTableFunc(
1561 sqlite3_context *context,
1562 int NotUsed,
1563 sqlite3_value **argv
1564){
1565 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001566 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001567 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1568 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1569 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1570 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001571 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001572
dan141e1192018-08-31 18:23:53 +00001573 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001574 Parse sParse;
1575 int rc;
1576 int bQuote = 1;
1577 RenameCtx sCtx;
1578 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001579
dan141e1192018-08-31 18:23:53 +00001580#ifndef SQLITE_OMIT_AUTHORIZATION
1581 sqlite3_xauth xAuth = db->xAuth;
1582 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001583#endif
1584
dan141e1192018-08-31 18:23:53 +00001585 sqlite3BtreeEnterAll(db);
1586
1587 memset(&sCtx, 0, sizeof(RenameCtx));
1588 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1589 memset(&sWalker, 0, sizeof(Walker));
1590 sWalker.pParse = &sParse;
1591 sWalker.xExprCallback = renameTableExprCb;
1592 sWalker.xSelectCallback = renameTableSelectCb;
1593 sWalker.u.pRename = &sCtx;
1594
drhb2ab3dc2019-12-20 14:08:34 +00001595 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001596
1597 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001598 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001599 if( sParse.pNewTable ){
1600 Table *pTab = sParse.pNewTable;
1601
1602 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001603 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001604 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001605 NameContext sNC;
1606 memset(&sNC, 0, sizeof(sNC));
1607 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001608
dan38096962019-12-09 08:13:43 +00001609 assert( pSelect->selFlags & SF_View );
1610 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001611 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001612 if( sParse.nErr ){
1613 rc = sParse.rc;
1614 }else{
1615 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1616 }
dan674b8942018-09-20 08:28:01 +00001617 }
dan141e1192018-08-31 18:23:53 +00001618 }else{
1619 /* Modify any FK definitions to point to the new table. */
1620#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001621 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001622 FKey *pFKey;
1623 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1624 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1625 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1626 }
dan141e1192018-08-31 18:23:53 +00001627 }
1628 }
1629#endif
1630
1631 /* If this is the table being altered, fix any table refs in CHECK
1632 ** expressions. Also update the name that appears right after the
1633 ** "CREATE [VIRTUAL] TABLE" bit. */
1634 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1635 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001636 if( isLegacy==0 ){
1637 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1638 }
dan141e1192018-08-31 18:23:53 +00001639 renameTokenFind(&sParse, &sCtx, pTab->zName);
1640 }
danc9461ec2018-08-29 21:00:16 +00001641 }
1642 }
danc9461ec2018-08-29 21:00:16 +00001643
dan141e1192018-08-31 18:23:53 +00001644 else if( sParse.pNewIndex ){
1645 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001646 if( isLegacy==0 ){
1647 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1648 }
dan141e1192018-08-31 18:23:53 +00001649 }
danc9461ec2018-08-29 21:00:16 +00001650
1651#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001652 else{
dan141e1192018-08-31 18:23:53 +00001653 Trigger *pTrigger = sParse.pNewTrigger;
1654 TriggerStep *pStep;
1655 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1656 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1657 ){
1658 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1659 }
danc9461ec2018-08-29 21:00:16 +00001660
dan674b8942018-09-20 08:28:01 +00001661 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001662 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001663 if( rc==SQLITE_OK ){
1664 renameWalkTrigger(&sWalker, pTrigger);
1665 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1666 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1667 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1668 }
dan141e1192018-08-31 18:23:53 +00001669 }
dan0ccda962018-08-30 16:26:48 +00001670 }
danc9461ec2018-08-29 21:00:16 +00001671 }
1672 }
dan141e1192018-08-31 18:23:53 +00001673#endif
danc9461ec2018-08-29 21:00:16 +00001674 }
dan141e1192018-08-31 18:23:53 +00001675
1676 if( rc==SQLITE_OK ){
1677 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1678 }
1679 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001680 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001681 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001682 }else{
1683 sqlite3_result_error_code(context, rc);
1684 }
dan141e1192018-08-31 18:23:53 +00001685 }
1686
1687 renameParseCleanup(&sParse);
1688 renameTokenFree(db, sCtx.pList);
1689 sqlite3BtreeLeaveAll(db);
1690#ifndef SQLITE_OMIT_AUTHORIZATION
1691 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001692#endif
1693 }
1694
danc9461ec2018-08-29 21:00:16 +00001695 return;
1696}
1697
dandd1a9c82018-09-05 08:28:30 +00001698/*
1699** An SQL user function that checks that there are no parse or symbol
1700** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1701** After an ALTER TABLE .. RENAME operation is performed and the schema
1702** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001703** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001704**
1705** 0: Database name ("main", "temp" etc.).
1706** 1: SQL statement.
1707** 2: Object type ("view", "table", "trigger" or "index").
1708** 3: Object name.
1709** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001710** 5: "when" part of error message.
dan1d85c6b2018-09-06 16:01:37 +00001711**
1712** Unless it finds an error, this function normally returns NULL. However, it
1713** returns integer value 1 if:
1714**
1715** * the SQL argument creates a trigger, and
1716** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001717*/
dan9d324822018-08-30 20:03:44 +00001718static void renameTableTest(
1719 sqlite3_context *context,
1720 int NotUsed,
1721 sqlite3_value **argv
1722){
1723 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001724 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1725 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001726 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001727 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001728 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan9d324822018-08-30 20:03:44 +00001729
dan141e1192018-08-31 18:23:53 +00001730#ifndef SQLITE_OMIT_AUTHORIZATION
1731 sqlite3_xauth xAuth = db->xAuth;
1732 db->xAuth = 0;
1733#endif
1734
drh5b1da302018-09-01 20:02:07 +00001735 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001736 if( zDb && zInput ){
1737 int rc;
1738 Parse sParse;
drhb2ab3dc2019-12-20 14:08:34 +00001739 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan09236502018-09-01 16:05:50 +00001740 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001741 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001742 NameContext sNC;
1743 memset(&sNC, 0, sizeof(sNC));
1744 sNC.pParse = &sParse;
1745 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1746 if( sParse.nErr ) rc = sParse.rc;
1747 }
1748
1749 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001750 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001751 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001752 }
drh3b700452018-09-07 19:12:08 +00001753 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001754 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1755 int i2 = sqlite3FindDbName(db, zDb);
1756 if( i1==i2 ) sqlite3_result_int(context, 1);
1757 }
dan09236502018-09-01 16:05:50 +00001758 }
dan9d324822018-08-30 20:03:44 +00001759 }
1760
dan16953462021-02-18 19:25:44 +00001761 if( rc!=SQLITE_OK && zWhen ){
1762 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001763 }
dan09236502018-09-01 16:05:50 +00001764 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001765 }
1766
dan141e1192018-08-31 18:23:53 +00001767#ifndef SQLITE_OMIT_AUTHORIZATION
1768 db->xAuth = xAuth;
1769#endif
dan9d324822018-08-30 20:03:44 +00001770}
1771
dancf8f2892018-08-09 20:47:01 +00001772/*
dan6a5a13d2021-02-17 20:08:22 +00001773** The implementation of internal UDF sqlite_drop_column().
1774**
dan6e6d9832021-02-16 20:43:36 +00001775** Arguments:
1776**
1777** argv[0]: An integer - the index of the schema containing the table
1778** argv[1]: CREATE TABLE statement to modify.
1779** argv[2]: An integer - the index of the column to remove.
1780** argv[3]: Byte offset of first byte after last column definition in argv[1]
dan6a5a13d2021-02-17 20:08:22 +00001781**
1782** The value returned is a string containing the CREATE TABLE statement
1783** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00001784*/
1785static void dropColumnFunc(
1786 sqlite3_context *context,
1787 int NotUsed,
1788 sqlite3_value **argv
1789){
1790 sqlite3 *db = sqlite3_context_db_handle(context);
1791 int iSchema = sqlite3_value_int(argv[0]);
1792 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1793 int iCol = sqlite3_value_int(argv[2]);
1794 int iAddColOffset = sqlite3_value_int(argv[3]);
1795 const char *zDb = db->aDb[iSchema].zDbSName;
1796 int rc;
1797 Parse sParse;
1798 RenameToken *pCol;
1799 Table *pTab;
1800 const char *zEnd;
1801 char *zNew = 0;
1802
dan678f3b32021-02-18 20:27:46 +00001803#ifndef SQLITE_OMIT_AUTHORIZATION
1804 sqlite3_xauth xAuth = db->xAuth;
1805 db->xAuth = 0;
1806#endif
1807
dan6e6d9832021-02-16 20:43:36 +00001808 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
1809 if( rc!=SQLITE_OK ) goto drop_column_done;
1810 pTab = sParse.pNewTable;
1811
1812 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
1813 if( iCol<pTab->nCol-1 ){
1814 RenameToken *pEnd;
1815 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
1816 zEnd = (const char*)pEnd->t.z;
1817 }else{
1818 zEnd = (const char*)&zSql[iAddColOffset];
1819 while( pCol->t.z[0]!=',' && pCol->t.z[1]!='(' ) pCol->t.z--;
1820 }
1821
danc2a878e2021-02-17 20:46:44 +00001822 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00001823 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
1824 sqlite3_free(zNew);
1825
1826drop_column_done:
1827 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00001828#ifndef SQLITE_OMIT_AUTHORIZATION
1829 db->xAuth = xAuth;
1830#endif
dan6e6d9832021-02-16 20:43:36 +00001831}
1832
dan6a5a13d2021-02-17 20:08:22 +00001833/*
1834** This function is called by the parser upon parsing an
1835**
1836** ALTER TABLE pSrc DROP COLUMN pName
1837**
1838** statement. Argument pSrc contains the possibly qualified name of the
1839** table being edited, and token pName the name of the column to drop.
1840*/
dan6e6d9832021-02-16 20:43:36 +00001841void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00001842 sqlite3 *db = pParse->db; /* Database handle */
1843 Table *pTab; /* Table to modify */
1844 int iDb; /* Index of db containing pTab in aDb[] */
1845 const char *zDb; /* Database containing pTab ("main" etc.) */
1846 char *zCol = 0; /* Name of column to drop */
1847 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00001848
1849 /* Look up the table being altered. */
1850 assert( pParse->pNewTable==0 );
1851 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00001852 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00001853 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
1854 if( !pTab ) goto exit_drop_column;
1855
dan6a5a13d2021-02-17 20:08:22 +00001856 /* Make sure this is not an attempt to ALTER a view, virtual table or
1857 ** system table. */
1858 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
1859 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00001860
1861 /* Find the index of the column being dropped. */
1862 zCol = sqlite3NameFromToken(db, pName);
1863 if( zCol==0 ){
1864 assert( db->mallocFailed );
1865 goto exit_drop_column;
1866 }
1867 iCol = sqlite3ColumnIndex(pTab, zCol);
1868 if( iCol<0 ){
1869 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
1870 goto exit_drop_column;
1871 }
1872
1873 /* Do not allow the user to drop a PRIMARY KEY column or a column
1874 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00001875 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
1876 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
1877 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
1878 zCol
1879 );
dan6e6d9832021-02-16 20:43:36 +00001880 goto exit_drop_column;
1881 }
dan6e6d9832021-02-16 20:43:36 +00001882
dan6a5a13d2021-02-17 20:08:22 +00001883 /* Edit the sqlite_schema table */
1884 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1885 assert( iDb>=0 );
1886 zDb = db->aDb[iDb].zDbSName;
dan16953462021-02-18 19:25:44 +00001887 renameTestSchema(pParse, zDb, iDb==1, "");
dan6e6d9832021-02-16 20:43:36 +00001888 sqlite3NestedParse(pParse,
1889 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
1890 "sql = sqlite_drop_column(%d, sql, %d, %d) "
1891 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan6a5a13d2021-02-17 20:08:22 +00001892 , zDb, iDb, iCol, pTab->addColOffset, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00001893 );
1894
1895 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00001896 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan16953462021-02-18 19:25:44 +00001897 renameTestSchema(pParse, zDb, iDb==1, "after drop column");
dan6e6d9832021-02-16 20:43:36 +00001898
1899 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00001900 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00001901 int i;
1902 int addr;
1903 int reg;
1904 int regRec;
1905 Index *pPk = 0;
1906 int nField = 0; /* Number of non-virtual columns after drop */
1907 int iCur;
1908 Vdbe *v = sqlite3GetVdbe(pParse);
1909 iCur = pParse->nTab++;
1910 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00001911 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00001912 reg = ++pParse->nMem;
1913 pParse->nMem += pTab->nCol;
1914 if( HasRowid(pTab) ){
1915 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
1916 }else{
1917 pPk = sqlite3PrimaryKeyIndex(pTab);
dan6e6d9832021-02-16 20:43:36 +00001918 }
dan6a5a13d2021-02-17 20:08:22 +00001919 for(i=0; i<pTab->nCol; i++){
1920 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
1921 int regOut;
1922 if( pPk ){
1923 int iPos = sqlite3TableColumnToIndex(pPk, i);
1924 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
1925 regOut = reg+1+iPos-(iPos>iColPos);
1926 }else{
1927 regOut = reg+1+nField;
1928 }
1929 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
1930 nField++;
1931 }
1932 }
1933 regRec = reg + pTab->nCol;
1934 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
1935 if( pPk ){
1936 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
1937 }else{
1938 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
1939 }
dan6e6d9832021-02-16 20:43:36 +00001940
drh03361402021-02-18 23:53:47 +00001941 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00001942 sqlite3VdbeJumpHere(v, addr);
1943 }
dan6e6d9832021-02-16 20:43:36 +00001944
1945exit_drop_column:
1946 sqlite3DbFree(db, zCol);
1947 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00001948}
1949
1950/*
dancf8f2892018-08-09 20:47:01 +00001951** Register built-in functions used to help implement ALTER TABLE
1952*/
1953void sqlite3AlterFunctions(void){
1954 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00001955 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1956 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan16953462021-02-18 19:25:44 +00001957 INTERNAL_FUNCTION(sqlite_rename_test, 6, renameTableTest),
dan6e6d9832021-02-16 20:43:36 +00001958 INTERNAL_FUNCTION(sqlite_drop_column, 4, dropColumnFunc),
dancf8f2892018-08-09 20:47:01 +00001959 };
1960 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1961}
drhd0e4a6c2005-02-15 20:47:57 +00001962#endif /* SQLITE_ALTER_TABLE */