blob: f76a59dea65896815e25a0d4c49e9233b2df9959 [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){
drh3d8c92d2021-04-22 18:02:48 +000032 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
dan397a78d2018-12-18 20:31:14 +000033#ifndef SQLITE_OMIT_VIRTUALTABLE
drh3d8c92d2021-04-22 18:02:48 +000034 || (pTab->tabFlags & TF_Eponymous)!=0
drh070ae3b2019-11-16 13:51:31 +000035 || ( (pTab->tabFlags & TF_Shadow)!=0
36 && sqlite3ReadOnlyShadowTables(pParse->db)
dan397a78d2018-12-18 20:31:14 +000037 )
38#endif
39 ){
40 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danbe535002011-04-01 15:15:58 +000041 return 1;
42 }
43 return 0;
44}
45
dan09236502018-09-01 16:05:50 +000046/*
47** Generate code to verify that the schemas of database zDb and, if
48** bTemp is not true, database "temp", can still be parsed. This is
49** called at the end of the generation of an ALTER TABLE ... RENAME ...
50** statement to ensure that the operation has not rendered any schema
51** objects unusable.
52*/
dan16953462021-02-18 19:25:44 +000053static void renameTestSchema(
54 Parse *pParse, /* Parse context */
55 const char *zDb, /* Name of db to verify schema of */
56 int bTemp, /* True if this is the temp db */
dan2ad080a2021-03-16 16:14:48 +000057 const char *zWhen, /* "when" part of error message */
58 int bNoDQS /* Do not allow DQS in the schema */
dan16953462021-02-18 19:25:44 +000059){
drh351ae772021-02-15 13:17:19 +000060 pParse->colNamesSet = 1;
dan9d324822018-08-30 20:03:44 +000061 sqlite3NestedParse(pParse,
62 "SELECT 1 "
drha4a871c2021-11-04 14:04:20 +000063 "FROM \"%w\"." LEGACY_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000064 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000065 " AND sql NOT LIKE 'create virtual%%'"
dan2ad080a2021-03-16 16:14:48 +000066 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
drh346a70c2020-06-15 20:27:35 +000067 zDb,
dan2ad080a2021-03-16 16:14:48 +000068 zDb, bTemp, zWhen, bNoDQS
dan9d324822018-08-30 20:03:44 +000069 );
70
71 if( bTemp==0 ){
72 sqlite3NestedParse(pParse,
73 "SELECT 1 "
drha4a871c2021-11-04 14:04:20 +000074 "FROM temp." LEGACY_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000075 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000076 " AND sql NOT LIKE 'create virtual%%'"
dan2ad080a2021-03-16 16:14:48 +000077 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
78 zDb, zWhen, bNoDQS
79 );
80 }
81}
82
83/*
84** Generate VM code to replace any double-quoted strings (but not double-quoted
85** identifiers) within the "sql" column of the sqlite_schema table in
86** database zDb with their single-quoted equivalents. If argument bTemp is
87** not true, similarly update all SQL statements in the sqlite_schema table
88** of the temp db.
89*/
90static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
91 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +000092 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE
dan2ad080a2021-03-16 16:14:48 +000093 " SET sql = sqlite_rename_quotefix(%Q, sql)"
94 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
95 " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
96 );
97 if( bTemp==0 ){
98 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +000099 "UPDATE temp." LEGACY_SCHEMA_TABLE
dan2ad080a2021-03-16 16:14:48 +0000100 " SET sql = sqlite_rename_quotefix('temp', sql)"
101 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
102 " AND sql NOT LIKE 'create virtual%%'"
dan9d324822018-08-30 20:03:44 +0000103 );
104 }
105}
106
danbe535002011-04-01 15:15:58 +0000107/*
dan09236502018-09-01 16:05:50 +0000108** Generate code to reload the schema for database iDb. And, if iDb!=1, for
109** the temp database as well.
110*/
dan6a5a13d2021-02-17 20:08:22 +0000111static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
dan09236502018-09-01 16:05:50 +0000112 Vdbe *v = pParse->pVdbe;
113 if( v ){
114 sqlite3ChangeCookie(pParse, iDb);
dan6a5a13d2021-02-17 20:08:22 +0000115 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
116 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
dan09236502018-09-01 16:05:50 +0000117 }
118}
119
120/*
drhd0e4a6c2005-02-15 20:47:57 +0000121** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
122** command.
123*/
124void sqlite3AlterRenameTable(
125 Parse *pParse, /* Parser context. */
126 SrcList *pSrc, /* The table to rename. */
127 Token *pName /* The new table name. */
128){
129 int iDb; /* Database that contains the table */
130 char *zDb; /* Name of database iDb */
131 Table *pTab; /* Table being renamed */
132 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000133 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000134 int nTabName; /* Number of UTF-8 characters in zTabName */
135 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000136 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000137 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh545f5872010-04-24 14:02:59 +0000138
drh56d56f72009-04-16 16:30:17 +0000139 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000140 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000141 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000142
dan41fb5cd2012-10-04 19:33:00 +0000143 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000144 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000145 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000146 zDb = db->aDb[iDb].zDbSName;
drhd0e4a6c2005-02-15 20:47:57 +0000147
148 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000149 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000150 if( !zName ) goto exit_rename_table;
151
152 /* Check that a table or index named 'zName' does not already exist
153 ** in database iDb. If so, this is an error.
154 */
drh3d863b52020-05-14 21:16:52 +0000155 if( sqlite3FindTable(db, zName, zDb)
156 || sqlite3FindIndex(db, zName, zDb)
157 || sqlite3IsShadowTableOf(db, pTab, zName)
158 ){
drhd0e4a6c2005-02-15 20:47:57 +0000159 sqlite3ErrorMsg(pParse,
160 "there is already another table or index with this name: %s", zName);
161 goto exit_rename_table;
162 }
163
164 /* Make sure it is not a system table being altered, or a reserved name
165 ** that the table is being renamed to.
166 */
dan397a78d2018-12-18 20:31:14 +0000167 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000168 goto exit_rename_table;
169 }
drhc5a93d42019-08-12 00:08:07 +0000170 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
171 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000172 }
173
danielk197761116ae2007-12-13 08:15:30 +0000174#ifndef SQLITE_OMIT_VIEW
drhf38524d2021-08-02 16:41:57 +0000175 if( IsView(pTab) ){
danielk197761116ae2007-12-13 08:15:30 +0000176 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
177 goto exit_rename_table;
178 }
179#endif
180
drhd0e4a6c2005-02-15 20:47:57 +0000181#ifndef SQLITE_OMIT_AUTHORIZATION
182 /* Invoke the authorization callback. */
183 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
184 goto exit_rename_table;
185 }
186#endif
187
danielk1977182c4ba2007-06-27 15:53:34 +0000188#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000189 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
190 goto exit_rename_table;
191 }
danielk1977595a5232009-07-24 17:58:53 +0000192 if( IsVirtual(pTab) ){
193 pVTab = sqlite3GetVTable(db, pTab);
194 if( pVTab->pVtab->pModule->xRename==0 ){
195 pVTab = 0;
196 }
danielk1977182c4ba2007-06-27 15:53:34 +0000197 }
198#endif
199
dan1f3b2842019-03-15 16:17:32 +0000200 /* Begin a transaction for database iDb. Then modify the schema cookie
201 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
202 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
203 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000204 v = sqlite3GetVdbe(pParse);
205 if( v==0 ){
206 goto exit_rename_table;
207 }
dan1f3b2842019-03-15 16:17:32 +0000208 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000209
drh4e5dd852007-05-15 03:56:49 +0000210 /* figure out how many UTF-8 characters are in zName */
211 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000212 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000213
danc9461ec2018-08-29 21:00:16 +0000214 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
215 ** the schema to use the new table name. */
216 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000217 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
dan65372fa2018-09-03 20:05:15 +0000218 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000219 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000220 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
drh346a70c2020-06-15 20:27:35 +0000221 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000222 );
dan432cc5b2009-09-26 17:51:48 +0000223
drh1e32bed2020-06-19 13:33:53 +0000224 /* Update the tbl_name and name columns of the sqlite_schema table
danc9461ec2018-08-29 21:00:16 +0000225 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000226 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000227 "UPDATE %Q." LEGACY_SCHEMA_TABLE " SET "
drhd0e4a6c2005-02-15 20:47:57 +0000228 "tbl_name = %Q, "
229 "name = CASE "
230 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000231 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
232 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000233 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000234 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000235 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000236 "(type='table' OR type='index' OR type='trigger');",
drh346a70c2020-06-15 20:27:35 +0000237 zDb,
danc9461ec2018-08-29 21:00:16 +0000238 zName, zName, zName,
239 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000240 );
241
242#ifndef SQLITE_OMIT_AUTOINCREMENT
243 /* If the sqlite_sequence table exists in this database, then update
244 ** it with the new table name.
245 */
246 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
247 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000248 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000249 zDb, zName, pTab->zName);
250 }
251#endif
252
danc9461ec2018-08-29 21:00:16 +0000253 /* If the table being renamed is not itself part of the temp database,
254 ** edit view and trigger definitions within the temp database
255 ** as required. */
256 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000257 sqlite3NestedParse(pParse,
drh1e32bed2020-06-19 13:33:53 +0000258 "UPDATE sqlite_temp_schema SET "
dan65372fa2018-09-03 20:05:15 +0000259 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000260 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000261 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
dan2ad080a2021-03-16 16:14:48 +0000262 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
dan1d85c6b2018-09-06 16:01:37 +0000263 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000264 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000265 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000266 }
drhd0e4a6c2005-02-15 20:47:57 +0000267
dan34566c42018-09-20 17:21:21 +0000268 /* If this is a virtual table, invoke the xRename() function if
269 ** one is defined. The xRename() callback will modify the names
270 ** of any resources used by the v-table implementation (including other
271 ** SQLite tables) that are identified by the name of the virtual table.
272 */
273#ifndef SQLITE_OMIT_VIRTUALTABLE
274 if( pVTab ){
275 int i = ++pParse->nMem;
276 sqlite3VdbeLoadString(v, i, zName);
277 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000278 }
279#endif
280
dan6a5a13d2021-02-17 20:08:22 +0000281 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000282 renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
dan9d324822018-08-30 20:03:44 +0000283
drhd0e4a6c2005-02-15 20:47:57 +0000284exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000285 sqlite3SrcListDelete(db, pSrc);
286 sqlite3DbFree(db, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000287}
danielk197719a8e7e2005-03-17 05:03:38 +0000288
drhd3001712009-05-12 17:46:53 +0000289/*
drh9e5fdc42020-05-08 19:02:21 +0000290** Write code that will raise an error if the table described by
291** zDb and zTab is not empty.
292*/
293static void sqlite3ErrorIfNotEmpty(
294 Parse *pParse, /* Parsing context */
295 const char *zDb, /* Schema holding the table */
296 const char *zTab, /* Table to check for empty */
297 const char *zErr /* Error message text */
298){
299 sqlite3NestedParse(pParse,
300 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
301 zErr, zDb, zTab
302 );
303}
304
305/*
danielk197719a8e7e2005-03-17 05:03:38 +0000306** This function is called after an "ALTER TABLE ... ADD" statement
307** has been parsed. Argument pColDef contains the text of the new
308** column definition.
309**
310** The Table structure pParse->pNewTable was extended to include
311** the new column during parsing.
312*/
313void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
314 Table *pNew; /* Copy of pParse->pNewTable */
315 Table *pTab; /* Table being altered */
316 int iDb; /* Database number */
317 const char *zDb; /* Database name */
318 const char *zTab; /* Table name */
319 char *zCol; /* Null-terminated column definition */
320 Column *pCol; /* The new column */
321 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000322 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000323 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000324 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000325
danielk1977f150c9d2008-10-30 17:21:12 +0000326 db = pParse->db;
327 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000328 pNew = pParse->pNewTable;
329 assert( pNew );
330
drh1fee73e2007-08-29 04:00:57 +0000331 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000332 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000333 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000334 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000335 pCol = &pNew->aCol[pNew->nCol-1];
drh79cf2b72021-07-31 20:30:41 +0000336 pDflt = sqlite3ColumnExpr(pNew, pCol);
drh17435752007-08-16 04:30:38 +0000337 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000338 assert( pTab );
339
drh81f2ccd2006-01-31 14:28:44 +0000340#ifndef SQLITE_OMIT_AUTHORIZATION
341 /* Invoke the authorization callback. */
342 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
343 return;
344 }
345#endif
346
danielk197719a8e7e2005-03-17 05:03:38 +0000347
348 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
349 ** If there is a NOT NULL constraint, then the default value for the
350 ** column must not be NULL.
351 */
drha371ace2012-09-13 14:22:47 +0000352 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000353 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
354 return;
355 }
356 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000357 sqlite3ErrorMsg(pParse,
358 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000359 return;
360 }
drhc27ea2a2019-10-16 20:05:56 +0000361 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
362 /* If the default value for the new column was specified with a
363 ** literal NULL, then set pDflt to 0. This simplifies checking
364 ** for an SQL NULL default below.
365 */
366 assert( pDflt==0 || pDflt->op==TK_SPAN );
367 if( pDflt && pDflt->pLeft->op==TK_NULL ){
368 pDflt = 0;
369 }
drh78b2fa82021-10-07 12:11:20 +0000370 assert( IsOrdinaryTable(pNew) );
drhf38524d2021-08-02 16:41:57 +0000371 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000372 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000373 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000374 }
375 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000376 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000377 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000378 }
379
drh9e5fdc42020-05-08 19:02:21 +0000380
drhc27ea2a2019-10-16 20:05:56 +0000381 /* Ensure the default expression is something that sqlite3ValueFromExpr()
382 ** can handle (i.e. not CURRENT_TIME etc.)
383 */
384 if( pDflt ){
385 sqlite3_value *pVal = 0;
386 int rc;
387 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
388 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
389 if( rc!=SQLITE_OK ){
390 assert( db->mallocFailed == 1 );
391 return;
392 }
393 if( !pVal ){
drh9e5fdc42020-05-08 19:02:21 +0000394 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
395 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000396 }
397 sqlite3ValueFree(pVal);
398 }
drh035f6d92019-10-24 01:04:10 +0000399 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000400 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000401 }
402
danielk197719a8e7e2005-03-17 05:03:38 +0000403
404 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000405 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000406 if( zCol ){
407 char *zEnd = &zCol[pColDef->n-1];
drh56d56f72009-04-16 16:30:17 +0000408 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000409 *zEnd-- = '\0';
410 }
drh37114fb2021-01-01 20:04:34 +0000411 /* substr() operations on characters, but addColOffset is in bytes. So we
412 ** have to use printf() to translate between these units: */
drh78b2fa82021-10-07 12:11:20 +0000413 assert( IsOrdinaryTable(pTab) );
414 assert( IsOrdinaryTable(pNew) );
danielk197719a8e7e2005-03-17 05:03:38 +0000415 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000416 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000417 "sql = printf('%%.%ds, ',sql) || %Q"
418 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000419 "WHERE type = 'table' AND name = %Q",
drhf38524d2021-08-02 16:41:57 +0000420 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000421 zTab
422 );
drh633e6d52008-07-28 19:34:53 +0000423 sqlite3DbFree(db, zCol);
danielk197719a8e7e2005-03-17 05:03:38 +0000424 }
425
dan09236502018-09-01 16:05:50 +0000426 v = sqlite3GetVdbe(pParse);
427 if( v ){
drhb4d9b2b2021-07-20 07:35:07 +0000428 /* Make sure the schema version is at least 3. But do not upgrade
429 ** from less than 3 to 4, as that will corrupt any preexisting DESC
430 ** index.
431 */
dan09236502018-09-01 16:05:50 +0000432 r1 = sqlite3GetTempReg(pParse);
433 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
434 sqlite3VdbeUsesBtree(v, iDb);
435 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
436 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
437 VdbeCoverage(v);
438 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
439 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000440
drhb4d9b2b2021-07-20 07:35:07 +0000441 /* Reload the table definition */
drhac894af2021-11-03 15:59:17 +0000442 renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
drhb4d9b2b2021-07-20 07:35:07 +0000443
444 /* Verify that constraints are still satisfied */
drh0f91a532021-07-20 08:23:54 +0000445 if( pNew->pCheck!=0
drhb4d9b2b2021-07-20 07:35:07 +0000446 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
447 ){
448 sqlite3NestedParse(pParse,
449 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
450 " THEN raise(ABORT,'CHECK constraint failed')"
drh0f91a532021-07-20 08:23:54 +0000451 " ELSE raise(ABORT,'NOT NULL constraint failed')"
drhb4d9b2b2021-07-20 07:35:07 +0000452 " END"
drh0f91a532021-07-20 08:23:54 +0000453 " FROM pragma_quick_check(\"%w\",\"%w\")"
454 " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
drhb4d9b2b2021-07-20 07:35:07 +0000455 zTab, zDb
456 );
457 }
458 }
danielk197719a8e7e2005-03-17 05:03:38 +0000459}
460
drhfdd6e852005-12-16 01:06:16 +0000461/*
danielk197719a8e7e2005-03-17 05:03:38 +0000462** This function is called by the parser after the table-name in
463** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
464** pSrc is the full-name of the table being altered.
465**
466** This routine makes a (partial) copy of the Table structure
467** for the table being altered and sets Parse.pNewTable to point
468** to it. Routines called by the parser as the column definition
469** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
470** the copy. The copy of the Table structure is deleted by tokenize.c
471** after parsing is finished.
472**
473** Routine sqlite3AlterFinishAddColumn() will be called to complete
474** coding the "ALTER TABLE ... ADD" statement.
475*/
476void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
477 Table *pNew;
478 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000479 int iDb;
480 int i;
481 int nAlloc;
drh17435752007-08-16 04:30:38 +0000482 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000483
484 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000485 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000486 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000487 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000488 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000489 if( !pTab ) goto exit_begin_add_column;
490
danielk19775ee9d692006-06-21 12:36:25 +0000491#ifndef SQLITE_OMIT_VIRTUALTABLE
492 if( IsVirtual(pTab) ){
493 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
494 goto exit_begin_add_column;
495 }
496#endif
497
danielk197719a8e7e2005-03-17 05:03:38 +0000498 /* Make sure this is not an attempt to ALTER a view. */
drhf38524d2021-08-02 16:41:57 +0000499 if( IsView(pTab) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000500 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
501 goto exit_begin_add_column;
502 }
dan397a78d2018-12-18 20:31:14 +0000503 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000504 goto exit_begin_add_column;
505 }
danielk197719a8e7e2005-03-17 05:03:38 +0000506
dan03e025e2019-10-07 18:43:21 +0000507 sqlite3MayAbort(pParse);
drh78b2fa82021-10-07 12:11:20 +0000508 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +0000509 assert( pTab->u.tab.addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000510 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000511
512 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000513 ** sqlite3AddColumn() function and friends to modify. But modify
514 ** the name by adding an "sqlite_altertab_" prefix. By adding this
515 ** prefix, we insure that the name will not collide with an existing
516 ** table because user table are not allowed to have the "sqlite_"
517 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000518 */
drh17435752007-08-16 04:30:38 +0000519 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000520 if( !pNew ) goto exit_begin_add_column;
521 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000522 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000523 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000524 assert( pNew->nCol>0 );
525 nAlloc = (((pNew->nCol-1)/8)*8)+8;
526 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000527 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000528 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000529 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000530 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000531 goto exit_begin_add_column;
532 }
533 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
534 for(i=0; i<pNew->nCol; i++){
535 Column *pCol = &pNew->aCol[i];
drhcf9d36d2021-08-02 18:03:43 +0000536 pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
537 pCol->hName = sqlite3StrIHash(pCol->zCnName);
danielk197719a8e7e2005-03-17 05:03:38 +0000538 }
drh78b2fa82021-10-07 12:11:20 +0000539 assert( IsOrdinaryTable(pNew) );
drhf38524d2021-08-02 16:41:57 +0000540 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
drh17435752007-08-16 04:30:38 +0000541 pNew->pSchema = db->aDb[iDb].pSchema;
drhf38524d2021-08-02 16:41:57 +0000542 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
drh79df7782016-12-14 14:07:35 +0000543 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000544
danielk197719a8e7e2005-03-17 05:03:38 +0000545exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000546 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000547 return;
548}
dancf8f2892018-08-09 20:47:01 +0000549
drh4a2c7472018-08-13 15:09:48 +0000550/*
dan9d705572018-08-20 16:16:05 +0000551** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
552** command. This function checks if the table is a view or virtual
553** table (columns of views or virtual tables may not be renamed). If so,
554** it loads an error message into pParse and returns non-zero.
555**
556** Or, if pTab is not a view or virtual table, zero is returned.
557*/
558#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000559static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000560 const char *zType = 0;
561#ifndef SQLITE_OMIT_VIEW
drhf38524d2021-08-02 16:41:57 +0000562 if( IsView(pTab) ){
dan9d705572018-08-20 16:16:05 +0000563 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000564 }
dan9d705572018-08-20 16:16:05 +0000565#endif
566#ifndef SQLITE_OMIT_VIRTUALTABLE
567 if( IsVirtual(pTab) ){
568 zType = "virtual table";
569 }
570#endif
571 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000572 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
573 (bDrop ? "drop column from" : "rename columns of"),
574 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000575 );
576 return 1;
577 }
578 return 0;
579}
580#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000581# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000582#endif
583
584/*
drh4a2c7472018-08-13 15:09:48 +0000585** Handles the following parser reduction:
586**
587** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
588*/
dancf8f2892018-08-09 20:47:01 +0000589void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000590 Parse *pParse, /* Parsing context */
591 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
592 Token *pOld, /* Name of column being changed */
593 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000594){
drh4a2c7472018-08-13 15:09:48 +0000595 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000596 Table *pTab; /* Table being updated */
597 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000598 char *zOld = 0; /* Old column name */
599 char *zNew = 0; /* New column name */
600 const char *zDb; /* Name of schema containing the table */
601 int iSchema; /* Index of the schema */
602 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000603
drh4a2c7472018-08-13 15:09:48 +0000604 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000605 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
606 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000607
608 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000609 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000610 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000611
612 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000613 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
614 assert( iSchema>=0 );
615 zDb = db->aDb[iSchema].zDbSName;
616
drh0d019b92018-08-25 16:14:46 +0000617#ifndef SQLITE_OMIT_AUTHORIZATION
618 /* Invoke the authorization callback. */
619 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
620 goto exit_rename_column;
621 }
622#endif
623
drh4a2c7472018-08-13 15:09:48 +0000624 /* Make sure the old name really is a column name in the table to be
625 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000626 zOld = sqlite3NameFromToken(db, pOld);
627 if( !zOld ) goto exit_rename_column;
628 for(iCol=0; iCol<pTab->nCol; iCol++){
drhcf9d36d2021-08-02 18:03:43 +0000629 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;
dancf8f2892018-08-09 20:47:01 +0000630 }
631 if( iCol==pTab->nCol ){
632 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
633 goto exit_rename_column;
634 }
635
dan2ad080a2021-03-16 16:14:48 +0000636 /* Ensure the schema contains no double-quoted strings */
637 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
638 renameFixQuotes(pParse, zDb, iSchema==1);
639
drh4a2c7472018-08-13 15:09:48 +0000640 /* Do the rename operation using a recursive UPDATE statement that
641 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000642 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000643 */
dan1f3b2842019-03-15 16:17:32 +0000644 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000645 zNew = sqlite3NameFromToken(db, pNew);
646 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000647 assert( pNew->n>0 );
648 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000649 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000650 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000651 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000652 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
drhe73e9572021-09-16 13:20:29 +0000653 " AND (type != 'index' OR tbl_name = %Q)",
drh346a70c2020-06-15 20:27:35 +0000654 zDb,
danb87a9a82018-09-01 20:23:28 +0000655 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000656 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000657 );
658
dan9d324822018-08-30 20:03:44 +0000659 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000660 "UPDATE temp." LEGACY_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000661 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000662 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000663 zDb, pTab->zName, iCol, zNew, bQuote
664 );
665
dane325ffe2018-08-11 13:40:20 +0000666 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000667 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000668 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000669
dancf8f2892018-08-09 20:47:01 +0000670 exit_rename_column:
671 sqlite3SrcListDelete(db, pSrc);
672 sqlite3DbFree(db, zOld);
673 sqlite3DbFree(db, zNew);
674 return;
675}
676
drh4a2c7472018-08-13 15:09:48 +0000677/*
678** Each RenameToken object maps an element of the parse tree into
679** the token that generated that element. The parse tree element
680** might be one of:
681**
682** * A pointer to an Expr that represents an ID
683** * The name of a table column in Column.zName
684**
685** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000686** Each new object is created by sqlite3RenameTokenMap().
687** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000688** routine is used to keep the mapping current.
689**
690** After the parse finishes, renameTokenFind() routine can be used
691** to look up the actual token value that created some element in
692** the parse tree.
693*/
dancf8f2892018-08-09 20:47:01 +0000694struct RenameToken {
drhb6dad522021-09-24 16:14:47 +0000695 const void *p; /* Parse tree element created by token t */
drh4a2c7472018-08-13 15:09:48 +0000696 Token t; /* The token that created parse tree element p */
697 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000698};
699
drh4a2c7472018-08-13 15:09:48 +0000700/*
701** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
702** down into the Walker.
703*/
dan5496d6a2018-08-13 17:14:26 +0000704typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000705struct RenameCtx {
706 RenameToken *pList; /* List of tokens to overwrite */
707 int nList; /* Number of tokens in pList */
708 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000709 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000710 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000711};
712
dan8900a482018-09-05 14:36:05 +0000713#ifdef SQLITE_DEBUG
714/*
715** This function is only for debugging. It performs two tasks:
716**
717** 1. Checks that pointer pPtr does not already appear in the
718** rename-token list.
719**
720** 2. Dereferences each pointer in the rename-token list.
721**
722** The second is most effective when debugging under valgrind or
723** address-sanitizer or similar. If any of these pointers no longer
724** point to valid objects, an exception is raised by the memory-checking
725** tool.
726**
727** The point of this is to prevent comparisons of invalid pointer values.
728** Even though this always seems to work, it is undefined according to the
729** C standard. Example of undefined comparison:
730**
731** sqlite3_free(x);
732** if( x==y ) ...
733**
734** Technically, as x no longer points into a valid object or to the byte
735** following a valid object, it may not be used in comparison operations.
736*/
drhb6dad522021-09-24 16:14:47 +0000737static void renameTokenCheckAll(Parse *pParse, const void *pPtr){
dan8900a482018-09-05 14:36:05 +0000738 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
drhb6dad522021-09-24 16:14:47 +0000739 const RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000740 u8 i = 0;
741 for(p=pParse->pRename; p; p=p->pNext){
742 if( p->p ){
743 assert( p->p!=pPtr );
744 i += *(u8*)(p->p);
745 }
danc9461ec2018-08-29 21:00:16 +0000746 }
747 }
748}
dan8900a482018-09-05 14:36:05 +0000749#else
750# define renameTokenCheckAll(x,y)
751#endif
danc9461ec2018-08-29 21:00:16 +0000752
drh4a2c7472018-08-13 15:09:48 +0000753/*
drh49b269e2018-11-26 15:00:25 +0000754** Remember that the parser tree element pPtr was created using
755** the token pToken.
dan07e95232018-08-21 16:32:53 +0000756**
drh49b269e2018-11-26 15:00:25 +0000757** In other words, construct a new RenameToken object and add it
758** to the list of RenameToken objects currently being built up
759** in pParse->pRename.
760**
761** The pPtr argument is returned so that this routine can be used
762** with tail recursion in tokenExpr() routine, for a small performance
763** improvement.
drh4a2c7472018-08-13 15:09:48 +0000764*/
drhb6dad522021-09-24 16:14:47 +0000765const void *sqlite3RenameTokenMap(
766 Parse *pParse,
767 const void *pPtr,
768 const Token *pToken
769){
dancf8f2892018-08-09 20:47:01 +0000770 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000771 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000772 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000773 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000774 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
775 if( pNew ){
776 pNew->p = pPtr;
777 pNew->t = *pToken;
778 pNew->pNext = pParse->pRename;
779 pParse->pRename = pNew;
780 }
dancf8f2892018-08-09 20:47:01 +0000781 }
danc9461ec2018-08-29 21:00:16 +0000782
dand145e5f2018-08-21 08:29:48 +0000783 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000784}
785
drh4a2c7472018-08-13 15:09:48 +0000786/*
dan07e95232018-08-21 16:32:53 +0000787** It is assumed that there is already a RenameToken object associated
788** with parse tree element pFrom. This function remaps the associated token
789** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000790*/
drhb6dad522021-09-24 16:14:47 +0000791void sqlite3RenameTokenRemap(Parse *pParse, const void *pTo, const void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000792 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000793 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000794 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000795 if( p->p==pFrom ){
796 p->p = pTo;
797 break;
798 }
799 }
dancf8f2892018-08-09 20:47:01 +0000800}
801
drh4a2c7472018-08-13 15:09:48 +0000802/*
dan8900a482018-09-05 14:36:05 +0000803** Walker callback used by sqlite3RenameExprUnmap().
804*/
805static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
806 Parse *pParse = pWalker->pParse;
drhb6dad522021-09-24 16:14:47 +0000807 sqlite3RenameTokenRemap(pParse, 0, (const void*)pExpr);
drh477572b2021-10-07 20:46:29 +0000808 if( ExprUseYTab(pExpr) ){
809 sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
810 }
dan8900a482018-09-05 14:36:05 +0000811 return WRC_Continue;
812}
813
814/*
dan8f407622019-12-04 14:26:38 +0000815** Iterate through the Select objects that are part of WITH clauses attached
816** to select statement pSelect.
817*/
818static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000819 With *pWith = pSelect->pWith;
820 if( pWith ){
dan26d61e52021-06-11 11:14:24 +0000821 Parse *pParse = pWalker->pParse;
dan8f407622019-12-04 14:26:38 +0000822 int i;
drh35e6cd02021-06-11 13:18:56 +0000823 With *pCopy = 0;
dan26d61e52021-06-11 11:14:24 +0000824 assert( pWith->nCte>0 );
drh35e6cd02021-06-11 13:18:56 +0000825 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
826 /* Push a copy of the With object onto the with-stack. We use a copy
827 ** here as the original will be expanded and resolved (flags SF_Expanded
828 ** and SF_Resolved) below. And the parser code that uses the with-stack
829 ** fails if the Select objects on it have already been expanded and
830 ** resolved. */
831 pCopy = sqlite3WithDup(pParse->db, pWith);
drh24ce9442021-06-12 17:45:32 +0000832 pCopy = sqlite3WithPush(pParse, pCopy, 1);
drh35e6cd02021-06-11 13:18:56 +0000833 }
834 for(i=0; i<pWith->nCte; i++){
835 Select *p = pWith->a[i].pSelect;
836 NameContext sNC;
837 memset(&sNC, 0, sizeof(sNC));
838 sNC.pParse = pParse;
839 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
dan5a69d192021-09-27 15:44:03 +0000840 if( sNC.pParse->db->mallocFailed ) return;
drh35e6cd02021-06-11 13:18:56 +0000841 sqlite3WalkSelect(pWalker, p);
842 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
843 }
844 if( pCopy && pParse->pWith==pCopy ){
dand03d3a92021-06-11 12:14:58 +0000845 pParse->pWith = pCopy->pOuter;
dan26d61e52021-06-11 11:14:24 +0000846 }
dan8f407622019-12-04 14:26:38 +0000847 }
848}
849
850/*
danfb99e382020-04-03 11:20:40 +0000851** Unmap all tokens in the IdList object passed as the second argument.
852*/
853static void unmapColumnIdlistNames(
854 Parse *pParse,
drhb6dad522021-09-24 16:14:47 +0000855 const IdList *pIdList
danfb99e382020-04-03 11:20:40 +0000856){
857 if( pIdList ){
858 int ii;
859 for(ii=0; ii<pIdList->nId; ii++){
drhb6dad522021-09-24 16:14:47 +0000860 sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
danfb99e382020-04-03 11:20:40 +0000861 }
862 }
863}
864
865/*
dan0b277a92019-06-11 12:03:10 +0000866** Walker callback used by sqlite3RenameExprUnmap().
867*/
868static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000869 Parse *pParse = pWalker->pParse;
870 int i;
drhd63b69b2019-12-04 15:08:58 +0000871 if( pParse->nErr ) return WRC_Abort;
drh0fbc19e2021-10-17 10:31:09 +0000872 testcase( p->selFlags & SF_View );
873 testcase( p->selFlags & SF_CopyCte );
drhfebf0352021-10-13 14:01:44 +0000874 if( p->selFlags & (SF_View|SF_CopyCte) ){
danac67f562021-06-14 20:08:48 +0000875 return WRC_Prune;
876 }
drhbdf4cf02019-06-15 15:21:49 +0000877 if( ALWAYS(p->pEList) ){
878 ExprList *pList = p->pEList;
879 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000880 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000881 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000882 }
883 }
884 }
drh2c3f4652019-06-11 16:43:58 +0000885 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000886 SrcList *pSrc = p->pSrc;
887 for(i=0; i<pSrc->nSrc; i++){
888 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
drh00197742021-09-29 20:17:19 +0000889 sqlite3WalkExpr(pWalker, pSrc->a[i].pOn);
danfb99e382020-04-03 11:20:40 +0000890 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000891 }
892 }
dan8f407622019-12-04 14:26:38 +0000893
894 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000895 return WRC_Continue;
896}
897
898/*
dan8900a482018-09-05 14:36:05 +0000899** Remove all nodes that are part of expression pExpr from the rename list.
900*/
901void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000902 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000903 Walker sWalker;
904 memset(&sWalker, 0, sizeof(Walker));
905 sWalker.pParse = pParse;
906 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000907 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000908 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000909 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000910 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000911}
912
913/*
dane8ab40d2018-09-12 08:51:48 +0000914** Remove all nodes that are part of expression-list pEList from the
915** rename list.
916*/
917void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
918 if( pEList ){
919 int i;
920 Walker sWalker;
921 memset(&sWalker, 0, sizeof(Walker));
922 sWalker.pParse = pParse;
923 sWalker.xExprCallback = renameUnmapExprCb;
924 sqlite3WalkExprList(&sWalker, pEList);
925 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000926 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000927 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
928 }
dane8ab40d2018-09-12 08:51:48 +0000929 }
930 }
931}
932
933/*
drh4a2c7472018-08-13 15:09:48 +0000934** Free the list of RenameToken objects given in the second argument
935*/
dancf8f2892018-08-09 20:47:01 +0000936static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
937 RenameToken *pNext;
938 RenameToken *p;
939 for(p=pToken; p; p=pNext){
940 pNext = p->pNext;
941 sqlite3DbFree(db, p);
942 }
943}
944
dan987db762018-08-14 20:18:50 +0000945/*
946** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000947** object associated with parse tree element pPtr. If found, return a pointer
948** to it. Otherwise, return NULL.
949**
950** If the second argument passed to this function is not NULL and a matching
951** RenameToken object is found, remove it from the Parse object and add it to
952** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000953*/
dan6e6d9832021-02-16 20:43:36 +0000954static RenameToken *renameTokenFind(
955 Parse *pParse,
956 struct RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +0000957 const void *pPtr
dan6e6d9832021-02-16 20:43:36 +0000958){
dancf8f2892018-08-09 20:47:01 +0000959 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000960 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000961 return 0;
962 }
dancf8f2892018-08-09 20:47:01 +0000963 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
964 if( (*pp)->p==pPtr ){
965 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000966 if( pCtx ){
967 *pp = pToken->pNext;
968 pToken->pNext = pCtx->pList;
969 pCtx->pList = pToken;
970 pCtx->nList++;
971 }
972 return pToken;
dancf8f2892018-08-09 20:47:01 +0000973 }
974 }
dan6e6d9832021-02-16 20:43:36 +0000975 return 0;
dancf8f2892018-08-09 20:47:01 +0000976}
977
dan24fedb92018-08-18 17:35:38 +0000978/*
979** This is a Walker select callback. It does nothing. It is only required
980** because without a dummy callback, sqlite3WalkExpr() and similar do not
981** descend into sub-select statements.
982*/
dan987db762018-08-14 20:18:50 +0000983static int renameColumnSelectCb(Walker *pWalker, Select *p){
danac67f562021-06-14 20:08:48 +0000984 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000985 testcase( p->selFlags & SF_View );
986 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000987 return WRC_Prune;
988 }
danea412512018-12-05 13:49:04 +0000989 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000990 return WRC_Continue;
991}
992
dan987db762018-08-14 20:18:50 +0000993/*
994** This is a Walker expression callback.
995**
996** For every TK_COLUMN node in the expression tree, search to see
997** if the column being references is the column being renamed by an
998** ALTER TABLE statement. If it is, then attach its associated
999** RenameToken object to the list of RenameToken objects being
1000** constructed in RenameCtx object at pWalker->u.pRename.
1001*/
dancf8f2892018-08-09 20:47:01 +00001002static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +00001003 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +00001004 if( pExpr->op==TK_TRIGGER
1005 && pExpr->iColumn==p->iCol
1006 && pWalker->pParse->pTriggerTab==p->pTab
1007 ){
dan5be60c52018-08-15 20:28:39 +00001008 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +00001009 }else if( pExpr->op==TK_COLUMN
drh477572b2021-10-07 20:46:29 +00001010 && pExpr->iColumn==p->iCol
1011 && ALWAYS(ExprUseYTab(pExpr))
drheda079c2018-09-20 19:02:15 +00001012 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +00001013 ){
dan5496d6a2018-08-13 17:14:26 +00001014 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +00001015 }
1016 return WRC_Continue;
1017}
1018
dan987db762018-08-14 20:18:50 +00001019/*
1020** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001021** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001022** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001023** RenameContext. "Last" means the last RenameToken encountered when
1024** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001025** return all column name tokens in the order that they are encountered
1026** in the SQL statement.
1027*/
dan5496d6a2018-08-13 17:14:26 +00001028static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001029 RenameToken *pBest = pCtx->pList;
1030 RenameToken *pToken;
1031 RenameToken **pp;
1032
1033 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1034 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1035 }
1036 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1037 *pp = pBest->pNext;
1038
1039 return pBest;
1040}
1041
dan6fe7f232018-08-10 19:19:33 +00001042/*
dan24fedb92018-08-18 17:35:38 +00001043** An error occured while parsing or otherwise processing a database
1044** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1045** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1046** sub-routine is currently stored in pParse->zErrMsg. This function
1047** adds context to the error message and then stores it in pCtx.
1048*/
danb0137382018-08-20 20:01:01 +00001049static void renameColumnParseError(
1050 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001051 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001052 sqlite3_value *pType,
1053 sqlite3_value *pObject,
1054 Parse *pParse
1055){
drh79a5ee92018-08-23 19:32:04 +00001056 const char *zT = (const char*)sqlite3_value_text(pType);
1057 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001058 char *zErr;
danb0137382018-08-20 20:01:01 +00001059
dan16953462021-02-18 19:25:44 +00001060 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1061 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001062 pParse->zErrMsg
1063 );
dan24fedb92018-08-18 17:35:38 +00001064 sqlite3_result_error(pCtx, zErr, -1);
1065 sqlite3_free(zErr);
1066}
1067
1068/*
dan06249392018-08-21 15:06:59 +00001069** For each name in the the expression-list pEList (i.e. each
1070** pEList->a[i].zName) that matches the string in zOld, extract the
1071** corresponding rename-token from Parse object pParse and add it
1072** to the RenameCtx pCtx.
1073*/
1074static void renameColumnElistNames(
1075 Parse *pParse,
1076 RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +00001077 const ExprList *pEList,
dan06249392018-08-21 15:06:59 +00001078 const char *zOld
1079){
1080 if( pEList ){
1081 int i;
1082 for(i=0; i<pEList->nExpr; i++){
drhb6dad522021-09-24 16:14:47 +00001083 const char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001084 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1085 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001086 && 0==sqlite3_stricmp(zName, zOld)
1087 ){
drhb6dad522021-09-24 16:14:47 +00001088 renameTokenFind(pParse, pCtx, (const void*)zName);
dan06249392018-08-21 15:06:59 +00001089 }
1090 }
1091 }
1092}
1093
1094/*
1095** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1096** that matches the string in zOld, extract the corresponding rename-token
1097** from Parse object pParse and add it to the RenameCtx pCtx.
1098*/
1099static void renameColumnIdlistNames(
1100 Parse *pParse,
1101 RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +00001102 const IdList *pIdList,
dan06249392018-08-21 15:06:59 +00001103 const char *zOld
1104){
1105 if( pIdList ){
1106 int i;
1107 for(i=0; i<pIdList->nId; i++){
drhb6dad522021-09-24 16:14:47 +00001108 const char *zName = pIdList->a[i].zName;
dan06249392018-08-21 15:06:59 +00001109 if( 0==sqlite3_stricmp(zName, zOld) ){
drhb6dad522021-09-24 16:14:47 +00001110 renameTokenFind(pParse, pCtx, (const void*)zName);
dan06249392018-08-21 15:06:59 +00001111 }
1112 }
1113 }
1114}
1115
danfb99e382020-04-03 11:20:40 +00001116
dandd1a9c82018-09-05 08:28:30 +00001117/*
1118** Parse the SQL statement zSql using Parse object (*p). The Parse object
1119** is initialized by this function before it is used.
1120*/
danc9461ec2018-08-29 21:00:16 +00001121static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001122 Parse *p, /* Memory to use for Parse object */
1123 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001124 sqlite3 *db, /* Database handle */
1125 const char *zSql, /* SQL to parse */
1126 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001127){
1128 int rc;
danc9461ec2018-08-29 21:00:16 +00001129
1130 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1131
1132 /* Parse the SQL statement passed as the first argument. If no error
1133 ** occurs and the parse does not result in a new table, index or
1134 ** trigger object, the database must be corrupt. */
1135 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001136 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001137 p->db = db;
1138 p->nQueryLoop = 1;
drh54bc6382021-12-31 19:20:42 +00001139 rc = zSql ? sqlite3RunParser(p, zSql) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001140 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1141 if( rc==SQLITE_OK
1142 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1143 ){
1144 rc = SQLITE_CORRUPT_BKPT;
1145 }
1146
1147#ifdef SQLITE_DEBUG
1148 /* Ensure that all mappings in the Parse.pRename list really do map to
1149 ** a part of the input string. */
1150 if( rc==SQLITE_OK ){
1151 int nSql = sqlite3Strlen30(zSql);
1152 RenameToken *pToken;
1153 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1154 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1155 }
1156 }
1157#endif
1158
1159 db->init.iDb = 0;
1160 return rc;
1161}
1162
dandd1a9c82018-09-05 08:28:30 +00001163/*
1164** This function edits SQL statement zSql, replacing each token identified
1165** by the linked list pRename with the text of zNew. If argument bQuote is
1166** true, then zNew is always quoted first. If no error occurs, the result
1167** is loaded into context object pCtx as the result.
1168**
1169** Or, if an error occurs (i.e. an OOM condition), an error is left in
1170** pCtx and an SQLite error code returned.
1171*/
danc9461ec2018-08-29 21:00:16 +00001172static int renameEditSql(
1173 sqlite3_context *pCtx, /* Return result here */
1174 RenameCtx *pRename, /* Rename context */
1175 const char *zSql, /* SQL statement to edit */
1176 const char *zNew, /* New token text */
1177 int bQuote /* True to always quote token */
1178){
drh236bcdf2021-06-16 11:32:54 +00001179 i64 nNew = sqlite3Strlen30(zNew);
1180 i64 nSql = sqlite3Strlen30(zSql);
danc9461ec2018-08-29 21:00:16 +00001181 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1182 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001183 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001184 char *zOut;
drh236bcdf2021-06-16 11:32:54 +00001185 i64 nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001186 char *zBuf1 = 0;
1187 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001188
dan1e240722021-03-15 20:22:34 +00001189 if( zNew ){
1190 /* Set zQuot to point to a buffer containing a quoted copy of the
1191 ** identifier zNew. If the corresponding identifier in the original
1192 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1193 ** point to zQuot so that all substitutions are made using the
1194 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001195 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001196 if( zQuot==0 ){
1197 return SQLITE_NOMEM;
1198 }else{
dan1d14ffe2021-03-23 22:15:34 +00001199 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001200 }
1201
1202 assert( nQuot>=nNew );
1203 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001204 }else{
dan1e240722021-03-15 20:22:34 +00001205 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1206 if( zOut ){
1207 zBuf1 = &zOut[nSql*2+1];
1208 zBuf2 = &zOut[nSql*4+2];
1209 }
danc9461ec2018-08-29 21:00:16 +00001210 }
1211
1212 /* At this point pRename->pList contains a list of RenameToken objects
1213 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001214 ** with the new column name, or with single-quoted versions of themselves.
1215 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001216 if( zOut ){
1217 int nOut = nSql;
1218 memcpy(zOut, zSql, nSql);
1219 while( pRename->pList ){
1220 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001221 u32 nReplace;
1222 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001223 RenameToken *pBest = renameColumnTokenNext(pRename);
1224
1225 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001226 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001227 nReplace = nNew;
1228 zReplace = zNew;
1229 }else{
1230 nReplace = nQuot;
1231 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001232 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001233 }
danc9461ec2018-08-29 21:00:16 +00001234 }else{
dan1e240722021-03-15 20:22:34 +00001235 /* Dequote the double-quoted token. Then requote it again, this time
1236 ** using single quotes. If the character immediately following the
1237 ** original token within the input SQL was a single quote ('), then
1238 ** add another space after the new, single-quoted version of the
1239 ** token. This is so that (SELECT "string"'alias') maps to
1240 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1241 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1242 zBuf1[pBest->t.n] = 0;
1243 sqlite3Dequote(zBuf1);
1244 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1245 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1246 );
1247 zReplace = zBuf2;
1248 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001249 }
1250
1251 iOff = pBest->t.z - zSql;
1252 if( pBest->t.n!=nReplace ){
1253 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1254 nOut - (iOff + pBest->t.n)
1255 );
1256 nOut += nReplace - pBest->t.n;
1257 zOut[nOut] = '\0';
1258 }
1259 memcpy(&zOut[iOff], zReplace, nReplace);
1260 sqlite3DbFree(db, pBest);
1261 }
1262
1263 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1264 sqlite3DbFree(db, zOut);
1265 }else{
1266 rc = SQLITE_NOMEM;
1267 }
1268
1269 sqlite3_free(zQuot);
1270 return rc;
1271}
1272
dandd1a9c82018-09-05 08:28:30 +00001273/*
1274** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1275** it was read from the schema of database zDb. Return SQLITE_OK if
1276** successful. Otherwise, return an SQLite error code and leave an error
1277** message in the Parse object.
1278*/
drha7c74002020-07-18 18:44:59 +00001279static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001280 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001281 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001282 TriggerStep *pStep;
1283 NameContext sNC;
1284 int rc = SQLITE_OK;
1285
1286 memset(&sNC, 0, sizeof(sNC));
1287 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001288 assert( pNew->pTabSchema );
1289 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1290 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1291 );
1292 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001293 /* ALWAYS() because if the table of the trigger does not exist, the
1294 ** error would have been hit before this point */
1295 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001296 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1297 }
danc9461ec2018-08-29 21:00:16 +00001298
1299 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001300 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001301 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001302 }
1303
dand5e6fef2018-09-07 15:50:31 +00001304 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001305 if( pStep->pSelect ){
1306 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1307 if( pParse->nErr ) rc = pParse->rc;
1308 }
dand5e6fef2018-09-07 15:50:31 +00001309 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001310 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1311 if( pSrc ){
1312 int i;
drha3e64952020-08-12 16:19:12 +00001313 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001314 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001315 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001316 if( p->pSelect ){
1317 sqlite3SelectPrep(pParse, p->pSelect, 0);
1318 sqlite3ExpandSubquery(pParse, p);
1319 assert( i>0 );
1320 assert( pStep->pFrom->a[i-1].pSelect );
1321 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001322 }else{
dan7a39fae2020-10-31 16:33:01 +00001323 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1324 if( p->pTab==0 ){
1325 rc = SQLITE_ERROR;
1326 }else{
1327 p->pTab->nTabRef++;
1328 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1329 }
dane7877b22020-07-14 19:51:01 +00001330 }
1331 }
drh61a8ad72021-11-02 17:55:01 +00001332 if( rc==SQLITE_OK && db->mallocFailed ){
1333 rc = SQLITE_NOMEM;
1334 }
dane7877b22020-07-14 19:51:01 +00001335 sNC.pSrcList = pSrc;
1336 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001337 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1338 }
1339 if( rc==SQLITE_OK ){
1340 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1341 }
1342 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001343 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001344 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001345 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001346 sNC.uNC.pUpsert = pUpsert;
1347 sNC.ncFlags = NC_UUpsert;
1348 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1349 if( rc==SQLITE_OK ){
1350 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1351 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1352 }
1353 if( rc==SQLITE_OK ){
1354 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1355 }
1356 if( rc==SQLITE_OK ){
1357 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1358 }
1359 sNC.ncFlags = 0;
1360 }
dan0e14e982019-01-18 16:06:18 +00001361 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001362 sqlite3SrcListDelete(db, pSrc);
1363 }else{
1364 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001365 }
1366 }
1367 }
1368 return rc;
1369}
1370
dandd1a9c82018-09-05 08:28:30 +00001371/*
1372** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1373** objects that are part of the trigger passed as the second argument.
1374*/
danc9461ec2018-08-29 21:00:16 +00001375static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1376 TriggerStep *pStep;
1377
1378 /* Find tokens to edit in WHEN clause */
1379 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1380
1381 /* Find tokens to edit in trigger steps */
1382 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1383 sqlite3WalkSelect(pWalker, pStep->pSelect);
1384 sqlite3WalkExpr(pWalker, pStep->pWhere);
1385 sqlite3WalkExprList(pWalker, pStep->pExprList);
1386 if( pStep->pUpsert ){
1387 Upsert *pUpsert = pStep->pUpsert;
1388 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1389 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1390 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1391 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1392 }
dan7a39fae2020-10-31 16:33:01 +00001393 if( pStep->pFrom ){
1394 int i;
1395 for(i=0; i<pStep->pFrom->nSrc; i++){
1396 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1397 }
1398 }
danc9461ec2018-08-29 21:00:16 +00001399 }
1400}
1401
dandd1a9c82018-09-05 08:28:30 +00001402/*
1403** Free the contents of Parse object (*pParse). Do not free the memory
1404** occupied by the Parse object itself.
1405*/
dan141e1192018-08-31 18:23:53 +00001406static void renameParseCleanup(Parse *pParse){
1407 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001408 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001409 if( pParse->pVdbe ){
1410 sqlite3VdbeFinalize(pParse->pVdbe);
1411 }
1412 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001413 while( (pIdx = pParse->pNewIndex)!=0 ){
1414 pParse->pNewIndex = pIdx->pNext;
1415 sqlite3FreeIndex(db, pIdx);
1416 }
dan141e1192018-08-31 18:23:53 +00001417 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1418 sqlite3DbFree(db, pParse->zErrMsg);
1419 renameTokenFree(db, pParse->pRename);
1420 sqlite3ParserReset(pParse);
1421}
1422
dan06249392018-08-21 15:06:59 +00001423/*
dan987db762018-08-14 20:18:50 +00001424** SQL function:
1425**
1426** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1427**
1428** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001429** 1. type: Type of object ("table", "view" etc.)
1430** 2. object: Name of object
1431** 3. Database: Database name (e.g. "main")
1432** 4. Table: Table name
1433** 5. iCol: Index of column to rename
1434** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001435** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001436** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001437**
1438** Do a column rename operation on the CREATE statement given in zSql.
1439** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1440** into zNew. The name should be quoted if bQuote is true.
1441**
1442** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001443** It is only accessible to SQL created using sqlite3NestedParse(). It is
1444** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001445*/
dancf8f2892018-08-09 20:47:01 +00001446static void renameColumnFunc(
1447 sqlite3_context *context,
1448 int NotUsed,
1449 sqlite3_value **argv
1450){
1451 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001452 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001453 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001454 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1455 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1456 int iCol = sqlite3_value_int(argv[5]);
1457 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001458 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001459 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001460 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001461 int rc;
dancf8f2892018-08-09 20:47:01 +00001462 Parse sParse;
1463 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001464 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001465 int i;
dan987db762018-08-14 20:18:50 +00001466 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001467#ifndef SQLITE_OMIT_AUTHORIZATION
1468 sqlite3_xauth xAuth = db->xAuth;
1469#endif
dancf8f2892018-08-09 20:47:01 +00001470
drh38d99642018-08-18 18:27:18 +00001471 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001472 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001473 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001474 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001475 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001476 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001477 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001478 if( pTab==0 || iCol>=pTab->nCol ){
1479 sqlite3BtreeLeaveAll(db);
1480 return;
1481 }
drhcf9d36d2021-08-02 18:03:43 +00001482 zOld = pTab->aCol[iCol].zCnName;
dancf8f2892018-08-09 20:47:01 +00001483 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001484 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001485
dan141e1192018-08-31 18:23:53 +00001486#ifndef SQLITE_OMIT_AUTHORIZATION
1487 db->xAuth = 0;
1488#endif
drhb2ab3dc2019-12-20 14:08:34 +00001489 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001490
dancf8f2892018-08-09 20:47:01 +00001491 /* Find tokens that need to be replaced. */
1492 memset(&sWalker, 0, sizeof(Walker));
1493 sWalker.pParse = &sParse;
1494 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001495 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001496 sWalker.u.pRename = &sCtx;
1497
dan0cbb0b12018-08-16 19:49:16 +00001498 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001499 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001500 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001501 if( IsView(sParse.pNewTable) ){
1502 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan38096962019-12-09 08:13:43 +00001503 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001504 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001505 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001506 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1507 if( rc==SQLITE_OK ){
1508 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001509 }
dan987db762018-08-14 20:18:50 +00001510 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
drhe73e9572021-09-16 13:20:29 +00001511 }else if( IsOrdinaryTable(sParse.pNewTable) ){
dan987db762018-08-14 20:18:50 +00001512 /* A regular table */
1513 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1514 FKey *pFKey;
dan0cbb0b12018-08-16 19:49:16 +00001515 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001516 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001517 if( iCol<sParse.pNewTable->nCol ){
1518 renameTokenFind(
drhcf9d36d2021-08-02 18:03:43 +00001519 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
drh06258a42021-06-04 23:26:56 +00001520 );
1521 }
dan987db762018-08-14 20:18:50 +00001522 if( sCtx.iCol<0 ){
1523 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001524 }
dan987db762018-08-14 20:18:50 +00001525 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1526 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1527 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1528 }
drh885eeb62019-01-09 02:02:24 +00001529 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1530 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1531 }
drhb9bcf7c2019-10-19 13:29:10 +00001532#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001533 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001534 Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable,
1535 &sParse.pNewTable->aCol[i]);
1536 sqlite3WalkExpr(&sWalker, pExpr);
dan776a5782021-03-16 11:11:07 +00001537 }
drhb9bcf7c2019-10-19 13:29:10 +00001538#endif
dan776a5782021-03-16 11:11:07 +00001539 }
dan987db762018-08-14 20:18:50 +00001540
drh78b2fa82021-10-07 12:11:20 +00001541 assert( IsOrdinaryTable(sParse.pNewTable) );
drhf38524d2021-08-02 16:41:57 +00001542 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan987db762018-08-14 20:18:50 +00001543 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001544 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001545 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1546 }
1547 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1548 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1549 ){
1550 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1551 }
dan6fe7f232018-08-10 19:19:33 +00001552 }
dancf8f2892018-08-09 20:47:01 +00001553 }
1554 }
dan5496d6a2018-08-13 17:14:26 +00001555 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001556 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1557 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001558 }else{
dan5be60c52018-08-15 20:28:39 +00001559 /* A trigger */
1560 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001561 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001562 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001563
danc9461ec2018-08-29 21:00:16 +00001564 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1565 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001566 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001567 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001568 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001569 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1570 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001571 }
danc9461ec2018-08-29 21:00:16 +00001572 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1573 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001574 }
1575 }
1576 }
1577
dan5be60c52018-08-15 20:28:39 +00001578
1579 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001580 if( sParse.pTriggerTab==pTab ){
1581 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001582 }
dan5be60c52018-08-15 20:28:39 +00001583
danc9461ec2018-08-29 21:00:16 +00001584 /* Find tokens to edit in various expressions and selects */
1585 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001586 }
1587
dan987db762018-08-14 20:18:50 +00001588 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001589 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001590
drh5fc22cd2018-08-13 13:43:11 +00001591renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001592 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001593 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001594 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001595 }else{
1596 sqlite3_result_error_code(context, rc);
1597 }
1598 }
1599
dan141e1192018-08-31 18:23:53 +00001600 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001601 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001602#ifndef SQLITE_OMIT_AUTHORIZATION
1603 db->xAuth = xAuth;
1604#endif
drhda76adc2018-08-25 02:04:05 +00001605 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001606}
1607
dandd1a9c82018-09-05 08:28:30 +00001608/*
1609** Walker expression callback used by "RENAME TABLE".
1610*/
danc9461ec2018-08-29 21:00:16 +00001611static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1612 RenameCtx *p = pWalker->u.pRename;
drh477572b2021-10-07 20:46:29 +00001613 if( pExpr->op==TK_COLUMN
1614 && ALWAYS(ExprUseYTab(pExpr))
1615 && p->pTab==pExpr->y.pTab
1616 ){
drheda079c2018-09-20 19:02:15 +00001617 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001618 }
1619 return WRC_Continue;
1620}
1621
1622/*
dandd1a9c82018-09-05 08:28:30 +00001623** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001624*/
1625static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1626 int i;
1627 RenameCtx *p = pWalker->u.pRename;
1628 SrcList *pSrc = pSelect->pSrc;
danac67f562021-06-14 20:08:48 +00001629 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1630 testcase( pSelect->selFlags & SF_View );
1631 testcase( pSelect->selFlags & SF_CopyCte );
1632 return WRC_Prune;
1633 }
drh9da977f2021-04-20 12:14:12 +00001634 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001635 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001636 return WRC_Abort;
1637 }
danc9461ec2018-08-29 21:00:16 +00001638 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001639 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001640 if( pItem->pTab==p->pTab ){
1641 renameTokenFind(pWalker->pParse, p, pItem->zName);
1642 }
1643 }
danea412512018-12-05 13:49:04 +00001644 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001645
1646 return WRC_Continue;
1647}
1648
1649
1650/*
1651** This C function implements an SQL user function that is used by SQL code
1652** generated by the ALTER TABLE ... RENAME command to modify the definition
1653** of any foreign key constraints that use the table being renamed as the
1654** parent table. It is passed three arguments:
1655**
dan141e1192018-08-31 18:23:53 +00001656** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001657** 1. type: Type of object ("table", "view" etc.)
1658** 2. object: Name of object
1659** 3: The complete text of the schema statement being modified,
1660** 4: The old name of the table being renamed, and
1661** 5: The new name of the table being renamed.
1662** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001663**
dan141e1192018-08-31 18:23:53 +00001664** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001665**
dan141e1192018-08-31 18:23:53 +00001666** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001667** -> 'CREATE TABLE t1(a REFERENCES t3)'
1668*/
1669static void renameTableFunc(
1670 sqlite3_context *context,
1671 int NotUsed,
1672 sqlite3_value **argv
1673){
1674 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001675 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001676 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1677 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1678 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1679 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001680 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001681
dan141e1192018-08-31 18:23:53 +00001682 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001683 Parse sParse;
1684 int rc;
1685 int bQuote = 1;
1686 RenameCtx sCtx;
1687 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001688
dan141e1192018-08-31 18:23:53 +00001689#ifndef SQLITE_OMIT_AUTHORIZATION
1690 sqlite3_xauth xAuth = db->xAuth;
1691 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001692#endif
1693
dan141e1192018-08-31 18:23:53 +00001694 sqlite3BtreeEnterAll(db);
1695
1696 memset(&sCtx, 0, sizeof(RenameCtx));
1697 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1698 memset(&sWalker, 0, sizeof(Walker));
1699 sWalker.pParse = &sParse;
1700 sWalker.xExprCallback = renameTableExprCb;
1701 sWalker.xSelectCallback = renameTableSelectCb;
1702 sWalker.u.pRename = &sCtx;
1703
drhb2ab3dc2019-12-20 14:08:34 +00001704 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001705
1706 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001707 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001708 if( sParse.pNewTable ){
1709 Table *pTab = sParse.pNewTable;
1710
drhf38524d2021-08-02 16:41:57 +00001711 if( IsView(pTab) ){
dan674b8942018-09-20 08:28:01 +00001712 if( isLegacy==0 ){
drhf38524d2021-08-02 16:41:57 +00001713 Select *pSelect = pTab->u.view.pSelect;
dan674b8942018-09-20 08:28:01 +00001714 NameContext sNC;
1715 memset(&sNC, 0, sizeof(sNC));
1716 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001717
dan38096962019-12-09 08:13:43 +00001718 assert( pSelect->selFlags & SF_View );
1719 pSelect->selFlags &= ~SF_View;
drhf38524d2021-08-02 16:41:57 +00001720 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001721 if( sParse.nErr ){
1722 rc = sParse.rc;
1723 }else{
drhf38524d2021-08-02 16:41:57 +00001724 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
drh1548d522019-12-20 12:55:21 +00001725 }
dan674b8942018-09-20 08:28:01 +00001726 }
dan141e1192018-08-31 18:23:53 +00001727 }else{
1728 /* Modify any FK definitions to point to the new table. */
1729#ifndef SQLITE_OMIT_FOREIGN_KEY
drhf38524d2021-08-02 16:41:57 +00001730 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
1731 && !IsVirtual(pTab)
1732 ){
dan202a0272018-09-07 11:51:21 +00001733 FKey *pFKey;
drh78b2fa82021-10-07 12:11:20 +00001734 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +00001735 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan202a0272018-09-07 11:51:21 +00001736 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1737 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1738 }
dan141e1192018-08-31 18:23:53 +00001739 }
1740 }
1741#endif
1742
1743 /* If this is the table being altered, fix any table refs in CHECK
1744 ** expressions. Also update the name that appears right after the
1745 ** "CREATE [VIRTUAL] TABLE" bit. */
1746 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1747 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001748 if( isLegacy==0 ){
1749 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1750 }
dan141e1192018-08-31 18:23:53 +00001751 renameTokenFind(&sParse, &sCtx, pTab->zName);
1752 }
danc9461ec2018-08-29 21:00:16 +00001753 }
1754 }
danc9461ec2018-08-29 21:00:16 +00001755
dan141e1192018-08-31 18:23:53 +00001756 else if( sParse.pNewIndex ){
1757 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001758 if( isLegacy==0 ){
1759 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1760 }
dan141e1192018-08-31 18:23:53 +00001761 }
danc9461ec2018-08-29 21:00:16 +00001762
1763#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001764 else{
dan141e1192018-08-31 18:23:53 +00001765 Trigger *pTrigger = sParse.pNewTrigger;
1766 TriggerStep *pStep;
1767 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1768 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1769 ){
1770 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1771 }
danc9461ec2018-08-29 21:00:16 +00001772
dan674b8942018-09-20 08:28:01 +00001773 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001774 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001775 if( rc==SQLITE_OK ){
1776 renameWalkTrigger(&sWalker, pTrigger);
1777 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1778 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1779 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1780 }
dan141e1192018-08-31 18:23:53 +00001781 }
dan0ccda962018-08-30 16:26:48 +00001782 }
danc9461ec2018-08-29 21:00:16 +00001783 }
1784 }
dan141e1192018-08-31 18:23:53 +00001785#endif
danc9461ec2018-08-29 21:00:16 +00001786 }
dan141e1192018-08-31 18:23:53 +00001787
1788 if( rc==SQLITE_OK ){
1789 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1790 }
1791 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001792 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001793 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001794 }else{
1795 sqlite3_result_error_code(context, rc);
1796 }
dan141e1192018-08-31 18:23:53 +00001797 }
1798
1799 renameParseCleanup(&sParse);
1800 renameTokenFree(db, sCtx.pList);
1801 sqlite3BtreeLeaveAll(db);
1802#ifndef SQLITE_OMIT_AUTHORIZATION
1803 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001804#endif
1805 }
1806
danc9461ec2018-08-29 21:00:16 +00001807 return;
1808}
1809
dan1e240722021-03-15 20:22:34 +00001810static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1811 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
drhb6dad522021-09-24 16:14:47 +00001812 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
dan1e240722021-03-15 20:22:34 +00001813 }
1814 return WRC_Continue;
1815}
1816
1817/*
1818** The implementation of an SQL scalar function that rewrites DDL statements
1819** so that any string literals that use double-quotes are modified so that
1820** they use single quotes.
1821**
1822** Two arguments must be passed:
1823**
1824** 0: Database name ("main", "temp" etc.).
1825** 1: SQL statement to edit.
1826**
1827** The returned value is the modified SQL statement. For example, given
1828** the database schema:
1829**
1830** CREATE TABLE t1(a, b, c);
1831**
1832** SELECT sqlite_rename_quotefix('main',
1833** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1834** );
1835**
1836** returns the string:
1837**
1838** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1839*/
1840static void renameQuotefixFunc(
1841 sqlite3_context *context,
1842 int NotUsed,
1843 sqlite3_value **argv
1844){
1845 sqlite3 *db = sqlite3_context_db_handle(context);
1846 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1847 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1848
1849#ifndef SQLITE_OMIT_AUTHORIZATION
1850 sqlite3_xauth xAuth = db->xAuth;
1851 db->xAuth = 0;
1852#endif
1853
1854 sqlite3BtreeEnterAll(db);
1855
1856 UNUSED_PARAMETER(NotUsed);
1857 if( zDb && zInput ){
1858 int rc;
1859 Parse sParse;
1860 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1861
1862 if( rc==SQLITE_OK ){
1863 RenameCtx sCtx;
1864 Walker sWalker;
1865
1866 /* Walker to find tokens that need to be replaced. */
1867 memset(&sCtx, 0, sizeof(RenameCtx));
1868 memset(&sWalker, 0, sizeof(Walker));
1869 sWalker.pParse = &sParse;
1870 sWalker.xExprCallback = renameQuotefixExprCb;
1871 sWalker.xSelectCallback = renameColumnSelectCb;
1872 sWalker.u.pRename = &sCtx;
1873
1874 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001875 if( IsView(sParse.pNewTable) ){
1876 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan1e240722021-03-15 20:22:34 +00001877 pSelect->selFlags &= ~SF_View;
1878 sParse.rc = SQLITE_OK;
1879 sqlite3SelectPrep(&sParse, pSelect, 0);
1880 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1881 if( rc==SQLITE_OK ){
1882 sqlite3WalkSelect(&sWalker, pSelect);
1883 }
1884 }else{
1885 int i;
1886 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1887#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1888 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001889 sqlite3WalkExpr(&sWalker,
1890 sqlite3ColumnExpr(sParse.pNewTable,
1891 &sParse.pNewTable->aCol[i]));
dan1e240722021-03-15 20:22:34 +00001892 }
1893#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1894 }
1895 }else if( sParse.pNewIndex ){
1896 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1897 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1898 }else{
1899#ifndef SQLITE_OMIT_TRIGGER
1900 rc = renameResolveTrigger(&sParse);
1901 if( rc==SQLITE_OK ){
1902 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1903 }
1904#endif /* SQLITE_OMIT_TRIGGER */
1905 }
1906
1907 if( rc==SQLITE_OK ){
1908 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1909 }
dan1fffa732021-03-16 18:24:49 +00001910 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001911 }
1912 if( rc!=SQLITE_OK ){
1913 sqlite3_result_error_code(context, rc);
1914 }
1915 renameParseCleanup(&sParse);
1916 }
1917
1918#ifndef SQLITE_OMIT_AUTHORIZATION
1919 db->xAuth = xAuth;
1920#endif
1921
1922 sqlite3BtreeLeaveAll(db);
1923}
1924
dandd1a9c82018-09-05 08:28:30 +00001925/*
1926** An SQL user function that checks that there are no parse or symbol
1927** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1928** After an ALTER TABLE .. RENAME operation is performed and the schema
1929** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001930** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001931**
1932** 0: Database name ("main", "temp" etc.).
1933** 1: SQL statement.
1934** 2: Object type ("view", "table", "trigger" or "index").
1935** 3: Object name.
1936** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001937** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001938** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001939**
1940** Unless it finds an error, this function normally returns NULL. However, it
1941** returns integer value 1 if:
1942**
1943** * the SQL argument creates a trigger, and
1944** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001945*/
dan9d324822018-08-30 20:03:44 +00001946static void renameTableTest(
1947 sqlite3_context *context,
1948 int NotUsed,
1949 sqlite3_value **argv
1950){
1951 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001952 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1953 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001954 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001955 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001956 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001957 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001958
dan141e1192018-08-31 18:23:53 +00001959#ifndef SQLITE_OMIT_AUTHORIZATION
1960 sqlite3_xauth xAuth = db->xAuth;
1961 db->xAuth = 0;
1962#endif
1963
drh5b1da302018-09-01 20:02:07 +00001964 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001965
dan09236502018-09-01 16:05:50 +00001966 if( zDb && zInput ){
1967 int rc;
1968 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001969 int flags = db->flags;
1970 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001971 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001972 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001973 if( rc==SQLITE_OK ){
drhf38524d2021-08-02 16:41:57 +00001974 if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){
dan09236502018-09-01 16:05:50 +00001975 NameContext sNC;
1976 memset(&sNC, 0, sizeof(sNC));
1977 sNC.pParse = &sParse;
drhf38524d2021-08-02 16:41:57 +00001978 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
dan09236502018-09-01 16:05:50 +00001979 if( sParse.nErr ) rc = sParse.rc;
1980 }
1981
1982 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001983 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001984 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001985 }
drh3b700452018-09-07 19:12:08 +00001986 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001987 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1988 int i2 = sqlite3FindDbName(db, zDb);
1989 if( i1==i2 ) sqlite3_result_int(context, 1);
1990 }
dan09236502018-09-01 16:05:50 +00001991 }
dan9d324822018-08-30 20:03:44 +00001992 }
1993
dan16953462021-02-18 19:25:44 +00001994 if( rc!=SQLITE_OK && zWhen ){
1995 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001996 }
dan09236502018-09-01 16:05:50 +00001997 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001998 }
1999
dan141e1192018-08-31 18:23:53 +00002000#ifndef SQLITE_OMIT_AUTHORIZATION
2001 db->xAuth = xAuth;
2002#endif
dan9d324822018-08-30 20:03:44 +00002003}
2004
dancf8f2892018-08-09 20:47:01 +00002005/*
dan6a5a13d2021-02-17 20:08:22 +00002006** The implementation of internal UDF sqlite_drop_column().
2007**
dan6e6d9832021-02-16 20:43:36 +00002008** Arguments:
2009**
2010** argv[0]: An integer - the index of the schema containing the table
2011** argv[1]: CREATE TABLE statement to modify.
2012** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00002013**
2014** The value returned is a string containing the CREATE TABLE statement
2015** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00002016*/
2017static void dropColumnFunc(
2018 sqlite3_context *context,
2019 int NotUsed,
2020 sqlite3_value **argv
2021){
2022 sqlite3 *db = sqlite3_context_db_handle(context);
2023 int iSchema = sqlite3_value_int(argv[0]);
2024 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
2025 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00002026 const char *zDb = db->aDb[iSchema].zDbSName;
2027 int rc;
2028 Parse sParse;
2029 RenameToken *pCol;
2030 Table *pTab;
2031 const char *zEnd;
2032 char *zNew = 0;
2033
dan678f3b32021-02-18 20:27:46 +00002034#ifndef SQLITE_OMIT_AUTHORIZATION
2035 sqlite3_xauth xAuth = db->xAuth;
2036 db->xAuth = 0;
2037#endif
2038
drh05edf722021-03-04 19:44:01 +00002039 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00002040 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2041 if( rc!=SQLITE_OK ) goto drop_column_done;
2042 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002043 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002044 /* This can happen if the sqlite_schema table is corrupt */
2045 rc = SQLITE_CORRUPT_BKPT;
2046 goto drop_column_done;
2047 }
dan6e6d9832021-02-16 20:43:36 +00002048
drhcf9d36d2021-08-02 18:03:43 +00002049 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
dan6e6d9832021-02-16 20:43:36 +00002050 if( iCol<pTab->nCol-1 ){
2051 RenameToken *pEnd;
drhcf9d36d2021-08-02 18:03:43 +00002052 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
dan6e6d9832021-02-16 20:43:36 +00002053 zEnd = (const char*)pEnd->t.z;
2054 }else{
drh78b2fa82021-10-07 12:11:20 +00002055 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +00002056 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
drh60fe2352021-02-19 09:46:52 +00002057 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002058 }
2059
danc2a878e2021-02-17 20:46:44 +00002060 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002061 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2062 sqlite3_free(zNew);
2063
2064drop_column_done:
2065 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002066#ifndef SQLITE_OMIT_AUTHORIZATION
2067 db->xAuth = xAuth;
2068#endif
danf4a72782021-02-19 14:13:40 +00002069 if( rc!=SQLITE_OK ){
2070 sqlite3_result_error_code(context, rc);
2071 }
dan6e6d9832021-02-16 20:43:36 +00002072}
2073
dan6a5a13d2021-02-17 20:08:22 +00002074/*
2075** This function is called by the parser upon parsing an
2076**
2077** ALTER TABLE pSrc DROP COLUMN pName
2078**
2079** statement. Argument pSrc contains the possibly qualified name of the
2080** table being edited, and token pName the name of the column to drop.
2081*/
drhb6dad522021-09-24 16:14:47 +00002082void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002083 sqlite3 *db = pParse->db; /* Database handle */
2084 Table *pTab; /* Table to modify */
2085 int iDb; /* Index of db containing pTab in aDb[] */
2086 const char *zDb; /* Database containing pTab ("main" etc.) */
2087 char *zCol = 0; /* Name of column to drop */
2088 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002089
2090 /* Look up the table being altered. */
2091 assert( pParse->pNewTable==0 );
2092 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002093 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002094 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2095 if( !pTab ) goto exit_drop_column;
2096
dan6a5a13d2021-02-17 20:08:22 +00002097 /* Make sure this is not an attempt to ALTER a view, virtual table or
2098 ** system table. */
2099 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2100 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002101
2102 /* Find the index of the column being dropped. */
2103 zCol = sqlite3NameFromToken(db, pName);
2104 if( zCol==0 ){
2105 assert( db->mallocFailed );
2106 goto exit_drop_column;
2107 }
2108 iCol = sqlite3ColumnIndex(pTab, zCol);
2109 if( iCol<0 ){
2110 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2111 goto exit_drop_column;
2112 }
2113
2114 /* Do not allow the user to drop a PRIMARY KEY column or a column
2115 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002116 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2117 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2118 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2119 zCol
2120 );
dan6e6d9832021-02-16 20:43:36 +00002121 goto exit_drop_column;
2122 }
dan6e6d9832021-02-16 20:43:36 +00002123
drh239c84f2021-02-19 09:09:07 +00002124 /* Do not allow the number of columns to go to zero */
2125 if( pTab->nCol<=1 ){
2126 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2127 goto exit_drop_column;
2128 }
2129
dan6a5a13d2021-02-17 20:08:22 +00002130 /* Edit the sqlite_schema table */
2131 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2132 assert( iDb>=0 );
2133 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002134 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2135 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002136 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +00002137 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002138 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002139 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002140 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002141 );
2142
2143 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002144 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002145 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002146
2147 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002148 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002149 int i;
2150 int addr;
2151 int reg;
2152 int regRec;
2153 Index *pPk = 0;
2154 int nField = 0; /* Number of non-virtual columns after drop */
2155 int iCur;
2156 Vdbe *v = sqlite3GetVdbe(pParse);
2157 iCur = pParse->nTab++;
2158 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002159 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002160 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002161 if( HasRowid(pTab) ){
2162 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002163 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002164 }else{
2165 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002166 pParse->nMem += pPk->nColumn;
2167 for(i=0; i<pPk->nKeyCol; i++){
2168 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2169 }
2170 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002171 }
dancc263012021-04-06 21:20:39 +00002172 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002173 for(i=0; i<pTab->nCol; i++){
2174 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2175 int regOut;
2176 if( pPk ){
2177 int iPos = sqlite3TableColumnToIndex(pPk, i);
2178 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002179 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002180 regOut = reg+1+iPos-(iPos>iColPos);
2181 }else{
2182 regOut = reg+1+nField;
2183 }
dan0a746cc2021-04-18 05:30:39 +00002184 if( i==pTab->iPKey ){
2185 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2186 }else{
2187 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2188 }
dan6a5a13d2021-02-17 20:08:22 +00002189 nField++;
2190 }
2191 }
drh55b8b732021-07-22 18:22:51 +00002192 if( nField==0 ){
2193 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
2194 pParse->nMem++;
2195 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
2196 nField = 1;
2197 }
dan6a5a13d2021-02-17 20:08:22 +00002198 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2199 if( pPk ){
2200 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2201 }else{
2202 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2203 }
dan0a746cc2021-04-18 05:30:39 +00002204 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002205
drh03361402021-02-18 23:53:47 +00002206 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002207 sqlite3VdbeJumpHere(v, addr);
2208 }
dan6e6d9832021-02-16 20:43:36 +00002209
2210exit_drop_column:
2211 sqlite3DbFree(db, zCol);
2212 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002213}
2214
2215/*
dancf8f2892018-08-09 20:47:01 +00002216** Register built-in functions used to help implement ALTER TABLE
2217*/
2218void sqlite3AlterFunctions(void){
2219 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002220 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2221 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002222 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002223 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002224 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002225 };
2226 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2227}
drhd0e4a6c2005-02-15 20:47:57 +00002228#endif /* SQLITE_ALTER_TABLE */