blob: cebeec38550b026abd69876e5d5e4b690186a999 [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;
drh0c7d3d32022-01-24 16:47:12 +0000327 assert( db->pParse==pParse );
328 if( pParse->nErr ) return;
329 assert( db->mallocFailed==0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000330 pNew = pParse->pNewTable;
331 assert( pNew );
332
drh1fee73e2007-08-29 04:00:57 +0000333 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000334 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000335 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000336 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000337 pCol = &pNew->aCol[pNew->nCol-1];
drh79cf2b72021-07-31 20:30:41 +0000338 pDflt = sqlite3ColumnExpr(pNew, pCol);
drh17435752007-08-16 04:30:38 +0000339 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000340 assert( pTab );
341
drh81f2ccd2006-01-31 14:28:44 +0000342#ifndef SQLITE_OMIT_AUTHORIZATION
343 /* Invoke the authorization callback. */
344 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
345 return;
346 }
347#endif
348
danielk197719a8e7e2005-03-17 05:03:38 +0000349
350 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
351 ** If there is a NOT NULL constraint, then the default value for the
352 ** column must not be NULL.
353 */
drha371ace2012-09-13 14:22:47 +0000354 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000355 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
356 return;
357 }
358 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000359 sqlite3ErrorMsg(pParse,
360 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000361 return;
362 }
drhc27ea2a2019-10-16 20:05:56 +0000363 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
364 /* If the default value for the new column was specified with a
365 ** literal NULL, then set pDflt to 0. This simplifies checking
366 ** for an SQL NULL default below.
367 */
368 assert( pDflt==0 || pDflt->op==TK_SPAN );
369 if( pDflt && pDflt->pLeft->op==TK_NULL ){
370 pDflt = 0;
371 }
drh78b2fa82021-10-07 12:11:20 +0000372 assert( IsOrdinaryTable(pNew) );
drhf38524d2021-08-02 16:41:57 +0000373 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000374 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000375 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000376 }
377 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000378 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000379 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000380 }
381
drh9e5fdc42020-05-08 19:02:21 +0000382
drhc27ea2a2019-10-16 20:05:56 +0000383 /* Ensure the default expression is something that sqlite3ValueFromExpr()
384 ** can handle (i.e. not CURRENT_TIME etc.)
385 */
386 if( pDflt ){
387 sqlite3_value *pVal = 0;
388 int rc;
389 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
390 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
391 if( rc!=SQLITE_OK ){
392 assert( db->mallocFailed == 1 );
393 return;
394 }
395 if( !pVal ){
drh9e5fdc42020-05-08 19:02:21 +0000396 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
397 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000398 }
399 sqlite3ValueFree(pVal);
400 }
drh035f6d92019-10-24 01:04:10 +0000401 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000402 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000403 }
404
danielk197719a8e7e2005-03-17 05:03:38 +0000405
406 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000407 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000408 if( zCol ){
409 char *zEnd = &zCol[pColDef->n-1];
drh56d56f72009-04-16 16:30:17 +0000410 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000411 *zEnd-- = '\0';
412 }
drh37114fb2021-01-01 20:04:34 +0000413 /* substr() operations on characters, but addColOffset is in bytes. So we
414 ** have to use printf() to translate between these units: */
drh78b2fa82021-10-07 12:11:20 +0000415 assert( IsOrdinaryTable(pTab) );
416 assert( IsOrdinaryTable(pNew) );
danielk197719a8e7e2005-03-17 05:03:38 +0000417 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000418 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000419 "sql = printf('%%.%ds, ',sql) || %Q"
420 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000421 "WHERE type = 'table' AND name = %Q",
drhf38524d2021-08-02 16:41:57 +0000422 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000423 zTab
424 );
drh633e6d52008-07-28 19:34:53 +0000425 sqlite3DbFree(db, zCol);
danielk197719a8e7e2005-03-17 05:03:38 +0000426 }
427
dan09236502018-09-01 16:05:50 +0000428 v = sqlite3GetVdbe(pParse);
429 if( v ){
drhb4d9b2b2021-07-20 07:35:07 +0000430 /* Make sure the schema version is at least 3. But do not upgrade
431 ** from less than 3 to 4, as that will corrupt any preexisting DESC
432 ** index.
433 */
dan09236502018-09-01 16:05:50 +0000434 r1 = sqlite3GetTempReg(pParse);
435 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
436 sqlite3VdbeUsesBtree(v, iDb);
437 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
438 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
439 VdbeCoverage(v);
440 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
441 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000442
drhb4d9b2b2021-07-20 07:35:07 +0000443 /* Reload the table definition */
drhac894af2021-11-03 15:59:17 +0000444 renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd);
drhb4d9b2b2021-07-20 07:35:07 +0000445
446 /* Verify that constraints are still satisfied */
drh0f91a532021-07-20 08:23:54 +0000447 if( pNew->pCheck!=0
drhb4d9b2b2021-07-20 07:35:07 +0000448 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
449 ){
450 sqlite3NestedParse(pParse,
451 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
452 " THEN raise(ABORT,'CHECK constraint failed')"
drh0f91a532021-07-20 08:23:54 +0000453 " ELSE raise(ABORT,'NOT NULL constraint failed')"
drhb4d9b2b2021-07-20 07:35:07 +0000454 " END"
drh72e30422022-01-16 15:15:39 +0000455 " FROM pragma_quick_check(%Q,%Q)"
drh0f91a532021-07-20 08:23:54 +0000456 " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
drhb4d9b2b2021-07-20 07:35:07 +0000457 zTab, zDb
458 );
459 }
460 }
danielk197719a8e7e2005-03-17 05:03:38 +0000461}
462
drhfdd6e852005-12-16 01:06:16 +0000463/*
danielk197719a8e7e2005-03-17 05:03:38 +0000464** This function is called by the parser after the table-name in
465** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
466** pSrc is the full-name of the table being altered.
467**
468** This routine makes a (partial) copy of the Table structure
469** for the table being altered and sets Parse.pNewTable to point
470** to it. Routines called by the parser as the column definition
471** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
472** the copy. The copy of the Table structure is deleted by tokenize.c
473** after parsing is finished.
474**
475** Routine sqlite3AlterFinishAddColumn() will be called to complete
476** coding the "ALTER TABLE ... ADD" statement.
477*/
478void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
479 Table *pNew;
480 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000481 int iDb;
482 int i;
483 int nAlloc;
drh17435752007-08-16 04:30:38 +0000484 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000485
486 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000487 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000488 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000489 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000490 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000491 if( !pTab ) goto exit_begin_add_column;
492
danielk19775ee9d692006-06-21 12:36:25 +0000493#ifndef SQLITE_OMIT_VIRTUALTABLE
494 if( IsVirtual(pTab) ){
495 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
496 goto exit_begin_add_column;
497 }
498#endif
499
danielk197719a8e7e2005-03-17 05:03:38 +0000500 /* Make sure this is not an attempt to ALTER a view. */
drhf38524d2021-08-02 16:41:57 +0000501 if( IsView(pTab) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000502 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
503 goto exit_begin_add_column;
504 }
dan397a78d2018-12-18 20:31:14 +0000505 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000506 goto exit_begin_add_column;
507 }
danielk197719a8e7e2005-03-17 05:03:38 +0000508
dan03e025e2019-10-07 18:43:21 +0000509 sqlite3MayAbort(pParse);
drh78b2fa82021-10-07 12:11:20 +0000510 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +0000511 assert( pTab->u.tab.addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000512 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000513
514 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000515 ** sqlite3AddColumn() function and friends to modify. But modify
516 ** the name by adding an "sqlite_altertab_" prefix. By adding this
517 ** prefix, we insure that the name will not collide with an existing
518 ** table because user table are not allowed to have the "sqlite_"
519 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000520 */
drh17435752007-08-16 04:30:38 +0000521 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000522 if( !pNew ) goto exit_begin_add_column;
523 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000524 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000525 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000526 assert( pNew->nCol>0 );
527 nAlloc = (((pNew->nCol-1)/8)*8)+8;
528 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000529 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000530 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000531 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000532 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000533 goto exit_begin_add_column;
534 }
535 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
536 for(i=0; i<pNew->nCol; i++){
537 Column *pCol = &pNew->aCol[i];
drhcf9d36d2021-08-02 18:03:43 +0000538 pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
539 pCol->hName = sqlite3StrIHash(pCol->zCnName);
danielk197719a8e7e2005-03-17 05:03:38 +0000540 }
drh78b2fa82021-10-07 12:11:20 +0000541 assert( IsOrdinaryTable(pNew) );
drhf38524d2021-08-02 16:41:57 +0000542 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
drh17435752007-08-16 04:30:38 +0000543 pNew->pSchema = db->aDb[iDb].pSchema;
drhf38524d2021-08-02 16:41:57 +0000544 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
drh79df7782016-12-14 14:07:35 +0000545 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000546
danielk197719a8e7e2005-03-17 05:03:38 +0000547exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000548 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000549 return;
550}
dancf8f2892018-08-09 20:47:01 +0000551
drh4a2c7472018-08-13 15:09:48 +0000552/*
dan9d705572018-08-20 16:16:05 +0000553** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
554** command. This function checks if the table is a view or virtual
555** table (columns of views or virtual tables may not be renamed). If so,
556** it loads an error message into pParse and returns non-zero.
557**
558** Or, if pTab is not a view or virtual table, zero is returned.
559*/
560#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000561static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000562 const char *zType = 0;
563#ifndef SQLITE_OMIT_VIEW
drhf38524d2021-08-02 16:41:57 +0000564 if( IsView(pTab) ){
dan9d705572018-08-20 16:16:05 +0000565 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000566 }
dan9d705572018-08-20 16:16:05 +0000567#endif
568#ifndef SQLITE_OMIT_VIRTUALTABLE
569 if( IsVirtual(pTab) ){
570 zType = "virtual table";
571 }
572#endif
573 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000574 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
575 (bDrop ? "drop column from" : "rename columns of"),
576 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000577 );
578 return 1;
579 }
580 return 0;
581}
582#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000583# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000584#endif
585
586/*
drh4a2c7472018-08-13 15:09:48 +0000587** Handles the following parser reduction:
588**
589** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
590*/
dancf8f2892018-08-09 20:47:01 +0000591void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000592 Parse *pParse, /* Parsing context */
593 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
594 Token *pOld, /* Name of column being changed */
595 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000596){
drh4a2c7472018-08-13 15:09:48 +0000597 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000598 Table *pTab; /* Table being updated */
599 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000600 char *zOld = 0; /* Old column name */
601 char *zNew = 0; /* New column name */
602 const char *zDb; /* Name of schema containing the table */
603 int iSchema; /* Index of the schema */
604 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000605
drh4a2c7472018-08-13 15:09:48 +0000606 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000607 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
608 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000609
610 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000611 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000612 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000613
614 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000615 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
616 assert( iSchema>=0 );
617 zDb = db->aDb[iSchema].zDbSName;
618
drh0d019b92018-08-25 16:14:46 +0000619#ifndef SQLITE_OMIT_AUTHORIZATION
620 /* Invoke the authorization callback. */
621 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
622 goto exit_rename_column;
623 }
624#endif
625
drh4a2c7472018-08-13 15:09:48 +0000626 /* Make sure the old name really is a column name in the table to be
627 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000628 zOld = sqlite3NameFromToken(db, pOld);
629 if( !zOld ) goto exit_rename_column;
630 for(iCol=0; iCol<pTab->nCol; iCol++){
drhcf9d36d2021-08-02 18:03:43 +0000631 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;
dancf8f2892018-08-09 20:47:01 +0000632 }
633 if( iCol==pTab->nCol ){
drh4e532952022-02-08 13:41:23 +0000634 sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld);
dancf8f2892018-08-09 20:47:01 +0000635 goto exit_rename_column;
636 }
637
dan2ad080a2021-03-16 16:14:48 +0000638 /* Ensure the schema contains no double-quoted strings */
639 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
640 renameFixQuotes(pParse, zDb, iSchema==1);
641
drh4a2c7472018-08-13 15:09:48 +0000642 /* Do the rename operation using a recursive UPDATE statement that
643 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000644 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000645 */
dan1f3b2842019-03-15 16:17:32 +0000646 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000647 zNew = sqlite3NameFromToken(db, pNew);
648 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000649 assert( pNew->n>0 );
650 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000651 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000652 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000653 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000654 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
drhe73e9572021-09-16 13:20:29 +0000655 " AND (type != 'index' OR tbl_name = %Q)",
drh346a70c2020-06-15 20:27:35 +0000656 zDb,
danb87a9a82018-09-01 20:23:28 +0000657 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000658 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000659 );
660
dan9d324822018-08-30 20:03:44 +0000661 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +0000662 "UPDATE temp." LEGACY_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000663 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000664 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000665 zDb, pTab->zName, iCol, zNew, bQuote
666 );
667
dane325ffe2018-08-11 13:40:20 +0000668 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000669 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000670 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000671
dancf8f2892018-08-09 20:47:01 +0000672 exit_rename_column:
673 sqlite3SrcListDelete(db, pSrc);
674 sqlite3DbFree(db, zOld);
675 sqlite3DbFree(db, zNew);
676 return;
677}
678
drh4a2c7472018-08-13 15:09:48 +0000679/*
680** Each RenameToken object maps an element of the parse tree into
681** the token that generated that element. The parse tree element
682** might be one of:
683**
684** * A pointer to an Expr that represents an ID
685** * The name of a table column in Column.zName
686**
687** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000688** Each new object is created by sqlite3RenameTokenMap().
689** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000690** routine is used to keep the mapping current.
691**
692** After the parse finishes, renameTokenFind() routine can be used
693** to look up the actual token value that created some element in
694** the parse tree.
695*/
dancf8f2892018-08-09 20:47:01 +0000696struct RenameToken {
drhb6dad522021-09-24 16:14:47 +0000697 const void *p; /* Parse tree element created by token t */
drh4a2c7472018-08-13 15:09:48 +0000698 Token t; /* The token that created parse tree element p */
699 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000700};
701
drh4a2c7472018-08-13 15:09:48 +0000702/*
703** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
704** down into the Walker.
705*/
dan5496d6a2018-08-13 17:14:26 +0000706typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000707struct RenameCtx {
708 RenameToken *pList; /* List of tokens to overwrite */
709 int nList; /* Number of tokens in pList */
710 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000711 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000712 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000713};
714
dan8900a482018-09-05 14:36:05 +0000715#ifdef SQLITE_DEBUG
716/*
717** This function is only for debugging. It performs two tasks:
718**
719** 1. Checks that pointer pPtr does not already appear in the
720** rename-token list.
721**
722** 2. Dereferences each pointer in the rename-token list.
723**
724** The second is most effective when debugging under valgrind or
725** address-sanitizer or similar. If any of these pointers no longer
726** point to valid objects, an exception is raised by the memory-checking
727** tool.
728**
729** The point of this is to prevent comparisons of invalid pointer values.
730** Even though this always seems to work, it is undefined according to the
731** C standard. Example of undefined comparison:
732**
733** sqlite3_free(x);
734** if( x==y ) ...
735**
736** Technically, as x no longer points into a valid object or to the byte
737** following a valid object, it may not be used in comparison operations.
738*/
drhb6dad522021-09-24 16:14:47 +0000739static void renameTokenCheckAll(Parse *pParse, const void *pPtr){
drh0c7d3d32022-01-24 16:47:12 +0000740 assert( pParse==pParse->db->pParse );
741 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
742 if( pParse->nErr==0 ){
drhb6dad522021-09-24 16:14:47 +0000743 const RenameToken *p;
drhde5f3af2022-12-23 11:46:57 +0000744 u32 i = 1;
dan8900a482018-09-05 14:36:05 +0000745 for(p=pParse->pRename; p; p=p->pNext){
746 if( p->p ){
747 assert( p->p!=pPtr );
drhde5f3af2022-12-23 11:46:57 +0000748 i += *(u8*)(p->p) | 1;
dan8900a482018-09-05 14:36:05 +0000749 }
danc9461ec2018-08-29 21:00:16 +0000750 }
drhde5f3af2022-12-23 11:46:57 +0000751 assert( i>0 );
danc9461ec2018-08-29 21:00:16 +0000752 }
753}
dan8900a482018-09-05 14:36:05 +0000754#else
755# define renameTokenCheckAll(x,y)
756#endif
danc9461ec2018-08-29 21:00:16 +0000757
drh4a2c7472018-08-13 15:09:48 +0000758/*
drh49b269e2018-11-26 15:00:25 +0000759** Remember that the parser tree element pPtr was created using
760** the token pToken.
dan07e95232018-08-21 16:32:53 +0000761**
drh49b269e2018-11-26 15:00:25 +0000762** In other words, construct a new RenameToken object and add it
763** to the list of RenameToken objects currently being built up
764** in pParse->pRename.
765**
766** The pPtr argument is returned so that this routine can be used
767** with tail recursion in tokenExpr() routine, for a small performance
768** improvement.
drh4a2c7472018-08-13 15:09:48 +0000769*/
drhb6dad522021-09-24 16:14:47 +0000770const void *sqlite3RenameTokenMap(
771 Parse *pParse,
772 const void *pPtr,
773 const Token *pToken
774){
dancf8f2892018-08-09 20:47:01 +0000775 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000776 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000777 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000778 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000779 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
780 if( pNew ){
781 pNew->p = pPtr;
782 pNew->t = *pToken;
783 pNew->pNext = pParse->pRename;
784 pParse->pRename = pNew;
785 }
dancf8f2892018-08-09 20:47:01 +0000786 }
danc9461ec2018-08-29 21:00:16 +0000787
dand145e5f2018-08-21 08:29:48 +0000788 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000789}
790
drh4a2c7472018-08-13 15:09:48 +0000791/*
dan07e95232018-08-21 16:32:53 +0000792** It is assumed that there is already a RenameToken object associated
793** with parse tree element pFrom. This function remaps the associated token
794** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000795*/
drhb6dad522021-09-24 16:14:47 +0000796void sqlite3RenameTokenRemap(Parse *pParse, const void *pTo, const void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000797 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000798 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000799 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000800 if( p->p==pFrom ){
801 p->p = pTo;
802 break;
803 }
804 }
dancf8f2892018-08-09 20:47:01 +0000805}
806
drh4a2c7472018-08-13 15:09:48 +0000807/*
dan8900a482018-09-05 14:36:05 +0000808** Walker callback used by sqlite3RenameExprUnmap().
809*/
810static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
811 Parse *pParse = pWalker->pParse;
drhb6dad522021-09-24 16:14:47 +0000812 sqlite3RenameTokenRemap(pParse, 0, (const void*)pExpr);
drh477572b2021-10-07 20:46:29 +0000813 if( ExprUseYTab(pExpr) ){
814 sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
815 }
dan8900a482018-09-05 14:36:05 +0000816 return WRC_Continue;
817}
818
819/*
dan8f407622019-12-04 14:26:38 +0000820** Iterate through the Select objects that are part of WITH clauses attached
821** to select statement pSelect.
822*/
823static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000824 With *pWith = pSelect->pWith;
825 if( pWith ){
dan26d61e52021-06-11 11:14:24 +0000826 Parse *pParse = pWalker->pParse;
dan8f407622019-12-04 14:26:38 +0000827 int i;
drh35e6cd02021-06-11 13:18:56 +0000828 With *pCopy = 0;
dan26d61e52021-06-11 11:14:24 +0000829 assert( pWith->nCte>0 );
drh35e6cd02021-06-11 13:18:56 +0000830 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
831 /* Push a copy of the With object onto the with-stack. We use a copy
832 ** here as the original will be expanded and resolved (flags SF_Expanded
833 ** and SF_Resolved) below. And the parser code that uses the with-stack
834 ** fails if the Select objects on it have already been expanded and
835 ** resolved. */
836 pCopy = sqlite3WithDup(pParse->db, pWith);
drh24ce9442021-06-12 17:45:32 +0000837 pCopy = sqlite3WithPush(pParse, pCopy, 1);
drh35e6cd02021-06-11 13:18:56 +0000838 }
839 for(i=0; i<pWith->nCte; i++){
840 Select *p = pWith->a[i].pSelect;
841 NameContext sNC;
842 memset(&sNC, 0, sizeof(sNC));
843 sNC.pParse = pParse;
844 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
dan5a69d192021-09-27 15:44:03 +0000845 if( sNC.pParse->db->mallocFailed ) return;
drh35e6cd02021-06-11 13:18:56 +0000846 sqlite3WalkSelect(pWalker, p);
847 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
848 }
849 if( pCopy && pParse->pWith==pCopy ){
dand03d3a92021-06-11 12:14:58 +0000850 pParse->pWith = pCopy->pOuter;
dan26d61e52021-06-11 11:14:24 +0000851 }
dan8f407622019-12-04 14:26:38 +0000852 }
853}
854
855/*
danfb99e382020-04-03 11:20:40 +0000856** Unmap all tokens in the IdList object passed as the second argument.
857*/
858static void unmapColumnIdlistNames(
859 Parse *pParse,
drhb6dad522021-09-24 16:14:47 +0000860 const IdList *pIdList
danfb99e382020-04-03 11:20:40 +0000861){
drhd44f8b22022-04-07 01:11:13 +0000862 int ii;
863 assert( pIdList!=0 );
864 for(ii=0; ii<pIdList->nId; ii++){
865 sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
danfb99e382020-04-03 11:20:40 +0000866 }
867}
868
869/*
dan0b277a92019-06-11 12:03:10 +0000870** Walker callback used by sqlite3RenameExprUnmap().
871*/
872static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000873 Parse *pParse = pWalker->pParse;
874 int i;
drhd63b69b2019-12-04 15:08:58 +0000875 if( pParse->nErr ) return WRC_Abort;
drh0fbc19e2021-10-17 10:31:09 +0000876 testcase( p->selFlags & SF_View );
877 testcase( p->selFlags & SF_CopyCte );
drhfebf0352021-10-13 14:01:44 +0000878 if( p->selFlags & (SF_View|SF_CopyCte) ){
danac67f562021-06-14 20:08:48 +0000879 return WRC_Prune;
880 }
drhbdf4cf02019-06-15 15:21:49 +0000881 if( ALWAYS(p->pEList) ){
882 ExprList *pList = p->pEList;
883 for(i=0; i<pList->nExpr; i++){
drhd88fd532022-05-02 20:49:30 +0000884 if( pList->a[i].zEName && pList->a[i].fg.eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000885 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000886 }
887 }
888 }
drh2c3f4652019-06-11 16:43:58 +0000889 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000890 SrcList *pSrc = p->pSrc;
891 for(i=0; i<pSrc->nSrc; i++){
892 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
drhd44f8b22022-04-07 01:11:13 +0000893 if( pSrc->a[i].fg.isUsing==0 ){
894 sqlite3WalkExpr(pWalker, pSrc->a[i].u3.pOn);
895 }else{
896 unmapColumnIdlistNames(pParse, pSrc->a[i].u3.pUsing);
897 }
dan0b277a92019-06-11 12:03:10 +0000898 }
899 }
dan8f407622019-12-04 14:26:38 +0000900
901 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000902 return WRC_Continue;
903}
904
905/*
dan8900a482018-09-05 14:36:05 +0000906** Remove all nodes that are part of expression pExpr from the rename list.
907*/
908void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000909 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000910 Walker sWalker;
911 memset(&sWalker, 0, sizeof(Walker));
912 sWalker.pParse = pParse;
913 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000914 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000915 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000916 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000917 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000918}
919
920/*
dane8ab40d2018-09-12 08:51:48 +0000921** Remove all nodes that are part of expression-list pEList from the
922** rename list.
923*/
924void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
925 if( pEList ){
926 int i;
927 Walker sWalker;
928 memset(&sWalker, 0, sizeof(Walker));
929 sWalker.pParse = pParse;
930 sWalker.xExprCallback = renameUnmapExprCb;
931 sqlite3WalkExprList(&sWalker, pEList);
932 for(i=0; i<pEList->nExpr; i++){
drhd88fd532022-05-02 20:49:30 +0000933 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000934 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
935 }
dane8ab40d2018-09-12 08:51:48 +0000936 }
937 }
938}
939
940/*
drh4a2c7472018-08-13 15:09:48 +0000941** Free the list of RenameToken objects given in the second argument
942*/
dancf8f2892018-08-09 20:47:01 +0000943static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
944 RenameToken *pNext;
945 RenameToken *p;
946 for(p=pToken; p; p=pNext){
947 pNext = p->pNext;
948 sqlite3DbFree(db, p);
949 }
950}
951
dan987db762018-08-14 20:18:50 +0000952/*
953** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000954** object associated with parse tree element pPtr. If found, return a pointer
955** to it. Otherwise, return NULL.
956**
957** If the second argument passed to this function is not NULL and a matching
958** RenameToken object is found, remove it from the Parse object and add it to
959** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000960*/
dan6e6d9832021-02-16 20:43:36 +0000961static RenameToken *renameTokenFind(
962 Parse *pParse,
963 struct RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +0000964 const void *pPtr
dan6e6d9832021-02-16 20:43:36 +0000965){
dancf8f2892018-08-09 20:47:01 +0000966 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000967 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000968 return 0;
969 }
dancf8f2892018-08-09 20:47:01 +0000970 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
971 if( (*pp)->p==pPtr ){
972 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000973 if( pCtx ){
974 *pp = pToken->pNext;
975 pToken->pNext = pCtx->pList;
976 pCtx->pList = pToken;
977 pCtx->nList++;
978 }
979 return pToken;
dancf8f2892018-08-09 20:47:01 +0000980 }
981 }
dan6e6d9832021-02-16 20:43:36 +0000982 return 0;
dancf8f2892018-08-09 20:47:01 +0000983}
984
dan24fedb92018-08-18 17:35:38 +0000985/*
986** This is a Walker select callback. It does nothing. It is only required
987** because without a dummy callback, sqlite3WalkExpr() and similar do not
988** descend into sub-select statements.
989*/
dan987db762018-08-14 20:18:50 +0000990static int renameColumnSelectCb(Walker *pWalker, Select *p){
danac67f562021-06-14 20:08:48 +0000991 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000992 testcase( p->selFlags & SF_View );
993 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000994 return WRC_Prune;
995 }
danea412512018-12-05 13:49:04 +0000996 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000997 return WRC_Continue;
998}
999
dan987db762018-08-14 20:18:50 +00001000/*
1001** This is a Walker expression callback.
1002**
1003** For every TK_COLUMN node in the expression tree, search to see
1004** if the column being references is the column being renamed by an
1005** ALTER TABLE statement. If it is, then attach its associated
1006** RenameToken object to the list of RenameToken objects being
1007** constructed in RenameCtx object at pWalker->u.pRename.
1008*/
dancf8f2892018-08-09 20:47:01 +00001009static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +00001010 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +00001011 if( pExpr->op==TK_TRIGGER
1012 && pExpr->iColumn==p->iCol
1013 && pWalker->pParse->pTriggerTab==p->pTab
1014 ){
dan5be60c52018-08-15 20:28:39 +00001015 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +00001016 }else if( pExpr->op==TK_COLUMN
drh477572b2021-10-07 20:46:29 +00001017 && pExpr->iColumn==p->iCol
1018 && ALWAYS(ExprUseYTab(pExpr))
drheda079c2018-09-20 19:02:15 +00001019 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +00001020 ){
dan5496d6a2018-08-13 17:14:26 +00001021 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +00001022 }
1023 return WRC_Continue;
1024}
1025
dan987db762018-08-14 20:18:50 +00001026/*
1027** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001028** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001029** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001030** RenameContext. "Last" means the last RenameToken encountered when
1031** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001032** return all column name tokens in the order that they are encountered
1033** in the SQL statement.
1034*/
dan5496d6a2018-08-13 17:14:26 +00001035static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001036 RenameToken *pBest = pCtx->pList;
1037 RenameToken *pToken;
1038 RenameToken **pp;
1039
1040 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1041 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1042 }
1043 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1044 *pp = pBest->pNext;
1045
1046 return pBest;
1047}
1048
dan6fe7f232018-08-10 19:19:33 +00001049/*
dan24fedb92018-08-18 17:35:38 +00001050** An error occured while parsing or otherwise processing a database
1051** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1052** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1053** sub-routine is currently stored in pParse->zErrMsg. This function
1054** adds context to the error message and then stores it in pCtx.
1055*/
danb0137382018-08-20 20:01:01 +00001056static void renameColumnParseError(
1057 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001058 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001059 sqlite3_value *pType,
1060 sqlite3_value *pObject,
1061 Parse *pParse
1062){
drh79a5ee92018-08-23 19:32:04 +00001063 const char *zT = (const char*)sqlite3_value_text(pType);
1064 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001065 char *zErr;
danb0137382018-08-20 20:01:01 +00001066
drh89e9baa2022-02-06 21:13:59 +00001067 zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s",
dan16953462021-02-18 19:25:44 +00001068 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001069 pParse->zErrMsg
1070 );
dan24fedb92018-08-18 17:35:38 +00001071 sqlite3_result_error(pCtx, zErr, -1);
drh89e9baa2022-02-06 21:13:59 +00001072 sqlite3DbFree(pParse->db, zErr);
dan24fedb92018-08-18 17:35:38 +00001073}
1074
1075/*
dan06249392018-08-21 15:06:59 +00001076** For each name in the the expression-list pEList (i.e. each
1077** pEList->a[i].zName) that matches the string in zOld, extract the
1078** corresponding rename-token from Parse object pParse and add it
1079** to the RenameCtx pCtx.
1080*/
1081static void renameColumnElistNames(
1082 Parse *pParse,
1083 RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +00001084 const ExprList *pEList,
dan06249392018-08-21 15:06:59 +00001085 const char *zOld
1086){
1087 if( pEList ){
1088 int i;
1089 for(i=0; i<pEList->nExpr; i++){
drhb6dad522021-09-24 16:14:47 +00001090 const char *zName = pEList->a[i].zEName;
drhd88fd532022-05-02 20:49:30 +00001091 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME)
drh9fc1b9a2020-01-02 22:23:01 +00001092 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001093 && 0==sqlite3_stricmp(zName, zOld)
1094 ){
drhb6dad522021-09-24 16:14:47 +00001095 renameTokenFind(pParse, pCtx, (const void*)zName);
dan06249392018-08-21 15:06:59 +00001096 }
1097 }
1098 }
1099}
1100
1101/*
1102** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1103** that matches the string in zOld, extract the corresponding rename-token
1104** from Parse object pParse and add it to the RenameCtx pCtx.
1105*/
1106static void renameColumnIdlistNames(
1107 Parse *pParse,
1108 RenameCtx *pCtx,
drhb6dad522021-09-24 16:14:47 +00001109 const IdList *pIdList,
dan06249392018-08-21 15:06:59 +00001110 const char *zOld
1111){
1112 if( pIdList ){
1113 int i;
1114 for(i=0; i<pIdList->nId; i++){
drhb6dad522021-09-24 16:14:47 +00001115 const char *zName = pIdList->a[i].zName;
dan06249392018-08-21 15:06:59 +00001116 if( 0==sqlite3_stricmp(zName, zOld) ){
drhb6dad522021-09-24 16:14:47 +00001117 renameTokenFind(pParse, pCtx, (const void*)zName);
dan06249392018-08-21 15:06:59 +00001118 }
1119 }
1120 }
1121}
1122
danfb99e382020-04-03 11:20:40 +00001123
dandd1a9c82018-09-05 08:28:30 +00001124/*
1125** Parse the SQL statement zSql using Parse object (*p). The Parse object
1126** is initialized by this function before it is used.
1127*/
danc9461ec2018-08-29 21:00:16 +00001128static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001129 Parse *p, /* Memory to use for Parse object */
1130 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001131 sqlite3 *db, /* Database handle */
1132 const char *zSql, /* SQL to parse */
1133 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001134){
1135 int rc;
danc9461ec2018-08-29 21:00:16 +00001136
drhc692df22022-01-24 15:34:55 +00001137 sqlite3ParseObjectInit(p, db);
drhfde30432022-03-10 21:04:49 +00001138 if( zSql==0 ){
1139 return SQLITE_NOMEM;
1140 }
1141 if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){
1142 return SQLITE_CORRUPT_BKPT;
1143 }
1144 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
dane6dc1e52019-12-05 14:31:43 +00001145 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001146 p->db = db;
1147 p->nQueryLoop = 1;
drhfde30432022-03-10 21:04:49 +00001148 rc = sqlite3RunParser(p, zSql);
danc9461ec2018-08-29 21:00:16 +00001149 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1150 if( rc==SQLITE_OK
drhfde30432022-03-10 21:04:49 +00001151 && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)
danc9461ec2018-08-29 21:00:16 +00001152 ){
1153 rc = SQLITE_CORRUPT_BKPT;
1154 }
1155
1156#ifdef SQLITE_DEBUG
1157 /* Ensure that all mappings in the Parse.pRename list really do map to
1158 ** a part of the input string. */
1159 if( rc==SQLITE_OK ){
1160 int nSql = sqlite3Strlen30(zSql);
1161 RenameToken *pToken;
1162 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1163 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1164 }
1165 }
1166#endif
1167
1168 db->init.iDb = 0;
1169 return rc;
1170}
1171
dandd1a9c82018-09-05 08:28:30 +00001172/*
1173** This function edits SQL statement zSql, replacing each token identified
1174** by the linked list pRename with the text of zNew. If argument bQuote is
1175** true, then zNew is always quoted first. If no error occurs, the result
1176** is loaded into context object pCtx as the result.
1177**
1178** Or, if an error occurs (i.e. an OOM condition), an error is left in
1179** pCtx and an SQLite error code returned.
1180*/
danc9461ec2018-08-29 21:00:16 +00001181static int renameEditSql(
1182 sqlite3_context *pCtx, /* Return result here */
1183 RenameCtx *pRename, /* Rename context */
1184 const char *zSql, /* SQL statement to edit */
1185 const char *zNew, /* New token text */
1186 int bQuote /* True to always quote token */
1187){
drh236bcdf2021-06-16 11:32:54 +00001188 i64 nNew = sqlite3Strlen30(zNew);
1189 i64 nSql = sqlite3Strlen30(zSql);
danc9461ec2018-08-29 21:00:16 +00001190 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1191 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001192 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001193 char *zOut;
drh236bcdf2021-06-16 11:32:54 +00001194 i64 nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001195 char *zBuf1 = 0;
1196 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001197
dan1e240722021-03-15 20:22:34 +00001198 if( zNew ){
1199 /* Set zQuot to point to a buffer containing a quoted copy of the
1200 ** identifier zNew. If the corresponding identifier in the original
1201 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1202 ** point to zQuot so that all substitutions are made using the
1203 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001204 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001205 if( zQuot==0 ){
1206 return SQLITE_NOMEM;
1207 }else{
dan1d14ffe2021-03-23 22:15:34 +00001208 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001209 }
1210
1211 assert( nQuot>=nNew );
1212 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001213 }else{
dan1e240722021-03-15 20:22:34 +00001214 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1215 if( zOut ){
1216 zBuf1 = &zOut[nSql*2+1];
1217 zBuf2 = &zOut[nSql*4+2];
1218 }
danc9461ec2018-08-29 21:00:16 +00001219 }
1220
1221 /* At this point pRename->pList contains a list of RenameToken objects
1222 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001223 ** with the new column name, or with single-quoted versions of themselves.
1224 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001225 if( zOut ){
1226 int nOut = nSql;
1227 memcpy(zOut, zSql, nSql);
1228 while( pRename->pList ){
1229 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001230 u32 nReplace;
1231 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001232 RenameToken *pBest = renameColumnTokenNext(pRename);
1233
1234 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001235 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001236 nReplace = nNew;
1237 zReplace = zNew;
1238 }else{
1239 nReplace = nQuot;
1240 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001241 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001242 }
danc9461ec2018-08-29 21:00:16 +00001243 }else{
dan1e240722021-03-15 20:22:34 +00001244 /* Dequote the double-quoted token. Then requote it again, this time
1245 ** using single quotes. If the character immediately following the
1246 ** original token within the input SQL was a single quote ('), then
1247 ** add another space after the new, single-quoted version of the
1248 ** token. This is so that (SELECT "string"'alias') maps to
1249 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1250 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1251 zBuf1[pBest->t.n] = 0;
1252 sqlite3Dequote(zBuf1);
1253 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1254 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1255 );
1256 zReplace = zBuf2;
1257 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001258 }
1259
1260 iOff = pBest->t.z - zSql;
1261 if( pBest->t.n!=nReplace ){
1262 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1263 nOut - (iOff + pBest->t.n)
1264 );
1265 nOut += nReplace - pBest->t.n;
1266 zOut[nOut] = '\0';
1267 }
1268 memcpy(&zOut[iOff], zReplace, nReplace);
1269 sqlite3DbFree(db, pBest);
1270 }
1271
1272 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1273 sqlite3DbFree(db, zOut);
1274 }else{
1275 rc = SQLITE_NOMEM;
1276 }
1277
1278 sqlite3_free(zQuot);
1279 return rc;
1280}
1281
dandd1a9c82018-09-05 08:28:30 +00001282/*
1283** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1284** it was read from the schema of database zDb. Return SQLITE_OK if
1285** successful. Otherwise, return an SQLite error code and leave an error
1286** message in the Parse object.
1287*/
drha7c74002020-07-18 18:44:59 +00001288static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001289 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001290 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001291 TriggerStep *pStep;
1292 NameContext sNC;
1293 int rc = SQLITE_OK;
1294
1295 memset(&sNC, 0, sizeof(sNC));
1296 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001297 assert( pNew->pTabSchema );
1298 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1299 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1300 );
1301 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001302 /* ALWAYS() because if the table of the trigger does not exist, the
1303 ** error would have been hit before this point */
1304 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001305 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1306 }
danc9461ec2018-08-29 21:00:16 +00001307
1308 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001309 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001310 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001311 }
1312
dand5e6fef2018-09-07 15:50:31 +00001313 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001314 if( pStep->pSelect ){
1315 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1316 if( pParse->nErr ) rc = pParse->rc;
1317 }
dand5e6fef2018-09-07 15:50:31 +00001318 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001319 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1320 if( pSrc ){
dan4209d552022-05-27 15:04:43 +00001321 Select *pSel = sqlite3SelectNew(
danca29bbc2022-05-27 15:33:51 +00001322 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
dan4209d552022-05-27 15:04:43 +00001323 );
1324 if( pSel==0 ){
1325 pStep->pExprList = 0;
dan4209d552022-05-27 15:04:43 +00001326 pSrc = 0;
1327 rc = SQLITE_NOMEM;
1328 }else{
1329 sqlite3SelectPrep(pParse, pSel, 0);
1330 rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
1331 assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
dan4209d552022-05-27 15:04:43 +00001332 assert( pSrc==pSel->pSrc );
1333 if( pStep->pExprList ) pSel->pEList = 0;
dan4209d552022-05-27 15:04:43 +00001334 pSel->pSrc = 0;
1335 sqlite3SelectDelete(db, pSel);
dane7877b22020-07-14 19:51:01 +00001336 }
danb8bbe3e2022-05-26 19:10:11 +00001337 if( pStep->pFrom ){
dan4209d552022-05-27 15:04:43 +00001338 int i;
danb8bbe3e2022-05-26 19:10:11 +00001339 for(i=0; i<pStep->pFrom->nSrc && rc==SQLITE_OK; i++){
1340 SrcItem *p = &pStep->pFrom->a[i];
1341 if( p->pSelect ){
1342 sqlite3SelectPrep(pParse, p->pSelect, 0);
1343 }
1344 }
1345 }
1346
drhabe1ff32022-05-27 17:36:21 +00001347 if( db->mallocFailed ){
drh61a8ad72021-11-02 17:55:01 +00001348 rc = SQLITE_NOMEM;
1349 }
dane7877b22020-07-14 19:51:01 +00001350 sNC.pSrcList = pSrc;
1351 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001352 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1353 }
1354 if( rc==SQLITE_OK ){
1355 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1356 }
1357 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001358 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001359 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001360 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001361 sNC.uNC.pUpsert = pUpsert;
1362 sNC.ncFlags = NC_UUpsert;
1363 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1364 if( rc==SQLITE_OK ){
1365 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1366 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1367 }
1368 if( rc==SQLITE_OK ){
1369 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1370 }
1371 if( rc==SQLITE_OK ){
1372 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1373 }
1374 sNC.ncFlags = 0;
1375 }
dan0e14e982019-01-18 16:06:18 +00001376 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001377 sqlite3SrcListDelete(db, pSrc);
1378 }else{
1379 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001380 }
1381 }
1382 }
1383 return rc;
1384}
1385
dandd1a9c82018-09-05 08:28:30 +00001386/*
1387** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1388** objects that are part of the trigger passed as the second argument.
1389*/
danc9461ec2018-08-29 21:00:16 +00001390static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1391 TriggerStep *pStep;
1392
1393 /* Find tokens to edit in WHEN clause */
1394 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1395
1396 /* Find tokens to edit in trigger steps */
1397 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1398 sqlite3WalkSelect(pWalker, pStep->pSelect);
1399 sqlite3WalkExpr(pWalker, pStep->pWhere);
1400 sqlite3WalkExprList(pWalker, pStep->pExprList);
1401 if( pStep->pUpsert ){
1402 Upsert *pUpsert = pStep->pUpsert;
1403 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1404 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1405 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1406 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1407 }
dan7a39fae2020-10-31 16:33:01 +00001408 if( pStep->pFrom ){
1409 int i;
1410 for(i=0; i<pStep->pFrom->nSrc; i++){
1411 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1412 }
1413 }
danc9461ec2018-08-29 21:00:16 +00001414 }
1415}
1416
dandd1a9c82018-09-05 08:28:30 +00001417/*
1418** Free the contents of Parse object (*pParse). Do not free the memory
1419** occupied by the Parse object itself.
1420*/
dan141e1192018-08-31 18:23:53 +00001421static void renameParseCleanup(Parse *pParse){
1422 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001423 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001424 if( pParse->pVdbe ){
1425 sqlite3VdbeFinalize(pParse->pVdbe);
1426 }
1427 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001428 while( (pIdx = pParse->pNewIndex)!=0 ){
1429 pParse->pNewIndex = pIdx->pNext;
1430 sqlite3FreeIndex(db, pIdx);
1431 }
dan141e1192018-08-31 18:23:53 +00001432 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1433 sqlite3DbFree(db, pParse->zErrMsg);
1434 renameTokenFree(db, pParse->pRename);
drhc692df22022-01-24 15:34:55 +00001435 sqlite3ParseObjectReset(pParse);
dan141e1192018-08-31 18:23:53 +00001436}
1437
dan06249392018-08-21 15:06:59 +00001438/*
dan987db762018-08-14 20:18:50 +00001439** SQL function:
1440**
drh5a800502022-02-04 16:43:30 +00001441** sqlite_rename_column(SQL,TYPE,OBJ,DB,TABLE,COL,NEWNAME,QUOTE,TEMP)
dan987db762018-08-14 20:18:50 +00001442**
1443** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001444** 1. type: Type of object ("table", "view" etc.)
1445** 2. object: Name of object
1446** 3. Database: Database name (e.g. "main")
1447** 4. Table: Table name
1448** 5. iCol: Index of column to rename
1449** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001450** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001451** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001452**
1453** Do a column rename operation on the CREATE statement given in zSql.
1454** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1455** into zNew. The name should be quoted if bQuote is true.
1456**
1457** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001458** It is only accessible to SQL created using sqlite3NestedParse(). It is
drh5a800502022-02-04 16:43:30 +00001459** not reachable from ordinary SQL passed into sqlite3_prepare() unless the
1460** SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test setting is enabled.
dan6fe7f232018-08-10 19:19:33 +00001461*/
dancf8f2892018-08-09 20:47:01 +00001462static void renameColumnFunc(
1463 sqlite3_context *context,
1464 int NotUsed,
1465 sqlite3_value **argv
1466){
1467 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001468 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001469 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001470 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1471 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1472 int iCol = sqlite3_value_int(argv[5]);
1473 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001474 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001475 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001476 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001477 int rc;
dancf8f2892018-08-09 20:47:01 +00001478 Parse sParse;
1479 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001480 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001481 int i;
dan987db762018-08-14 20:18:50 +00001482 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001483#ifndef SQLITE_OMIT_AUTHORIZATION
1484 sqlite3_xauth xAuth = db->xAuth;
1485#endif
dancf8f2892018-08-09 20:47:01 +00001486
drh38d99642018-08-18 18:27:18 +00001487 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001488 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001489 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001490 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001491 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001492 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001493 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001494 if( pTab==0 || iCol>=pTab->nCol ){
1495 sqlite3BtreeLeaveAll(db);
1496 return;
1497 }
drhcf9d36d2021-08-02 18:03:43 +00001498 zOld = pTab->aCol[iCol].zCnName;
dancf8f2892018-08-09 20:47:01 +00001499 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001500 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001501
dan141e1192018-08-31 18:23:53 +00001502#ifndef SQLITE_OMIT_AUTHORIZATION
1503 db->xAuth = 0;
1504#endif
drhb2ab3dc2019-12-20 14:08:34 +00001505 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001506
dancf8f2892018-08-09 20:47:01 +00001507 /* Find tokens that need to be replaced. */
1508 memset(&sWalker, 0, sizeof(Walker));
1509 sWalker.pParse = &sParse;
1510 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001511 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001512 sWalker.u.pRename = &sCtx;
1513
dan0cbb0b12018-08-16 19:49:16 +00001514 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001515 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001516 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001517 if( IsView(sParse.pNewTable) ){
1518 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan38096962019-12-09 08:13:43 +00001519 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001520 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001521 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001522 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1523 if( rc==SQLITE_OK ){
1524 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001525 }
dan987db762018-08-14 20:18:50 +00001526 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
drhe73e9572021-09-16 13:20:29 +00001527 }else if( IsOrdinaryTable(sParse.pNewTable) ){
dan987db762018-08-14 20:18:50 +00001528 /* A regular table */
1529 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1530 FKey *pFKey;
dan0cbb0b12018-08-16 19:49:16 +00001531 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001532 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001533 if( iCol<sParse.pNewTable->nCol ){
1534 renameTokenFind(
drhcf9d36d2021-08-02 18:03:43 +00001535 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
drh06258a42021-06-04 23:26:56 +00001536 );
1537 }
dan987db762018-08-14 20:18:50 +00001538 if( sCtx.iCol<0 ){
1539 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001540 }
dan987db762018-08-14 20:18:50 +00001541 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1542 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1543 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1544 }
drh885eeb62019-01-09 02:02:24 +00001545 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1546 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1547 }
drhb9bcf7c2019-10-19 13:29:10 +00001548#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001549 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001550 Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable,
1551 &sParse.pNewTable->aCol[i]);
1552 sqlite3WalkExpr(&sWalker, pExpr);
dan776a5782021-03-16 11:11:07 +00001553 }
drhb9bcf7c2019-10-19 13:29:10 +00001554#endif
dan776a5782021-03-16 11:11:07 +00001555 }
dan987db762018-08-14 20:18:50 +00001556
drh78b2fa82021-10-07 12:11:20 +00001557 assert( IsOrdinaryTable(sParse.pNewTable) );
drhf38524d2021-08-02 16:41:57 +00001558 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan987db762018-08-14 20:18:50 +00001559 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001560 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001561 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1562 }
1563 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1564 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1565 ){
1566 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1567 }
dan6fe7f232018-08-10 19:19:33 +00001568 }
dancf8f2892018-08-09 20:47:01 +00001569 }
1570 }
dan5496d6a2018-08-13 17:14:26 +00001571 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001572 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1573 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001574 }else{
dan5be60c52018-08-15 20:28:39 +00001575 /* A trigger */
1576 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001577 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001578 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001579
danc9461ec2018-08-29 21:00:16 +00001580 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1581 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001582 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001583 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001584 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001585 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1586 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001587 }
danc9461ec2018-08-29 21:00:16 +00001588 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1589 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001590 }
1591 }
1592 }
1593
dan5be60c52018-08-15 20:28:39 +00001594
1595 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001596 if( sParse.pTriggerTab==pTab ){
1597 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001598 }
dan5be60c52018-08-15 20:28:39 +00001599
danc9461ec2018-08-29 21:00:16 +00001600 /* Find tokens to edit in various expressions and selects */
1601 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001602 }
1603
dan987db762018-08-14 20:18:50 +00001604 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001605 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001606
drh5fc22cd2018-08-13 13:43:11 +00001607renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001608 if( rc!=SQLITE_OK ){
drh89e9baa2022-02-06 21:13:59 +00001609 if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
drh5a800502022-02-04 16:43:30 +00001610 sqlite3_result_value(context, argv[0]);
1611 }else if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001612 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001613 }else{
1614 sqlite3_result_error_code(context, rc);
1615 }
1616 }
1617
dan141e1192018-08-31 18:23:53 +00001618 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001619 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001620#ifndef SQLITE_OMIT_AUTHORIZATION
1621 db->xAuth = xAuth;
1622#endif
drhda76adc2018-08-25 02:04:05 +00001623 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001624}
1625
dandd1a9c82018-09-05 08:28:30 +00001626/*
1627** Walker expression callback used by "RENAME TABLE".
1628*/
danc9461ec2018-08-29 21:00:16 +00001629static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1630 RenameCtx *p = pWalker->u.pRename;
drh477572b2021-10-07 20:46:29 +00001631 if( pExpr->op==TK_COLUMN
1632 && ALWAYS(ExprUseYTab(pExpr))
1633 && p->pTab==pExpr->y.pTab
1634 ){
drheda079c2018-09-20 19:02:15 +00001635 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001636 }
1637 return WRC_Continue;
1638}
1639
1640/*
dandd1a9c82018-09-05 08:28:30 +00001641** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001642*/
1643static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1644 int i;
1645 RenameCtx *p = pWalker->u.pRename;
1646 SrcList *pSrc = pSelect->pSrc;
danac67f562021-06-14 20:08:48 +00001647 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1648 testcase( pSelect->selFlags & SF_View );
1649 testcase( pSelect->selFlags & SF_CopyCte );
1650 return WRC_Prune;
1651 }
drh9da977f2021-04-20 12:14:12 +00001652 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001653 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001654 return WRC_Abort;
1655 }
danc9461ec2018-08-29 21:00:16 +00001656 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001657 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001658 if( pItem->pTab==p->pTab ){
1659 renameTokenFind(pWalker->pParse, p, pItem->zName);
1660 }
1661 }
danea412512018-12-05 13:49:04 +00001662 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001663
1664 return WRC_Continue;
1665}
1666
1667
1668/*
1669** This C function implements an SQL user function that is used by SQL code
1670** generated by the ALTER TABLE ... RENAME command to modify the definition
1671** of any foreign key constraints that use the table being renamed as the
1672** parent table. It is passed three arguments:
1673**
dan141e1192018-08-31 18:23:53 +00001674** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001675** 1. type: Type of object ("table", "view" etc.)
1676** 2. object: Name of object
1677** 3: The complete text of the schema statement being modified,
1678** 4: The old name of the table being renamed, and
1679** 5: The new name of the table being renamed.
1680** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001681**
dan141e1192018-08-31 18:23:53 +00001682** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001683**
dan141e1192018-08-31 18:23:53 +00001684** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001685** -> 'CREATE TABLE t1(a REFERENCES t3)'
1686*/
1687static void renameTableFunc(
1688 sqlite3_context *context,
1689 int NotUsed,
1690 sqlite3_value **argv
1691){
1692 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001693 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001694 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1695 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1696 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1697 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001698 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001699
dan141e1192018-08-31 18:23:53 +00001700 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001701 Parse sParse;
1702 int rc;
1703 int bQuote = 1;
1704 RenameCtx sCtx;
1705 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001706
dan141e1192018-08-31 18:23:53 +00001707#ifndef SQLITE_OMIT_AUTHORIZATION
1708 sqlite3_xauth xAuth = db->xAuth;
1709 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001710#endif
1711
dan141e1192018-08-31 18:23:53 +00001712 sqlite3BtreeEnterAll(db);
1713
1714 memset(&sCtx, 0, sizeof(RenameCtx));
1715 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1716 memset(&sWalker, 0, sizeof(Walker));
1717 sWalker.pParse = &sParse;
1718 sWalker.xExprCallback = renameTableExprCb;
1719 sWalker.xSelectCallback = renameTableSelectCb;
1720 sWalker.u.pRename = &sCtx;
1721
drhb2ab3dc2019-12-20 14:08:34 +00001722 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001723
1724 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001725 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001726 if( sParse.pNewTable ){
1727 Table *pTab = sParse.pNewTable;
1728
drhf38524d2021-08-02 16:41:57 +00001729 if( IsView(pTab) ){
dan674b8942018-09-20 08:28:01 +00001730 if( isLegacy==0 ){
drhf38524d2021-08-02 16:41:57 +00001731 Select *pSelect = pTab->u.view.pSelect;
dan674b8942018-09-20 08:28:01 +00001732 NameContext sNC;
1733 memset(&sNC, 0, sizeof(sNC));
1734 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001735
dan38096962019-12-09 08:13:43 +00001736 assert( pSelect->selFlags & SF_View );
1737 pSelect->selFlags &= ~SF_View;
drhf38524d2021-08-02 16:41:57 +00001738 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001739 if( sParse.nErr ){
1740 rc = sParse.rc;
1741 }else{
drhf38524d2021-08-02 16:41:57 +00001742 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
drh1548d522019-12-20 12:55:21 +00001743 }
dan674b8942018-09-20 08:28:01 +00001744 }
dan141e1192018-08-31 18:23:53 +00001745 }else{
1746 /* Modify any FK definitions to point to the new table. */
1747#ifndef SQLITE_OMIT_FOREIGN_KEY
drhf38524d2021-08-02 16:41:57 +00001748 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
1749 && !IsVirtual(pTab)
1750 ){
dan202a0272018-09-07 11:51:21 +00001751 FKey *pFKey;
drh78b2fa82021-10-07 12:11:20 +00001752 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +00001753 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan202a0272018-09-07 11:51:21 +00001754 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1755 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1756 }
dan141e1192018-08-31 18:23:53 +00001757 }
1758 }
1759#endif
1760
1761 /* If this is the table being altered, fix any table refs in CHECK
1762 ** expressions. Also update the name that appears right after the
1763 ** "CREATE [VIRTUAL] TABLE" bit. */
1764 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1765 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001766 if( isLegacy==0 ){
1767 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1768 }
dan141e1192018-08-31 18:23:53 +00001769 renameTokenFind(&sParse, &sCtx, pTab->zName);
1770 }
danc9461ec2018-08-29 21:00:16 +00001771 }
1772 }
danc9461ec2018-08-29 21:00:16 +00001773
dan141e1192018-08-31 18:23:53 +00001774 else if( sParse.pNewIndex ){
1775 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001776 if( isLegacy==0 ){
1777 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1778 }
dan141e1192018-08-31 18:23:53 +00001779 }
danc9461ec2018-08-29 21:00:16 +00001780
1781#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001782 else{
dan141e1192018-08-31 18:23:53 +00001783 Trigger *pTrigger = sParse.pNewTrigger;
1784 TriggerStep *pStep;
1785 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1786 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1787 ){
1788 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1789 }
danc9461ec2018-08-29 21:00:16 +00001790
dan674b8942018-09-20 08:28:01 +00001791 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001792 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001793 if( rc==SQLITE_OK ){
1794 renameWalkTrigger(&sWalker, pTrigger);
1795 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1796 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1797 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1798 }
danb8bbe3e2022-05-26 19:10:11 +00001799 if( pStep->pFrom ){
1800 int i;
1801 for(i=0; i<pStep->pFrom->nSrc; i++){
1802 SrcItem *pItem = &pStep->pFrom->a[i];
drh8d2f6612022-05-27 14:41:48 +00001803 if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
danb8bbe3e2022-05-26 19:10:11 +00001804 renameTokenFind(&sParse, &sCtx, pItem->zName);
1805 }
1806 }
1807 }
dan141e1192018-08-31 18:23:53 +00001808 }
dan0ccda962018-08-30 16:26:48 +00001809 }
danc9461ec2018-08-29 21:00:16 +00001810 }
1811 }
dan141e1192018-08-31 18:23:53 +00001812#endif
danc9461ec2018-08-29 21:00:16 +00001813 }
dan141e1192018-08-31 18:23:53 +00001814
1815 if( rc==SQLITE_OK ){
1816 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1817 }
1818 if( rc!=SQLITE_OK ){
drh89e9baa2022-02-06 21:13:59 +00001819 if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){
drh10d29c72022-02-04 20:07:24 +00001820 sqlite3_result_value(context, argv[3]);
1821 }else if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001822 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001823 }else{
1824 sqlite3_result_error_code(context, rc);
1825 }
dan141e1192018-08-31 18:23:53 +00001826 }
1827
1828 renameParseCleanup(&sParse);
1829 renameTokenFree(db, sCtx.pList);
1830 sqlite3BtreeLeaveAll(db);
1831#ifndef SQLITE_OMIT_AUTHORIZATION
1832 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001833#endif
1834 }
1835
danc9461ec2018-08-29 21:00:16 +00001836 return;
1837}
1838
dan1e240722021-03-15 20:22:34 +00001839static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1840 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
drhb6dad522021-09-24 16:14:47 +00001841 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
dan1e240722021-03-15 20:22:34 +00001842 }
1843 return WRC_Continue;
1844}
1845
drh5a800502022-02-04 16:43:30 +00001846/* SQL function: sqlite_rename_quotefix(DB,SQL)
1847**
1848** Rewrite the DDL statement "SQL" so that any string literals that use
1849** double-quotes use single quotes instead.
dan1e240722021-03-15 20:22:34 +00001850**
1851** Two arguments must be passed:
1852**
1853** 0: Database name ("main", "temp" etc.).
1854** 1: SQL statement to edit.
1855**
1856** The returned value is the modified SQL statement. For example, given
1857** the database schema:
1858**
1859** CREATE TABLE t1(a, b, c);
1860**
1861** SELECT sqlite_rename_quotefix('main',
1862** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1863** );
1864**
1865** returns the string:
1866**
1867** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
drh5a800502022-02-04 16:43:30 +00001868**
1869** If there is a error in the input SQL, then raise an error, except
1870** if PRAGMA writable_schema=ON, then just return the input string
1871** unmodified following an error.
dan1e240722021-03-15 20:22:34 +00001872*/
1873static void renameQuotefixFunc(
1874 sqlite3_context *context,
1875 int NotUsed,
1876 sqlite3_value **argv
1877){
1878 sqlite3 *db = sqlite3_context_db_handle(context);
1879 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1880 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1881
1882#ifndef SQLITE_OMIT_AUTHORIZATION
1883 sqlite3_xauth xAuth = db->xAuth;
1884 db->xAuth = 0;
1885#endif
1886
1887 sqlite3BtreeEnterAll(db);
1888
1889 UNUSED_PARAMETER(NotUsed);
1890 if( zDb && zInput ){
1891 int rc;
1892 Parse sParse;
1893 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1894
1895 if( rc==SQLITE_OK ){
1896 RenameCtx sCtx;
1897 Walker sWalker;
1898
1899 /* Walker to find tokens that need to be replaced. */
1900 memset(&sCtx, 0, sizeof(RenameCtx));
1901 memset(&sWalker, 0, sizeof(Walker));
1902 sWalker.pParse = &sParse;
1903 sWalker.xExprCallback = renameQuotefixExprCb;
1904 sWalker.xSelectCallback = renameColumnSelectCb;
1905 sWalker.u.pRename = &sCtx;
1906
1907 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001908 if( IsView(sParse.pNewTable) ){
1909 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan1e240722021-03-15 20:22:34 +00001910 pSelect->selFlags &= ~SF_View;
1911 sParse.rc = SQLITE_OK;
1912 sqlite3SelectPrep(&sParse, pSelect, 0);
1913 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1914 if( rc==SQLITE_OK ){
1915 sqlite3WalkSelect(&sWalker, pSelect);
1916 }
1917 }else{
1918 int i;
1919 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1920#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1921 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001922 sqlite3WalkExpr(&sWalker,
1923 sqlite3ColumnExpr(sParse.pNewTable,
1924 &sParse.pNewTable->aCol[i]));
dan1e240722021-03-15 20:22:34 +00001925 }
1926#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1927 }
1928 }else if( sParse.pNewIndex ){
1929 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1930 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1931 }else{
1932#ifndef SQLITE_OMIT_TRIGGER
1933 rc = renameResolveTrigger(&sParse);
1934 if( rc==SQLITE_OK ){
1935 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1936 }
1937#endif /* SQLITE_OMIT_TRIGGER */
1938 }
1939
1940 if( rc==SQLITE_OK ){
1941 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1942 }
dan1fffa732021-03-16 18:24:49 +00001943 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001944 }
1945 if( rc!=SQLITE_OK ){
drh89e9baa2022-02-06 21:13:59 +00001946 if( sqlite3WritableSchema(db) && rc==SQLITE_ERROR ){
drh5a800502022-02-04 16:43:30 +00001947 sqlite3_result_value(context, argv[1]);
1948 }else{
1949 sqlite3_result_error_code(context, rc);
1950 }
dan1e240722021-03-15 20:22:34 +00001951 }
1952 renameParseCleanup(&sParse);
1953 }
1954
1955#ifndef SQLITE_OMIT_AUTHORIZATION
1956 db->xAuth = xAuth;
1957#endif
1958
1959 sqlite3BtreeLeaveAll(db);
1960}
1961
drh5a800502022-02-04 16:43:30 +00001962/* Function: sqlite_rename_test(DB,SQL,TYPE,NAME,ISTEMP,WHEN,DQS)
1963**
dandd1a9c82018-09-05 08:28:30 +00001964** An SQL user function that checks that there are no parse or symbol
1965** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1966** After an ALTER TABLE .. RENAME operation is performed and the schema
1967** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001968** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001969**
1970** 0: Database name ("main", "temp" etc.).
1971** 1: SQL statement.
1972** 2: Object type ("view", "table", "trigger" or "index").
1973** 3: Object name.
1974** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001975** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001976** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001977**
drh5a800502022-02-04 16:43:30 +00001978** The return value is computed as follows:
dan1d85c6b2018-09-06 16:01:37 +00001979**
drh5a800502022-02-04 16:43:30 +00001980** A. If an error is seen and not in PRAGMA writable_schema=ON mode,
1981** then raise the error.
1982** B. Else if a trigger is created and the the table that the trigger is
1983** attached to is in database zDb, then return 1.
1984** C. Otherwise return NULL.
dandd1a9c82018-09-05 08:28:30 +00001985*/
dan9d324822018-08-30 20:03:44 +00001986static void renameTableTest(
1987 sqlite3_context *context,
1988 int NotUsed,
1989 sqlite3_value **argv
1990){
1991 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001992 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1993 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001994 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001995 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001996 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001997 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001998
dan141e1192018-08-31 18:23:53 +00001999#ifndef SQLITE_OMIT_AUTHORIZATION
2000 sqlite3_xauth xAuth = db->xAuth;
2001 db->xAuth = 0;
2002#endif
2003
drh5b1da302018-09-01 20:02:07 +00002004 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00002005
dan09236502018-09-01 16:05:50 +00002006 if( zDb && zInput ){
2007 int rc;
2008 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00002009 int flags = db->flags;
2010 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00002011 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00002012 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00002013 if( rc==SQLITE_OK ){
drhf38524d2021-08-02 16:41:57 +00002014 if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){
dan09236502018-09-01 16:05:50 +00002015 NameContext sNC;
2016 memset(&sNC, 0, sizeof(sNC));
2017 sNC.pParse = &sParse;
drhf38524d2021-08-02 16:41:57 +00002018 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
dan09236502018-09-01 16:05:50 +00002019 if( sParse.nErr ) rc = sParse.rc;
2020 }
2021
2022 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00002023 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00002024 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00002025 }
drh3b700452018-09-07 19:12:08 +00002026 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00002027 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
2028 int i2 = sqlite3FindDbName(db, zDb);
drh5a800502022-02-04 16:43:30 +00002029 if( i1==i2 ){
2030 /* Handle output case B */
2031 sqlite3_result_int(context, 1);
2032 }
dan1d85c6b2018-09-06 16:01:37 +00002033 }
dan09236502018-09-01 16:05:50 +00002034 }
dan9d324822018-08-30 20:03:44 +00002035 }
2036
drh569c1052022-02-05 12:05:43 +00002037 if( rc!=SQLITE_OK && zWhen && !sqlite3WritableSchema(db) ){
drh5a800502022-02-04 16:43:30 +00002038 /* Output case A */
dan16953462021-02-18 19:25:44 +00002039 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00002040 }
dan09236502018-09-01 16:05:50 +00002041 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00002042 }
2043
dan141e1192018-08-31 18:23:53 +00002044#ifndef SQLITE_OMIT_AUTHORIZATION
2045 db->xAuth = xAuth;
2046#endif
dan9d324822018-08-30 20:03:44 +00002047}
2048
dancf8f2892018-08-09 20:47:01 +00002049/*
dan6a5a13d2021-02-17 20:08:22 +00002050** The implementation of internal UDF sqlite_drop_column().
2051**
dan6e6d9832021-02-16 20:43:36 +00002052** Arguments:
2053**
2054** argv[0]: An integer - the index of the schema containing the table
2055** argv[1]: CREATE TABLE statement to modify.
2056** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00002057**
2058** The value returned is a string containing the CREATE TABLE statement
2059** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00002060*/
2061static void dropColumnFunc(
2062 sqlite3_context *context,
2063 int NotUsed,
2064 sqlite3_value **argv
2065){
2066 sqlite3 *db = sqlite3_context_db_handle(context);
2067 int iSchema = sqlite3_value_int(argv[0]);
2068 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
2069 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00002070 const char *zDb = db->aDb[iSchema].zDbSName;
2071 int rc;
2072 Parse sParse;
2073 RenameToken *pCol;
2074 Table *pTab;
2075 const char *zEnd;
2076 char *zNew = 0;
2077
dan678f3b32021-02-18 20:27:46 +00002078#ifndef SQLITE_OMIT_AUTHORIZATION
2079 sqlite3_xauth xAuth = db->xAuth;
2080 db->xAuth = 0;
2081#endif
2082
drh05edf722021-03-04 19:44:01 +00002083 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00002084 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2085 if( rc!=SQLITE_OK ) goto drop_column_done;
2086 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002087 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002088 /* This can happen if the sqlite_schema table is corrupt */
2089 rc = SQLITE_CORRUPT_BKPT;
2090 goto drop_column_done;
2091 }
dan6e6d9832021-02-16 20:43:36 +00002092
drhcf9d36d2021-08-02 18:03:43 +00002093 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
dan6e6d9832021-02-16 20:43:36 +00002094 if( iCol<pTab->nCol-1 ){
2095 RenameToken *pEnd;
drhcf9d36d2021-08-02 18:03:43 +00002096 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
dan6e6d9832021-02-16 20:43:36 +00002097 zEnd = (const char*)pEnd->t.z;
2098 }else{
drh78b2fa82021-10-07 12:11:20 +00002099 assert( IsOrdinaryTable(pTab) );
drhf38524d2021-08-02 16:41:57 +00002100 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
drh60fe2352021-02-19 09:46:52 +00002101 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002102 }
2103
danc2a878e2021-02-17 20:46:44 +00002104 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002105 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2106 sqlite3_free(zNew);
2107
2108drop_column_done:
2109 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002110#ifndef SQLITE_OMIT_AUTHORIZATION
2111 db->xAuth = xAuth;
2112#endif
danf4a72782021-02-19 14:13:40 +00002113 if( rc!=SQLITE_OK ){
2114 sqlite3_result_error_code(context, rc);
2115 }
dan6e6d9832021-02-16 20:43:36 +00002116}
2117
dan6a5a13d2021-02-17 20:08:22 +00002118/*
2119** This function is called by the parser upon parsing an
2120**
2121** ALTER TABLE pSrc DROP COLUMN pName
2122**
2123** statement. Argument pSrc contains the possibly qualified name of the
2124** table being edited, and token pName the name of the column to drop.
2125*/
drhb6dad522021-09-24 16:14:47 +00002126void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002127 sqlite3 *db = pParse->db; /* Database handle */
2128 Table *pTab; /* Table to modify */
2129 int iDb; /* Index of db containing pTab in aDb[] */
2130 const char *zDb; /* Database containing pTab ("main" etc.) */
2131 char *zCol = 0; /* Name of column to drop */
2132 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002133
2134 /* Look up the table being altered. */
2135 assert( pParse->pNewTable==0 );
2136 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002137 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002138 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2139 if( !pTab ) goto exit_drop_column;
2140
dan6a5a13d2021-02-17 20:08:22 +00002141 /* Make sure this is not an attempt to ALTER a view, virtual table or
2142 ** system table. */
2143 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2144 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002145
2146 /* Find the index of the column being dropped. */
2147 zCol = sqlite3NameFromToken(db, pName);
2148 if( zCol==0 ){
2149 assert( db->mallocFailed );
2150 goto exit_drop_column;
2151 }
2152 iCol = sqlite3ColumnIndex(pTab, zCol);
2153 if( iCol<0 ){
drh4e532952022-02-08 13:41:23 +00002154 sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pName);
dan6e6d9832021-02-16 20:43:36 +00002155 goto exit_drop_column;
2156 }
2157
2158 /* Do not allow the user to drop a PRIMARY KEY column or a column
2159 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002160 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2161 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2162 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2163 zCol
2164 );
dan6e6d9832021-02-16 20:43:36 +00002165 goto exit_drop_column;
2166 }
dan6e6d9832021-02-16 20:43:36 +00002167
drh239c84f2021-02-19 09:09:07 +00002168 /* Do not allow the number of columns to go to zero */
2169 if( pTab->nCol<=1 ){
2170 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2171 goto exit_drop_column;
2172 }
2173
dan6a5a13d2021-02-17 20:08:22 +00002174 /* Edit the sqlite_schema table */
2175 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2176 assert( iDb>=0 );
2177 zDb = db->aDb[iDb].zDbSName;
drh85b70e02022-01-18 16:16:32 +00002178#ifndef SQLITE_OMIT_AUTHORIZATION
2179 /* Invoke the authorization callback. */
2180 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){
2181 goto exit_drop_column;
2182 }
2183#endif
dan2ad080a2021-03-16 16:14:48 +00002184 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2185 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002186 sqlite3NestedParse(pParse,
drha4a871c2021-11-04 14:04:20 +00002187 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002188 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002189 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002190 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002191 );
2192
2193 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002194 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002195 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002196
2197 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002198 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002199 int i;
2200 int addr;
2201 int reg;
2202 int regRec;
2203 Index *pPk = 0;
2204 int nField = 0; /* Number of non-virtual columns after drop */
2205 int iCur;
2206 Vdbe *v = sqlite3GetVdbe(pParse);
2207 iCur = pParse->nTab++;
2208 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002209 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002210 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002211 if( HasRowid(pTab) ){
2212 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002213 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002214 }else{
2215 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002216 pParse->nMem += pPk->nColumn;
2217 for(i=0; i<pPk->nKeyCol; i++){
2218 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2219 }
2220 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002221 }
dancc263012021-04-06 21:20:39 +00002222 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002223 for(i=0; i<pTab->nCol; i++){
2224 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2225 int regOut;
2226 if( pPk ){
2227 int iPos = sqlite3TableColumnToIndex(pPk, i);
2228 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002229 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002230 regOut = reg+1+iPos-(iPos>iColPos);
2231 }else{
2232 regOut = reg+1+nField;
2233 }
dan0a746cc2021-04-18 05:30:39 +00002234 if( i==pTab->iPKey ){
2235 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2236 }else{
2237 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2238 }
dan6a5a13d2021-02-17 20:08:22 +00002239 nField++;
2240 }
2241 }
drh55b8b732021-07-22 18:22:51 +00002242 if( nField==0 ){
2243 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
2244 pParse->nMem++;
2245 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
2246 nField = 1;
2247 }
dan6a5a13d2021-02-17 20:08:22 +00002248 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2249 if( pPk ){
2250 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2251 }else{
2252 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2253 }
dan0a746cc2021-04-18 05:30:39 +00002254 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002255
drh03361402021-02-18 23:53:47 +00002256 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002257 sqlite3VdbeJumpHere(v, addr);
2258 }
dan6e6d9832021-02-16 20:43:36 +00002259
2260exit_drop_column:
2261 sqlite3DbFree(db, zCol);
2262 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002263}
2264
2265/*
dancf8f2892018-08-09 20:47:01 +00002266** Register built-in functions used to help implement ALTER TABLE
2267*/
2268void sqlite3AlterFunctions(void){
2269 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002270 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2271 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002272 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002273 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002274 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002275 };
2276 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2277}
drhd0e4a6c2005-02-15 20:47:57 +00002278#endif /* SQLITE_ALTER_TABLE */