blob: 75220a1de38695ece6c645c3e1e0049a97995a79 [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 "
drh346a70c2020-06-15 20:27:35 +000063 "FROM \"%w\"." DFLT_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 "
drh346a70c2020-06-15 20:27:35 +000074 "FROM temp." DFLT_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,
92 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
93 " 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,
99 "UPDATE temp." DFLT_SCHEMA_TABLE
100 " 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() */
drh8257aa82017-07-26 19:59:13 +0000138 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000139
drh8257aa82017-07-26 19:59:13 +0000140 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000141 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000142 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000143 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000144
dan41fb5cd2012-10-04 19:33:00 +0000145 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000146 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000147 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000148 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000149 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000150
151 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000152 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000153 if( !zName ) goto exit_rename_table;
154
155 /* Check that a table or index named 'zName' does not already exist
156 ** in database iDb. If so, this is an error.
157 */
drh3d863b52020-05-14 21:16:52 +0000158 if( sqlite3FindTable(db, zName, zDb)
159 || sqlite3FindIndex(db, zName, zDb)
160 || sqlite3IsShadowTableOf(db, pTab, zName)
161 ){
drhd0e4a6c2005-02-15 20:47:57 +0000162 sqlite3ErrorMsg(pParse,
163 "there is already another table or index with this name: %s", zName);
164 goto exit_rename_table;
165 }
166
167 /* Make sure it is not a system table being altered, or a reserved name
168 ** that the table is being renamed to.
169 */
dan397a78d2018-12-18 20:31:14 +0000170 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000171 goto exit_rename_table;
172 }
drhc5a93d42019-08-12 00:08:07 +0000173 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
174 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000175 }
176
danielk197761116ae2007-12-13 08:15:30 +0000177#ifndef SQLITE_OMIT_VIEW
drhf38524d2021-08-02 16:41:57 +0000178 if( IsView(pTab) ){
danielk197761116ae2007-12-13 08:15:30 +0000179 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
180 goto exit_rename_table;
181 }
182#endif
183
drhd0e4a6c2005-02-15 20:47:57 +0000184#ifndef SQLITE_OMIT_AUTHORIZATION
185 /* Invoke the authorization callback. */
186 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
187 goto exit_rename_table;
188 }
189#endif
190
danielk1977182c4ba2007-06-27 15:53:34 +0000191#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000192 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
193 goto exit_rename_table;
194 }
danielk1977595a5232009-07-24 17:58:53 +0000195 if( IsVirtual(pTab) ){
196 pVTab = sqlite3GetVTable(db, pTab);
197 if( pVTab->pVtab->pModule->xRename==0 ){
198 pVTab = 0;
199 }
danielk1977182c4ba2007-06-27 15:53:34 +0000200 }
201#endif
202
dan1f3b2842019-03-15 16:17:32 +0000203 /* Begin a transaction for database iDb. Then modify the schema cookie
204 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
205 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
206 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000207 v = sqlite3GetVdbe(pParse);
208 if( v==0 ){
209 goto exit_rename_table;
210 }
dan1f3b2842019-03-15 16:17:32 +0000211 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000212
drh4e5dd852007-05-15 03:56:49 +0000213 /* figure out how many UTF-8 characters are in zName */
214 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000215 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000216
danc9461ec2018-08-29 21:00:16 +0000217 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
218 ** the schema to use the new table name. */
219 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000220 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan65372fa2018-09-03 20:05:15 +0000221 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000222 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000223 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
drh346a70c2020-06-15 20:27:35 +0000224 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000225 );
dan432cc5b2009-09-26 17:51:48 +0000226
drh1e32bed2020-06-19 13:33:53 +0000227 /* Update the tbl_name and name columns of the sqlite_schema table
danc9461ec2018-08-29 21:00:16 +0000228 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000229 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000230 "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
drhd0e4a6c2005-02-15 20:47:57 +0000231 "tbl_name = %Q, "
232 "name = CASE "
233 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000234 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
235 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000236 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000237 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000238 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000239 "(type='table' OR type='index' OR type='trigger');",
drh346a70c2020-06-15 20:27:35 +0000240 zDb,
danc9461ec2018-08-29 21:00:16 +0000241 zName, zName, zName,
242 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000243 );
244
245#ifndef SQLITE_OMIT_AUTOINCREMENT
246 /* If the sqlite_sequence table exists in this database, then update
247 ** it with the new table name.
248 */
249 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
250 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000251 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000252 zDb, zName, pTab->zName);
253 }
254#endif
255
danc9461ec2018-08-29 21:00:16 +0000256 /* If the table being renamed is not itself part of the temp database,
257 ** edit view and trigger definitions within the temp database
258 ** as required. */
259 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000260 sqlite3NestedParse(pParse,
drh1e32bed2020-06-19 13:33:53 +0000261 "UPDATE sqlite_temp_schema SET "
dan65372fa2018-09-03 20:05:15 +0000262 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000263 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000264 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
dan2ad080a2021-03-16 16:14:48 +0000265 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
dan1d85c6b2018-09-06 16:01:37 +0000266 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000267 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000268 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000269 }
drhd0e4a6c2005-02-15 20:47:57 +0000270
dan34566c42018-09-20 17:21:21 +0000271 /* If this is a virtual table, invoke the xRename() function if
272 ** one is defined. The xRename() callback will modify the names
273 ** of any resources used by the v-table implementation (including other
274 ** SQLite tables) that are identified by the name of the virtual table.
275 */
276#ifndef SQLITE_OMIT_VIRTUALTABLE
277 if( pVTab ){
278 int i = ++pParse->nMem;
279 sqlite3VdbeLoadString(v, i, zName);
280 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000281 }
282#endif
283
dan6a5a13d2021-02-17 20:08:22 +0000284 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000285 renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
dan9d324822018-08-30 20:03:44 +0000286
drhd0e4a6c2005-02-15 20:47:57 +0000287exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000288 sqlite3SrcListDelete(db, pSrc);
289 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000290 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000291}
danielk197719a8e7e2005-03-17 05:03:38 +0000292
drhd3001712009-05-12 17:46:53 +0000293/*
drh9e5fdc42020-05-08 19:02:21 +0000294** Write code that will raise an error if the table described by
295** zDb and zTab is not empty.
296*/
297static void sqlite3ErrorIfNotEmpty(
298 Parse *pParse, /* Parsing context */
299 const char *zDb, /* Schema holding the table */
300 const char *zTab, /* Table to check for empty */
301 const char *zErr /* Error message text */
302){
303 sqlite3NestedParse(pParse,
304 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
305 zErr, zDb, zTab
306 );
307}
308
309/*
danielk197719a8e7e2005-03-17 05:03:38 +0000310** This function is called after an "ALTER TABLE ... ADD" statement
311** has been parsed. Argument pColDef contains the text of the new
312** column definition.
313**
314** The Table structure pParse->pNewTable was extended to include
315** the new column during parsing.
316*/
317void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
318 Table *pNew; /* Copy of pParse->pNewTable */
319 Table *pTab; /* Table being altered */
320 int iDb; /* Database number */
321 const char *zDb; /* Database name */
322 const char *zTab; /* Table name */
323 char *zCol; /* Null-terminated column definition */
324 Column *pCol; /* The new column */
325 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000326 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000327 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000328 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000329
danielk1977f150c9d2008-10-30 17:21:12 +0000330 db = pParse->db;
331 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000332 pNew = pParse->pNewTable;
333 assert( pNew );
334
drh1fee73e2007-08-29 04:00:57 +0000335 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000336 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000337 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000338 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000339 pCol = &pNew->aCol[pNew->nCol-1];
drh79cf2b72021-07-31 20:30:41 +0000340 pDflt = sqlite3ColumnExpr(pNew, pCol);
drh17435752007-08-16 04:30:38 +0000341 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000342 assert( pTab );
343
drh81f2ccd2006-01-31 14:28:44 +0000344#ifndef SQLITE_OMIT_AUTHORIZATION
345 /* Invoke the authorization callback. */
346 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
347 return;
348 }
349#endif
350
danielk197719a8e7e2005-03-17 05:03:38 +0000351
352 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
353 ** If there is a NOT NULL constraint, then the default value for the
354 ** column must not be NULL.
355 */
drha371ace2012-09-13 14:22:47 +0000356 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000357 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
358 return;
359 }
360 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000361 sqlite3ErrorMsg(pParse,
362 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000363 return;
364 }
drhc27ea2a2019-10-16 20:05:56 +0000365 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
366 /* If the default value for the new column was specified with a
367 ** literal NULL, then set pDflt to 0. This simplifies checking
368 ** for an SQL NULL default below.
369 */
370 assert( pDflt==0 || pDflt->op==TK_SPAN );
371 if( pDflt && pDflt->pLeft->op==TK_NULL ){
372 pDflt = 0;
373 }
drhf38524d2021-08-02 16:41:57 +0000374 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000375 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000376 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000377 }
378 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000379 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000380 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000381 }
382
drh9e5fdc42020-05-08 19:02:21 +0000383
drhc27ea2a2019-10-16 20:05:56 +0000384 /* Ensure the default expression is something that sqlite3ValueFromExpr()
385 ** can handle (i.e. not CURRENT_TIME etc.)
386 */
387 if( pDflt ){
388 sqlite3_value *pVal = 0;
389 int rc;
390 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
391 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
392 if( rc!=SQLITE_OK ){
393 assert( db->mallocFailed == 1 );
394 return;
395 }
396 if( !pVal ){
drh9e5fdc42020-05-08 19:02:21 +0000397 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
398 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000399 }
400 sqlite3ValueFree(pVal);
401 }
drh035f6d92019-10-24 01:04:10 +0000402 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000403 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000404 }
405
danielk197719a8e7e2005-03-17 05:03:38 +0000406
407 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000408 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000409 if( zCol ){
410 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000411 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000412 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000413 *zEnd-- = '\0';
414 }
drh8257aa82017-07-26 19:59:13 +0000415 db->mDbFlags |= DBFLAG_PreferBuiltin;
drh37114fb2021-01-01 20:04:34 +0000416 /* substr() operations on characters, but addColOffset is in bytes. So we
417 ** have to use printf() to translate between these units: */
drhf38524d2021-08-02 16:41:57 +0000418 assert( !IsVirtual(pTab) );
danielk197719a8e7e2005-03-17 05:03:38 +0000419 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000420 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000421 "sql = printf('%%.%ds, ',sql) || %Q"
422 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000423 "WHERE type = 'table' AND name = %Q",
drhf38524d2021-08-02 16:41:57 +0000424 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000425 zTab
426 );
drh633e6d52008-07-28 19:34:53 +0000427 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000428 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000429 }
430
dan09236502018-09-01 16:05:50 +0000431 v = sqlite3GetVdbe(pParse);
432 if( v ){
drhb4d9b2b2021-07-20 07:35:07 +0000433 /* Make sure the schema version is at least 3. But do not upgrade
434 ** from less than 3 to 4, as that will corrupt any preexisting DESC
435 ** index.
436 */
dan09236502018-09-01 16:05:50 +0000437 r1 = sqlite3GetTempReg(pParse);
438 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
439 sqlite3VdbeUsesBtree(v, iDb);
440 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
441 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
442 VdbeCoverage(v);
443 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
444 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000445
drhb4d9b2b2021-07-20 07:35:07 +0000446 /* Reload the table definition */
447 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
448
449 /* Verify that constraints are still satisfied */
drh0f91a532021-07-20 08:23:54 +0000450 if( pNew->pCheck!=0
drhb4d9b2b2021-07-20 07:35:07 +0000451 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
452 ){
453 sqlite3NestedParse(pParse,
454 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
455 " THEN raise(ABORT,'CHECK constraint failed')"
drh0f91a532021-07-20 08:23:54 +0000456 " ELSE raise(ABORT,'NOT NULL constraint failed')"
drhb4d9b2b2021-07-20 07:35:07 +0000457 " END"
drh0f91a532021-07-20 08:23:54 +0000458 " FROM pragma_quick_check(\"%w\",\"%w\")"
459 " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
drhb4d9b2b2021-07-20 07:35:07 +0000460 zTab, zDb
461 );
462 }
463 }
danielk197719a8e7e2005-03-17 05:03:38 +0000464}
465
drhfdd6e852005-12-16 01:06:16 +0000466/*
danielk197719a8e7e2005-03-17 05:03:38 +0000467** This function is called by the parser after the table-name in
468** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
469** pSrc is the full-name of the table being altered.
470**
471** This routine makes a (partial) copy of the Table structure
472** for the table being altered and sets Parse.pNewTable to point
473** to it. Routines called by the parser as the column definition
474** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
475** the copy. The copy of the Table structure is deleted by tokenize.c
476** after parsing is finished.
477**
478** Routine sqlite3AlterFinishAddColumn() will be called to complete
479** coding the "ALTER TABLE ... ADD" statement.
480*/
481void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
482 Table *pNew;
483 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000484 int iDb;
485 int i;
486 int nAlloc;
drh17435752007-08-16 04:30:38 +0000487 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000488
489 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000490 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000491 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000492 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000493 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000494 if( !pTab ) goto exit_begin_add_column;
495
danielk19775ee9d692006-06-21 12:36:25 +0000496#ifndef SQLITE_OMIT_VIRTUALTABLE
497 if( IsVirtual(pTab) ){
498 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
499 goto exit_begin_add_column;
500 }
501#endif
502
danielk197719a8e7e2005-03-17 05:03:38 +0000503 /* Make sure this is not an attempt to ALTER a view. */
drhf38524d2021-08-02 16:41:57 +0000504 if( IsView(pTab) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000505 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
506 goto exit_begin_add_column;
507 }
dan397a78d2018-12-18 20:31:14 +0000508 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000509 goto exit_begin_add_column;
510 }
danielk197719a8e7e2005-03-17 05:03:38 +0000511
dan03e025e2019-10-07 18:43:21 +0000512 sqlite3MayAbort(pParse);
drhf38524d2021-08-02 16:41:57 +0000513 assert( pTab->u.tab.addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000514 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000515
516 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000517 ** sqlite3AddColumn() function and friends to modify. But modify
518 ** the name by adding an "sqlite_altertab_" prefix. By adding this
519 ** prefix, we insure that the name will not collide with an existing
520 ** table because user table are not allowed to have the "sqlite_"
521 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000522 */
drh17435752007-08-16 04:30:38 +0000523 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000524 if( !pNew ) goto exit_begin_add_column;
525 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000526 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000527 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000528 assert( pNew->nCol>0 );
529 nAlloc = (((pNew->nCol-1)/8)*8)+8;
530 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000531 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000532 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000533 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000534 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000535 goto exit_begin_add_column;
536 }
537 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
538 for(i=0; i<pNew->nCol; i++){
539 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000540 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000541 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000542 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000543 }
drhf38524d2021-08-02 16:41:57 +0000544 assert( !IsVirtual(pNew) );
545 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
drh17435752007-08-16 04:30:38 +0000546 pNew->pSchema = db->aDb[iDb].pSchema;
drhf38524d2021-08-02 16:41:57 +0000547 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
drh79df7782016-12-14 14:07:35 +0000548 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000549
danielk197719a8e7e2005-03-17 05:03:38 +0000550exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000551 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000552 return;
553}
dancf8f2892018-08-09 20:47:01 +0000554
drh4a2c7472018-08-13 15:09:48 +0000555/*
dan9d705572018-08-20 16:16:05 +0000556** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
557** command. This function checks if the table is a view or virtual
558** table (columns of views or virtual tables may not be renamed). If so,
559** it loads an error message into pParse and returns non-zero.
560**
561** Or, if pTab is not a view or virtual table, zero is returned.
562*/
563#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000564static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000565 const char *zType = 0;
566#ifndef SQLITE_OMIT_VIEW
drhf38524d2021-08-02 16:41:57 +0000567 if( IsView(pTab) ){
dan9d705572018-08-20 16:16:05 +0000568 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000569 }
dan9d705572018-08-20 16:16:05 +0000570#endif
571#ifndef SQLITE_OMIT_VIRTUALTABLE
572 if( IsVirtual(pTab) ){
573 zType = "virtual table";
574 }
575#endif
576 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000577 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
578 (bDrop ? "drop column from" : "rename columns of"),
579 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000580 );
581 return 1;
582 }
583 return 0;
584}
585#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000586# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000587#endif
588
589/*
drh4a2c7472018-08-13 15:09:48 +0000590** Handles the following parser reduction:
591**
592** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
593*/
dancf8f2892018-08-09 20:47:01 +0000594void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000595 Parse *pParse, /* Parsing context */
596 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
597 Token *pOld, /* Name of column being changed */
598 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000599){
drh4a2c7472018-08-13 15:09:48 +0000600 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000601 Table *pTab; /* Table being updated */
602 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000603 char *zOld = 0; /* Old column name */
604 char *zNew = 0; /* New column name */
605 const char *zDb; /* Name of schema containing the table */
606 int iSchema; /* Index of the schema */
607 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000608
drh4a2c7472018-08-13 15:09:48 +0000609 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000610 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
611 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000612
613 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000614 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000615 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000616
617 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000618 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
619 assert( iSchema>=0 );
620 zDb = db->aDb[iSchema].zDbSName;
621
drh0d019b92018-08-25 16:14:46 +0000622#ifndef SQLITE_OMIT_AUTHORIZATION
623 /* Invoke the authorization callback. */
624 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
625 goto exit_rename_column;
626 }
627#endif
628
drh4a2c7472018-08-13 15:09:48 +0000629 /* Make sure the old name really is a column name in the table to be
630 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000631 zOld = sqlite3NameFromToken(db, pOld);
632 if( !zOld ) goto exit_rename_column;
633 for(iCol=0; iCol<pTab->nCol; iCol++){
634 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
635 }
636 if( iCol==pTab->nCol ){
637 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
638 goto exit_rename_column;
639 }
640
dan2ad080a2021-03-16 16:14:48 +0000641 /* Ensure the schema contains no double-quoted strings */
642 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
643 renameFixQuotes(pParse, zDb, iSchema==1);
644
drh4a2c7472018-08-13 15:09:48 +0000645 /* Do the rename operation using a recursive UPDATE statement that
646 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000647 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000648 */
dan1f3b2842019-03-15 16:17:32 +0000649 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000650 zNew = sqlite3NameFromToken(db, pNew);
651 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000652 assert( pNew->n>0 );
653 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000654 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000655 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000656 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000657 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
658 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000659 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000660 zDb,
danb87a9a82018-09-01 20:23:28 +0000661 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000662 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000663 );
664
dan9d324822018-08-30 20:03:44 +0000665 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000666 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000667 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000668 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000669 zDb, pTab->zName, iCol, zNew, bQuote
670 );
671
dane325ffe2018-08-11 13:40:20 +0000672 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000673 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000674 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000675
dancf8f2892018-08-09 20:47:01 +0000676 exit_rename_column:
677 sqlite3SrcListDelete(db, pSrc);
678 sqlite3DbFree(db, zOld);
679 sqlite3DbFree(db, zNew);
680 return;
681}
682
drh4a2c7472018-08-13 15:09:48 +0000683/*
684** Each RenameToken object maps an element of the parse tree into
685** the token that generated that element. The parse tree element
686** might be one of:
687**
688** * A pointer to an Expr that represents an ID
689** * The name of a table column in Column.zName
690**
691** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000692** Each new object is created by sqlite3RenameTokenMap().
693** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000694** routine is used to keep the mapping current.
695**
696** After the parse finishes, renameTokenFind() routine can be used
697** to look up the actual token value that created some element in
698** the parse tree.
699*/
dancf8f2892018-08-09 20:47:01 +0000700struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000701 void *p; /* Parse tree element created by token t */
702 Token t; /* The token that created parse tree element p */
703 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000704};
705
drh4a2c7472018-08-13 15:09:48 +0000706/*
707** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
708** down into the Walker.
709*/
dan5496d6a2018-08-13 17:14:26 +0000710typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000711struct RenameCtx {
712 RenameToken *pList; /* List of tokens to overwrite */
713 int nList; /* Number of tokens in pList */
714 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000715 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000716 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000717};
718
dan8900a482018-09-05 14:36:05 +0000719#ifdef SQLITE_DEBUG
720/*
721** This function is only for debugging. It performs two tasks:
722**
723** 1. Checks that pointer pPtr does not already appear in the
724** rename-token list.
725**
726** 2. Dereferences each pointer in the rename-token list.
727**
728** The second is most effective when debugging under valgrind or
729** address-sanitizer or similar. If any of these pointers no longer
730** point to valid objects, an exception is raised by the memory-checking
731** tool.
732**
733** The point of this is to prevent comparisons of invalid pointer values.
734** Even though this always seems to work, it is undefined according to the
735** C standard. Example of undefined comparison:
736**
737** sqlite3_free(x);
738** if( x==y ) ...
739**
740** Technically, as x no longer points into a valid object or to the byte
741** following a valid object, it may not be used in comparison operations.
742*/
drh16b870d2018-09-12 15:51:56 +0000743static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000744 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
745 RenameToken *p;
746 u8 i = 0;
747 for(p=pParse->pRename; p; p=p->pNext){
748 if( p->p ){
749 assert( p->p!=pPtr );
750 i += *(u8*)(p->p);
751 }
danc9461ec2018-08-29 21:00:16 +0000752 }
753 }
754}
dan8900a482018-09-05 14:36:05 +0000755#else
756# define renameTokenCheckAll(x,y)
757#endif
danc9461ec2018-08-29 21:00:16 +0000758
drh4a2c7472018-08-13 15:09:48 +0000759/*
drh49b269e2018-11-26 15:00:25 +0000760** Remember that the parser tree element pPtr was created using
761** the token pToken.
dan07e95232018-08-21 16:32:53 +0000762**
drh49b269e2018-11-26 15:00:25 +0000763** In other words, construct a new RenameToken object and add it
764** to the list of RenameToken objects currently being built up
765** in pParse->pRename.
766**
767** The pPtr argument is returned so that this routine can be used
768** with tail recursion in tokenExpr() routine, for a small performance
769** improvement.
drh4a2c7472018-08-13 15:09:48 +0000770*/
dan07e95232018-08-21 16:32:53 +0000771void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000772 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000773 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000774 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000775 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000776 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
777 if( pNew ){
778 pNew->p = pPtr;
779 pNew->t = *pToken;
780 pNew->pNext = pParse->pRename;
781 pParse->pRename = pNew;
782 }
dancf8f2892018-08-09 20:47:01 +0000783 }
danc9461ec2018-08-29 21:00:16 +0000784
dand145e5f2018-08-21 08:29:48 +0000785 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000786}
787
drh4a2c7472018-08-13 15:09:48 +0000788/*
dan07e95232018-08-21 16:32:53 +0000789** It is assumed that there is already a RenameToken object associated
790** with parse tree element pFrom. This function remaps the associated token
791** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000792*/
dan07e95232018-08-21 16:32:53 +0000793void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000794 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000795 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000796 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000797 if( p->p==pFrom ){
798 p->p = pTo;
799 break;
800 }
801 }
dancf8f2892018-08-09 20:47:01 +0000802}
803
drh4a2c7472018-08-13 15:09:48 +0000804/*
dan8900a482018-09-05 14:36:05 +0000805** Walker callback used by sqlite3RenameExprUnmap().
806*/
807static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
808 Parse *pParse = pWalker->pParse;
809 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
810 return WRC_Continue;
811}
812
813/*
dan8f407622019-12-04 14:26:38 +0000814** Iterate through the Select objects that are part of WITH clauses attached
815** to select statement pSelect.
816*/
817static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000818 With *pWith = pSelect->pWith;
819 if( pWith ){
dan26d61e52021-06-11 11:14:24 +0000820 Parse *pParse = pWalker->pParse;
dan8f407622019-12-04 14:26:38 +0000821 int i;
drh35e6cd02021-06-11 13:18:56 +0000822 With *pCopy = 0;
dan26d61e52021-06-11 11:14:24 +0000823 assert( pWith->nCte>0 );
drh35e6cd02021-06-11 13:18:56 +0000824 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
825 /* Push a copy of the With object onto the with-stack. We use a copy
826 ** here as the original will be expanded and resolved (flags SF_Expanded
827 ** and SF_Resolved) below. And the parser code that uses the with-stack
828 ** fails if the Select objects on it have already been expanded and
829 ** resolved. */
830 pCopy = sqlite3WithDup(pParse->db, pWith);
drh24ce9442021-06-12 17:45:32 +0000831 pCopy = sqlite3WithPush(pParse, pCopy, 1);
drh35e6cd02021-06-11 13:18:56 +0000832 }
833 for(i=0; i<pWith->nCte; i++){
834 Select *p = pWith->a[i].pSelect;
835 NameContext sNC;
836 memset(&sNC, 0, sizeof(sNC));
837 sNC.pParse = pParse;
838 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
839 sqlite3WalkSelect(pWalker, p);
840 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
841 }
842 if( pCopy && pParse->pWith==pCopy ){
dand03d3a92021-06-11 12:14:58 +0000843 pParse->pWith = pCopy->pOuter;
dan26d61e52021-06-11 11:14:24 +0000844 }
dan8f407622019-12-04 14:26:38 +0000845 }
846}
847
848/*
danfb99e382020-04-03 11:20:40 +0000849** Unmap all tokens in the IdList object passed as the second argument.
850*/
851static void unmapColumnIdlistNames(
852 Parse *pParse,
853 IdList *pIdList
854){
855 if( pIdList ){
856 int ii;
857 for(ii=0; ii<pIdList->nId; ii++){
858 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
859 }
860 }
861}
862
863/*
dan0b277a92019-06-11 12:03:10 +0000864** Walker callback used by sqlite3RenameExprUnmap().
865*/
866static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000867 Parse *pParse = pWalker->pParse;
868 int i;
drhd63b69b2019-12-04 15:08:58 +0000869 if( pParse->nErr ) return WRC_Abort;
danac67f562021-06-14 20:08:48 +0000870 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000871 testcase( p->selFlags & SF_View );
872 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000873 return WRC_Prune;
874 }
drhbdf4cf02019-06-15 15:21:49 +0000875 if( ALWAYS(p->pEList) ){
876 ExprList *pList = p->pEList;
877 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000878 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000879 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000880 }
881 }
882 }
drh2c3f4652019-06-11 16:43:58 +0000883 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000884 SrcList *pSrc = p->pSrc;
885 for(i=0; i<pSrc->nSrc; i++){
886 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000887 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000888 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000889 }
890 }
dan8f407622019-12-04 14:26:38 +0000891
892 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000893 return WRC_Continue;
894}
895
896/*
dan8900a482018-09-05 14:36:05 +0000897** Remove all nodes that are part of expression pExpr from the rename list.
898*/
899void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000900 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000901 Walker sWalker;
902 memset(&sWalker, 0, sizeof(Walker));
903 sWalker.pParse = pParse;
904 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000905 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000906 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000907 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000908 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000909}
910
911/*
dane8ab40d2018-09-12 08:51:48 +0000912** Remove all nodes that are part of expression-list pEList from the
913** rename list.
914*/
915void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
916 if( pEList ){
917 int i;
918 Walker sWalker;
919 memset(&sWalker, 0, sizeof(Walker));
920 sWalker.pParse = pParse;
921 sWalker.xExprCallback = renameUnmapExprCb;
922 sqlite3WalkExprList(&sWalker, pEList);
923 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000924 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000925 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
926 }
dane8ab40d2018-09-12 08:51:48 +0000927 }
928 }
929}
930
931/*
drh4a2c7472018-08-13 15:09:48 +0000932** Free the list of RenameToken objects given in the second argument
933*/
dancf8f2892018-08-09 20:47:01 +0000934static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
935 RenameToken *pNext;
936 RenameToken *p;
937 for(p=pToken; p; p=pNext){
938 pNext = p->pNext;
939 sqlite3DbFree(db, p);
940 }
941}
942
dan987db762018-08-14 20:18:50 +0000943/*
944** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000945** object associated with parse tree element pPtr. If found, return a pointer
946** to it. Otherwise, return NULL.
947**
948** If the second argument passed to this function is not NULL and a matching
949** RenameToken object is found, remove it from the Parse object and add it to
950** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000951*/
dan6e6d9832021-02-16 20:43:36 +0000952static RenameToken *renameTokenFind(
953 Parse *pParse,
954 struct RenameCtx *pCtx,
955 void *pPtr
956){
dancf8f2892018-08-09 20:47:01 +0000957 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000958 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000959 return 0;
960 }
dancf8f2892018-08-09 20:47:01 +0000961 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
962 if( (*pp)->p==pPtr ){
963 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000964 if( pCtx ){
965 *pp = pToken->pNext;
966 pToken->pNext = pCtx->pList;
967 pCtx->pList = pToken;
968 pCtx->nList++;
969 }
970 return pToken;
dancf8f2892018-08-09 20:47:01 +0000971 }
972 }
dan6e6d9832021-02-16 20:43:36 +0000973 return 0;
dancf8f2892018-08-09 20:47:01 +0000974}
975
dan24fedb92018-08-18 17:35:38 +0000976/*
977** This is a Walker select callback. It does nothing. It is only required
978** because without a dummy callback, sqlite3WalkExpr() and similar do not
979** descend into sub-select statements.
980*/
dan987db762018-08-14 20:18:50 +0000981static int renameColumnSelectCb(Walker *pWalker, Select *p){
danac67f562021-06-14 20:08:48 +0000982 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000983 testcase( p->selFlags & SF_View );
984 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000985 return WRC_Prune;
986 }
danea412512018-12-05 13:49:04 +0000987 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000988 return WRC_Continue;
989}
990
dan987db762018-08-14 20:18:50 +0000991/*
992** This is a Walker expression callback.
993**
994** For every TK_COLUMN node in the expression tree, search to see
995** if the column being references is the column being renamed by an
996** ALTER TABLE statement. If it is, then attach its associated
997** RenameToken object to the list of RenameToken objects being
998** constructed in RenameCtx object at pWalker->u.pRename.
999*/
dancf8f2892018-08-09 20:47:01 +00001000static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +00001001 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +00001002 if( pExpr->op==TK_TRIGGER
1003 && pExpr->iColumn==p->iCol
1004 && pWalker->pParse->pTriggerTab==p->pTab
1005 ){
dan5be60c52018-08-15 20:28:39 +00001006 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +00001007 }else if( pExpr->op==TK_COLUMN
1008 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +00001009 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +00001010 ){
dan5496d6a2018-08-13 17:14:26 +00001011 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +00001012 }
1013 return WRC_Continue;
1014}
1015
dan987db762018-08-14 20:18:50 +00001016/*
1017** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001018** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001019** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001020** RenameContext. "Last" means the last RenameToken encountered when
1021** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001022** return all column name tokens in the order that they are encountered
1023** in the SQL statement.
1024*/
dan5496d6a2018-08-13 17:14:26 +00001025static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001026 RenameToken *pBest = pCtx->pList;
1027 RenameToken *pToken;
1028 RenameToken **pp;
1029
1030 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1031 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1032 }
1033 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1034 *pp = pBest->pNext;
1035
1036 return pBest;
1037}
1038
dan6fe7f232018-08-10 19:19:33 +00001039/*
dan24fedb92018-08-18 17:35:38 +00001040** An error occured while parsing or otherwise processing a database
1041** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1042** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1043** sub-routine is currently stored in pParse->zErrMsg. This function
1044** adds context to the error message and then stores it in pCtx.
1045*/
danb0137382018-08-20 20:01:01 +00001046static void renameColumnParseError(
1047 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001048 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001049 sqlite3_value *pType,
1050 sqlite3_value *pObject,
1051 Parse *pParse
1052){
drh79a5ee92018-08-23 19:32:04 +00001053 const char *zT = (const char*)sqlite3_value_text(pType);
1054 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001055 char *zErr;
danb0137382018-08-20 20:01:01 +00001056
dan16953462021-02-18 19:25:44 +00001057 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1058 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001059 pParse->zErrMsg
1060 );
dan24fedb92018-08-18 17:35:38 +00001061 sqlite3_result_error(pCtx, zErr, -1);
1062 sqlite3_free(zErr);
1063}
1064
1065/*
dan06249392018-08-21 15:06:59 +00001066** For each name in the the expression-list pEList (i.e. each
1067** pEList->a[i].zName) that matches the string in zOld, extract the
1068** corresponding rename-token from Parse object pParse and add it
1069** to the RenameCtx pCtx.
1070*/
1071static void renameColumnElistNames(
1072 Parse *pParse,
1073 RenameCtx *pCtx,
1074 ExprList *pEList,
1075 const char *zOld
1076){
1077 if( pEList ){
1078 int i;
1079 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001080 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001081 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1082 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001083 && 0==sqlite3_stricmp(zName, zOld)
1084 ){
dan06249392018-08-21 15:06:59 +00001085 renameTokenFind(pParse, pCtx, (void*)zName);
1086 }
1087 }
1088 }
1089}
1090
1091/*
1092** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1093** that matches the string in zOld, extract the corresponding rename-token
1094** from Parse object pParse and add it to the RenameCtx pCtx.
1095*/
1096static void renameColumnIdlistNames(
1097 Parse *pParse,
1098 RenameCtx *pCtx,
1099 IdList *pIdList,
1100 const char *zOld
1101){
1102 if( pIdList ){
1103 int i;
1104 for(i=0; i<pIdList->nId; i++){
1105 char *zName = pIdList->a[i].zName;
1106 if( 0==sqlite3_stricmp(zName, zOld) ){
1107 renameTokenFind(pParse, pCtx, (void*)zName);
1108 }
1109 }
1110 }
1111}
1112
danfb99e382020-04-03 11:20:40 +00001113
dandd1a9c82018-09-05 08:28:30 +00001114/*
1115** Parse the SQL statement zSql using Parse object (*p). The Parse object
1116** is initialized by this function before it is used.
1117*/
danc9461ec2018-08-29 21:00:16 +00001118static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001119 Parse *p, /* Memory to use for Parse object */
1120 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001121 sqlite3 *db, /* Database handle */
1122 const char *zSql, /* SQL to parse */
1123 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001124){
1125 int rc;
1126 char *zErr = 0;
1127
1128 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1129
1130 /* Parse the SQL statement passed as the first argument. If no error
1131 ** occurs and the parse does not result in a new table, index or
1132 ** trigger object, the database must be corrupt. */
1133 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001134 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001135 p->db = db;
1136 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001137 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001138 assert( p->zErrMsg==0 );
1139 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001140 p->zErrMsg = zErr;
1141 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1142 if( rc==SQLITE_OK
1143 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1144 ){
1145 rc = SQLITE_CORRUPT_BKPT;
1146 }
1147
1148#ifdef SQLITE_DEBUG
1149 /* Ensure that all mappings in the Parse.pRename list really do map to
1150 ** a part of the input string. */
1151 if( rc==SQLITE_OK ){
1152 int nSql = sqlite3Strlen30(zSql);
1153 RenameToken *pToken;
1154 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1155 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1156 }
1157 }
1158#endif
1159
1160 db->init.iDb = 0;
1161 return rc;
1162}
1163
dandd1a9c82018-09-05 08:28:30 +00001164/*
1165** This function edits SQL statement zSql, replacing each token identified
1166** by the linked list pRename with the text of zNew. If argument bQuote is
1167** true, then zNew is always quoted first. If no error occurs, the result
1168** is loaded into context object pCtx as the result.
1169**
1170** Or, if an error occurs (i.e. an OOM condition), an error is left in
1171** pCtx and an SQLite error code returned.
1172*/
danc9461ec2018-08-29 21:00:16 +00001173static int renameEditSql(
1174 sqlite3_context *pCtx, /* Return result here */
1175 RenameCtx *pRename, /* Rename context */
1176 const char *zSql, /* SQL statement to edit */
1177 const char *zNew, /* New token text */
1178 int bQuote /* True to always quote token */
1179){
drh236bcdf2021-06-16 11:32:54 +00001180 i64 nNew = sqlite3Strlen30(zNew);
1181 i64 nSql = sqlite3Strlen30(zSql);
danc9461ec2018-08-29 21:00:16 +00001182 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1183 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001184 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001185 char *zOut;
drh236bcdf2021-06-16 11:32:54 +00001186 i64 nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001187 char *zBuf1 = 0;
1188 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001189
dan1e240722021-03-15 20:22:34 +00001190 if( zNew ){
1191 /* Set zQuot to point to a buffer containing a quoted copy of the
1192 ** identifier zNew. If the corresponding identifier in the original
1193 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1194 ** point to zQuot so that all substitutions are made using the
1195 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001196 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001197 if( zQuot==0 ){
1198 return SQLITE_NOMEM;
1199 }else{
dan1d14ffe2021-03-23 22:15:34 +00001200 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001201 }
1202
1203 assert( nQuot>=nNew );
1204 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001205 }else{
dan1e240722021-03-15 20:22:34 +00001206 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1207 if( zOut ){
1208 zBuf1 = &zOut[nSql*2+1];
1209 zBuf2 = &zOut[nSql*4+2];
1210 }
danc9461ec2018-08-29 21:00:16 +00001211 }
1212
1213 /* At this point pRename->pList contains a list of RenameToken objects
1214 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001215 ** with the new column name, or with single-quoted versions of themselves.
1216 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001217 if( zOut ){
1218 int nOut = nSql;
1219 memcpy(zOut, zSql, nSql);
1220 while( pRename->pList ){
1221 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001222 u32 nReplace;
1223 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001224 RenameToken *pBest = renameColumnTokenNext(pRename);
1225
1226 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001227 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001228 nReplace = nNew;
1229 zReplace = zNew;
1230 }else{
1231 nReplace = nQuot;
1232 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001233 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001234 }
danc9461ec2018-08-29 21:00:16 +00001235 }else{
dan1e240722021-03-15 20:22:34 +00001236 /* Dequote the double-quoted token. Then requote it again, this time
1237 ** using single quotes. If the character immediately following the
1238 ** original token within the input SQL was a single quote ('), then
1239 ** add another space after the new, single-quoted version of the
1240 ** token. This is so that (SELECT "string"'alias') maps to
1241 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1242 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1243 zBuf1[pBest->t.n] = 0;
1244 sqlite3Dequote(zBuf1);
1245 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1246 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1247 );
1248 zReplace = zBuf2;
1249 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001250 }
1251
1252 iOff = pBest->t.z - zSql;
1253 if( pBest->t.n!=nReplace ){
1254 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1255 nOut - (iOff + pBest->t.n)
1256 );
1257 nOut += nReplace - pBest->t.n;
1258 zOut[nOut] = '\0';
1259 }
1260 memcpy(&zOut[iOff], zReplace, nReplace);
1261 sqlite3DbFree(db, pBest);
1262 }
1263
1264 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1265 sqlite3DbFree(db, zOut);
1266 }else{
1267 rc = SQLITE_NOMEM;
1268 }
1269
1270 sqlite3_free(zQuot);
1271 return rc;
1272}
1273
dandd1a9c82018-09-05 08:28:30 +00001274/*
1275** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1276** it was read from the schema of database zDb. Return SQLITE_OK if
1277** successful. Otherwise, return an SQLite error code and leave an error
1278** message in the Parse object.
1279*/
drha7c74002020-07-18 18:44:59 +00001280static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001281 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001282 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001283 TriggerStep *pStep;
1284 NameContext sNC;
1285 int rc = SQLITE_OK;
1286
1287 memset(&sNC, 0, sizeof(sNC));
1288 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001289 assert( pNew->pTabSchema );
1290 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1291 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1292 );
1293 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001294 /* ALWAYS() because if the table of the trigger does not exist, the
1295 ** error would have been hit before this point */
1296 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001297 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1298 }
danc9461ec2018-08-29 21:00:16 +00001299
1300 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001301 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001302 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001303 }
1304
dand5e6fef2018-09-07 15:50:31 +00001305 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001306 if( pStep->pSelect ){
1307 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1308 if( pParse->nErr ) rc = pParse->rc;
1309 }
dand5e6fef2018-09-07 15:50:31 +00001310 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001311 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1312 if( pSrc ){
1313 int i;
drha3e64952020-08-12 16:19:12 +00001314 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001315 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001316 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001317 if( p->pSelect ){
1318 sqlite3SelectPrep(pParse, p->pSelect, 0);
1319 sqlite3ExpandSubquery(pParse, p);
1320 assert( i>0 );
1321 assert( pStep->pFrom->a[i-1].pSelect );
1322 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001323 }else{
dan7a39fae2020-10-31 16:33:01 +00001324 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1325 if( p->pTab==0 ){
1326 rc = SQLITE_ERROR;
1327 }else{
1328 p->pTab->nTabRef++;
1329 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1330 }
dane7877b22020-07-14 19:51:01 +00001331 }
1332 }
1333 sNC.pSrcList = pSrc;
1334 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001335 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1336 }
1337 if( rc==SQLITE_OK ){
1338 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1339 }
1340 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001341 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001342 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001343 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001344 sNC.uNC.pUpsert = pUpsert;
1345 sNC.ncFlags = NC_UUpsert;
1346 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1347 if( rc==SQLITE_OK ){
1348 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1349 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1350 }
1351 if( rc==SQLITE_OK ){
1352 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1353 }
1354 if( rc==SQLITE_OK ){
1355 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1356 }
1357 sNC.ncFlags = 0;
1358 }
dan0e14e982019-01-18 16:06:18 +00001359 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001360 sqlite3SrcListDelete(db, pSrc);
1361 }else{
1362 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001363 }
1364 }
1365 }
1366 return rc;
1367}
1368
dandd1a9c82018-09-05 08:28:30 +00001369/*
1370** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1371** objects that are part of the trigger passed as the second argument.
1372*/
danc9461ec2018-08-29 21:00:16 +00001373static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1374 TriggerStep *pStep;
1375
1376 /* Find tokens to edit in WHEN clause */
1377 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1378
1379 /* Find tokens to edit in trigger steps */
1380 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1381 sqlite3WalkSelect(pWalker, pStep->pSelect);
1382 sqlite3WalkExpr(pWalker, pStep->pWhere);
1383 sqlite3WalkExprList(pWalker, pStep->pExprList);
1384 if( pStep->pUpsert ){
1385 Upsert *pUpsert = pStep->pUpsert;
1386 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1387 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1388 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1389 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1390 }
dan7a39fae2020-10-31 16:33:01 +00001391 if( pStep->pFrom ){
1392 int i;
1393 for(i=0; i<pStep->pFrom->nSrc; i++){
1394 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1395 }
1396 }
danc9461ec2018-08-29 21:00:16 +00001397 }
1398}
1399
dandd1a9c82018-09-05 08:28:30 +00001400/*
1401** Free the contents of Parse object (*pParse). Do not free the memory
1402** occupied by the Parse object itself.
1403*/
dan141e1192018-08-31 18:23:53 +00001404static void renameParseCleanup(Parse *pParse){
1405 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001406 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001407 if( pParse->pVdbe ){
1408 sqlite3VdbeFinalize(pParse->pVdbe);
1409 }
1410 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001411 while( (pIdx = pParse->pNewIndex)!=0 ){
1412 pParse->pNewIndex = pIdx->pNext;
1413 sqlite3FreeIndex(db, pIdx);
1414 }
dan141e1192018-08-31 18:23:53 +00001415 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1416 sqlite3DbFree(db, pParse->zErrMsg);
1417 renameTokenFree(db, pParse->pRename);
1418 sqlite3ParserReset(pParse);
1419}
1420
dan06249392018-08-21 15:06:59 +00001421/*
dan987db762018-08-14 20:18:50 +00001422** SQL function:
1423**
1424** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1425**
1426** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001427** 1. type: Type of object ("table", "view" etc.)
1428** 2. object: Name of object
1429** 3. Database: Database name (e.g. "main")
1430** 4. Table: Table name
1431** 5. iCol: Index of column to rename
1432** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001433** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001434** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001435**
1436** Do a column rename operation on the CREATE statement given in zSql.
1437** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1438** into zNew. The name should be quoted if bQuote is true.
1439**
1440** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001441** It is only accessible to SQL created using sqlite3NestedParse(). It is
1442** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001443*/
dancf8f2892018-08-09 20:47:01 +00001444static void renameColumnFunc(
1445 sqlite3_context *context,
1446 int NotUsed,
1447 sqlite3_value **argv
1448){
1449 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001450 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001451 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001452 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1453 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1454 int iCol = sqlite3_value_int(argv[5]);
1455 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001456 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001457 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001458 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001459 int rc;
dancf8f2892018-08-09 20:47:01 +00001460 Parse sParse;
1461 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001462 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001463 int i;
dan987db762018-08-14 20:18:50 +00001464 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001465#ifndef SQLITE_OMIT_AUTHORIZATION
1466 sqlite3_xauth xAuth = db->xAuth;
1467#endif
dancf8f2892018-08-09 20:47:01 +00001468
drh38d99642018-08-18 18:27:18 +00001469 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001470 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001471 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001472 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001473 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001474 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001475 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001476 if( pTab==0 || iCol>=pTab->nCol ){
1477 sqlite3BtreeLeaveAll(db);
1478 return;
1479 }
dan987db762018-08-14 20:18:50 +00001480 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001481 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001482 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001483
dan141e1192018-08-31 18:23:53 +00001484#ifndef SQLITE_OMIT_AUTHORIZATION
1485 db->xAuth = 0;
1486#endif
drhb2ab3dc2019-12-20 14:08:34 +00001487 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001488
dancf8f2892018-08-09 20:47:01 +00001489 /* Find tokens that need to be replaced. */
1490 memset(&sWalker, 0, sizeof(Walker));
1491 sWalker.pParse = &sParse;
1492 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001493 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001494 sWalker.u.pRename = &sCtx;
1495
dan0cbb0b12018-08-16 19:49:16 +00001496 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001497 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001498 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001499 if( IsView(sParse.pNewTable) ){
1500 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan38096962019-12-09 08:13:43 +00001501 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001502 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001503 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001504 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1505 if( rc==SQLITE_OK ){
1506 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001507 }
dan987db762018-08-14 20:18:50 +00001508 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
drhf38524d2021-08-02 16:41:57 +00001509 }else if( IsOrdinaryTable(sParse.pNewTable) ){
dan987db762018-08-14 20:18:50 +00001510 /* A regular table */
1511 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1512 FKey *pFKey;
dan0cbb0b12018-08-16 19:49:16 +00001513 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001514 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001515 if( iCol<sParse.pNewTable->nCol ){
1516 renameTokenFind(
1517 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1518 );
1519 }
dan987db762018-08-14 20:18:50 +00001520 if( sCtx.iCol<0 ){
1521 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001522 }
dan987db762018-08-14 20:18:50 +00001523 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1524 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1525 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1526 }
drh885eeb62019-01-09 02:02:24 +00001527 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1528 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1529 }
drhb9bcf7c2019-10-19 13:29:10 +00001530#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001531 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001532 Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable,
1533 &sParse.pNewTable->aCol[i]);
1534 sqlite3WalkExpr(&sWalker, pExpr);
dan776a5782021-03-16 11:11:07 +00001535 }
drhb9bcf7c2019-10-19 13:29:10 +00001536#endif
dan776a5782021-03-16 11:11:07 +00001537 }
dan987db762018-08-14 20:18:50 +00001538
drhf38524d2021-08-02 16:41:57 +00001539 assert( !IsVirtual(sParse.pNewTable) );
1540 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan987db762018-08-14 20:18:50 +00001541 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001542 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001543 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1544 }
1545 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1546 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1547 ){
1548 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1549 }
dan6fe7f232018-08-10 19:19:33 +00001550 }
dancf8f2892018-08-09 20:47:01 +00001551 }
1552 }
dan5496d6a2018-08-13 17:14:26 +00001553 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001554 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1555 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001556 }else{
dan5be60c52018-08-15 20:28:39 +00001557 /* A trigger */
1558 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001559 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001560 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001561
danc9461ec2018-08-29 21:00:16 +00001562 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1563 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001564 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001565 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001566 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001567 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1568 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001569 }
danc9461ec2018-08-29 21:00:16 +00001570 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1571 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001572 }
1573 }
1574 }
1575
dan5be60c52018-08-15 20:28:39 +00001576
1577 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001578 if( sParse.pTriggerTab==pTab ){
1579 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001580 }
dan5be60c52018-08-15 20:28:39 +00001581
danc9461ec2018-08-29 21:00:16 +00001582 /* Find tokens to edit in various expressions and selects */
1583 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001584 }
1585
dan987db762018-08-14 20:18:50 +00001586 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001587 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001588
drh5fc22cd2018-08-13 13:43:11 +00001589renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001590 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001591 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001592 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001593 }else{
1594 sqlite3_result_error_code(context, rc);
1595 }
1596 }
1597
dan141e1192018-08-31 18:23:53 +00001598 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001599 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001600#ifndef SQLITE_OMIT_AUTHORIZATION
1601 db->xAuth = xAuth;
1602#endif
drhda76adc2018-08-25 02:04:05 +00001603 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001604}
1605
dandd1a9c82018-09-05 08:28:30 +00001606/*
1607** Walker expression callback used by "RENAME TABLE".
1608*/
danc9461ec2018-08-29 21:00:16 +00001609static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1610 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001611 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1612 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001613 }
1614 return WRC_Continue;
1615}
1616
1617/*
dandd1a9c82018-09-05 08:28:30 +00001618** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001619*/
1620static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1621 int i;
1622 RenameCtx *p = pWalker->u.pRename;
1623 SrcList *pSrc = pSelect->pSrc;
danac67f562021-06-14 20:08:48 +00001624 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1625 testcase( pSelect->selFlags & SF_View );
1626 testcase( pSelect->selFlags & SF_CopyCte );
1627 return WRC_Prune;
1628 }
drh9da977f2021-04-20 12:14:12 +00001629 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001630 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001631 return WRC_Abort;
1632 }
danc9461ec2018-08-29 21:00:16 +00001633 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001634 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001635 if( pItem->pTab==p->pTab ){
1636 renameTokenFind(pWalker->pParse, p, pItem->zName);
1637 }
1638 }
danea412512018-12-05 13:49:04 +00001639 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001640
1641 return WRC_Continue;
1642}
1643
1644
1645/*
1646** This C function implements an SQL user function that is used by SQL code
1647** generated by the ALTER TABLE ... RENAME command to modify the definition
1648** of any foreign key constraints that use the table being renamed as the
1649** parent table. It is passed three arguments:
1650**
dan141e1192018-08-31 18:23:53 +00001651** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001652** 1. type: Type of object ("table", "view" etc.)
1653** 2. object: Name of object
1654** 3: The complete text of the schema statement being modified,
1655** 4: The old name of the table being renamed, and
1656** 5: The new name of the table being renamed.
1657** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001658**
dan141e1192018-08-31 18:23:53 +00001659** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001660**
dan141e1192018-08-31 18:23:53 +00001661** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001662** -> 'CREATE TABLE t1(a REFERENCES t3)'
1663*/
1664static void renameTableFunc(
1665 sqlite3_context *context,
1666 int NotUsed,
1667 sqlite3_value **argv
1668){
1669 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001670 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001671 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1672 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1673 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1674 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001675 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001676
dan141e1192018-08-31 18:23:53 +00001677 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001678 Parse sParse;
1679 int rc;
1680 int bQuote = 1;
1681 RenameCtx sCtx;
1682 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001683
dan141e1192018-08-31 18:23:53 +00001684#ifndef SQLITE_OMIT_AUTHORIZATION
1685 sqlite3_xauth xAuth = db->xAuth;
1686 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001687#endif
1688
dan141e1192018-08-31 18:23:53 +00001689 sqlite3BtreeEnterAll(db);
1690
1691 memset(&sCtx, 0, sizeof(RenameCtx));
1692 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1693 memset(&sWalker, 0, sizeof(Walker));
1694 sWalker.pParse = &sParse;
1695 sWalker.xExprCallback = renameTableExprCb;
1696 sWalker.xSelectCallback = renameTableSelectCb;
1697 sWalker.u.pRename = &sCtx;
1698
drhb2ab3dc2019-12-20 14:08:34 +00001699 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001700
1701 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001702 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001703 if( sParse.pNewTable ){
1704 Table *pTab = sParse.pNewTable;
1705
drhf38524d2021-08-02 16:41:57 +00001706 if( IsView(pTab) ){
dan674b8942018-09-20 08:28:01 +00001707 if( isLegacy==0 ){
drhf38524d2021-08-02 16:41:57 +00001708 Select *pSelect = pTab->u.view.pSelect;
dan674b8942018-09-20 08:28:01 +00001709 NameContext sNC;
1710 memset(&sNC, 0, sizeof(sNC));
1711 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001712
dan38096962019-12-09 08:13:43 +00001713 assert( pSelect->selFlags & SF_View );
1714 pSelect->selFlags &= ~SF_View;
drhf38524d2021-08-02 16:41:57 +00001715 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001716 if( sParse.nErr ){
1717 rc = sParse.rc;
1718 }else{
drhf38524d2021-08-02 16:41:57 +00001719 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
drh1548d522019-12-20 12:55:21 +00001720 }
dan674b8942018-09-20 08:28:01 +00001721 }
dan141e1192018-08-31 18:23:53 +00001722 }else{
1723 /* Modify any FK definitions to point to the new table. */
1724#ifndef SQLITE_OMIT_FOREIGN_KEY
drhf38524d2021-08-02 16:41:57 +00001725 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
1726 && !IsVirtual(pTab)
1727 ){
dan202a0272018-09-07 11:51:21 +00001728 FKey *pFKey;
drhf38524d2021-08-02 16:41:57 +00001729 assert( !IsVirtual(pTab) );
1730 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
dan202a0272018-09-07 11:51:21 +00001731 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1732 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1733 }
dan141e1192018-08-31 18:23:53 +00001734 }
1735 }
1736#endif
1737
1738 /* If this is the table being altered, fix any table refs in CHECK
1739 ** expressions. Also update the name that appears right after the
1740 ** "CREATE [VIRTUAL] TABLE" bit. */
1741 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1742 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001743 if( isLegacy==0 ){
1744 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1745 }
dan141e1192018-08-31 18:23:53 +00001746 renameTokenFind(&sParse, &sCtx, pTab->zName);
1747 }
danc9461ec2018-08-29 21:00:16 +00001748 }
1749 }
danc9461ec2018-08-29 21:00:16 +00001750
dan141e1192018-08-31 18:23:53 +00001751 else if( sParse.pNewIndex ){
1752 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001753 if( isLegacy==0 ){
1754 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1755 }
dan141e1192018-08-31 18:23:53 +00001756 }
danc9461ec2018-08-29 21:00:16 +00001757
1758#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001759 else{
dan141e1192018-08-31 18:23:53 +00001760 Trigger *pTrigger = sParse.pNewTrigger;
1761 TriggerStep *pStep;
1762 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1763 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1764 ){
1765 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1766 }
danc9461ec2018-08-29 21:00:16 +00001767
dan674b8942018-09-20 08:28:01 +00001768 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001769 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001770 if( rc==SQLITE_OK ){
1771 renameWalkTrigger(&sWalker, pTrigger);
1772 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1773 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1774 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1775 }
dan141e1192018-08-31 18:23:53 +00001776 }
dan0ccda962018-08-30 16:26:48 +00001777 }
danc9461ec2018-08-29 21:00:16 +00001778 }
1779 }
dan141e1192018-08-31 18:23:53 +00001780#endif
danc9461ec2018-08-29 21:00:16 +00001781 }
dan141e1192018-08-31 18:23:53 +00001782
1783 if( rc==SQLITE_OK ){
1784 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1785 }
1786 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001787 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001788 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001789 }else{
1790 sqlite3_result_error_code(context, rc);
1791 }
dan141e1192018-08-31 18:23:53 +00001792 }
1793
1794 renameParseCleanup(&sParse);
1795 renameTokenFree(db, sCtx.pList);
1796 sqlite3BtreeLeaveAll(db);
1797#ifndef SQLITE_OMIT_AUTHORIZATION
1798 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001799#endif
1800 }
1801
danc9461ec2018-08-29 21:00:16 +00001802 return;
1803}
1804
dan1e240722021-03-15 20:22:34 +00001805static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1806 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1807 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1808 }
1809 return WRC_Continue;
1810}
1811
1812/*
1813** The implementation of an SQL scalar function that rewrites DDL statements
1814** so that any string literals that use double-quotes are modified so that
1815** they use single quotes.
1816**
1817** Two arguments must be passed:
1818**
1819** 0: Database name ("main", "temp" etc.).
1820** 1: SQL statement to edit.
1821**
1822** The returned value is the modified SQL statement. For example, given
1823** the database schema:
1824**
1825** CREATE TABLE t1(a, b, c);
1826**
1827** SELECT sqlite_rename_quotefix('main',
1828** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1829** );
1830**
1831** returns the string:
1832**
1833** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1834*/
1835static void renameQuotefixFunc(
1836 sqlite3_context *context,
1837 int NotUsed,
1838 sqlite3_value **argv
1839){
1840 sqlite3 *db = sqlite3_context_db_handle(context);
1841 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1842 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1843
1844#ifndef SQLITE_OMIT_AUTHORIZATION
1845 sqlite3_xauth xAuth = db->xAuth;
1846 db->xAuth = 0;
1847#endif
1848
1849 sqlite3BtreeEnterAll(db);
1850
1851 UNUSED_PARAMETER(NotUsed);
1852 if( zDb && zInput ){
1853 int rc;
1854 Parse sParse;
1855 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1856
1857 if( rc==SQLITE_OK ){
1858 RenameCtx sCtx;
1859 Walker sWalker;
1860
1861 /* Walker to find tokens that need to be replaced. */
1862 memset(&sCtx, 0, sizeof(RenameCtx));
1863 memset(&sWalker, 0, sizeof(Walker));
1864 sWalker.pParse = &sParse;
1865 sWalker.xExprCallback = renameQuotefixExprCb;
1866 sWalker.xSelectCallback = renameColumnSelectCb;
1867 sWalker.u.pRename = &sCtx;
1868
1869 if( sParse.pNewTable ){
drhf38524d2021-08-02 16:41:57 +00001870 if( IsView(sParse.pNewTable) ){
1871 Select *pSelect = sParse.pNewTable->u.view.pSelect;
dan1e240722021-03-15 20:22:34 +00001872 pSelect->selFlags &= ~SF_View;
1873 sParse.rc = SQLITE_OK;
1874 sqlite3SelectPrep(&sParse, pSelect, 0);
1875 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1876 if( rc==SQLITE_OK ){
1877 sqlite3WalkSelect(&sWalker, pSelect);
1878 }
1879 }else{
1880 int i;
1881 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1882#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1883 for(i=0; i<sParse.pNewTable->nCol; i++){
drh79cf2b72021-07-31 20:30:41 +00001884 sqlite3WalkExpr(&sWalker,
1885 sqlite3ColumnExpr(sParse.pNewTable,
1886 &sParse.pNewTable->aCol[i]));
dan1e240722021-03-15 20:22:34 +00001887 }
1888#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1889 }
1890 }else if( sParse.pNewIndex ){
1891 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1892 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1893 }else{
1894#ifndef SQLITE_OMIT_TRIGGER
1895 rc = renameResolveTrigger(&sParse);
1896 if( rc==SQLITE_OK ){
1897 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1898 }
1899#endif /* SQLITE_OMIT_TRIGGER */
1900 }
1901
1902 if( rc==SQLITE_OK ){
1903 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1904 }
dan1fffa732021-03-16 18:24:49 +00001905 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001906 }
1907 if( rc!=SQLITE_OK ){
1908 sqlite3_result_error_code(context, rc);
1909 }
1910 renameParseCleanup(&sParse);
1911 }
1912
1913#ifndef SQLITE_OMIT_AUTHORIZATION
1914 db->xAuth = xAuth;
1915#endif
1916
1917 sqlite3BtreeLeaveAll(db);
1918}
1919
dandd1a9c82018-09-05 08:28:30 +00001920/*
1921** An SQL user function that checks that there are no parse or symbol
1922** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1923** After an ALTER TABLE .. RENAME operation is performed and the schema
1924** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001925** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001926**
1927** 0: Database name ("main", "temp" etc.).
1928** 1: SQL statement.
1929** 2: Object type ("view", "table", "trigger" or "index").
1930** 3: Object name.
1931** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001932** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001933** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001934**
1935** Unless it finds an error, this function normally returns NULL. However, it
1936** returns integer value 1 if:
1937**
1938** * the SQL argument creates a trigger, and
1939** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001940*/
dan9d324822018-08-30 20:03:44 +00001941static void renameTableTest(
1942 sqlite3_context *context,
1943 int NotUsed,
1944 sqlite3_value **argv
1945){
1946 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001947 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1948 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001949 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001950 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001951 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001952 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001953
dan141e1192018-08-31 18:23:53 +00001954#ifndef SQLITE_OMIT_AUTHORIZATION
1955 sqlite3_xauth xAuth = db->xAuth;
1956 db->xAuth = 0;
1957#endif
1958
drh5b1da302018-09-01 20:02:07 +00001959 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001960
dan09236502018-09-01 16:05:50 +00001961 if( zDb && zInput ){
1962 int rc;
1963 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001964 int flags = db->flags;
1965 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001966 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001967 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001968 if( rc==SQLITE_OK ){
drhf38524d2021-08-02 16:41:57 +00001969 if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){
dan09236502018-09-01 16:05:50 +00001970 NameContext sNC;
1971 memset(&sNC, 0, sizeof(sNC));
1972 sNC.pParse = &sParse;
drhf38524d2021-08-02 16:41:57 +00001973 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
dan09236502018-09-01 16:05:50 +00001974 if( sParse.nErr ) rc = sParse.rc;
1975 }
1976
1977 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001978 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001979 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001980 }
drh3b700452018-09-07 19:12:08 +00001981 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001982 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1983 int i2 = sqlite3FindDbName(db, zDb);
1984 if( i1==i2 ) sqlite3_result_int(context, 1);
1985 }
dan09236502018-09-01 16:05:50 +00001986 }
dan9d324822018-08-30 20:03:44 +00001987 }
1988
dan16953462021-02-18 19:25:44 +00001989 if( rc!=SQLITE_OK && zWhen ){
1990 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001991 }
dan09236502018-09-01 16:05:50 +00001992 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001993 }
1994
dan141e1192018-08-31 18:23:53 +00001995#ifndef SQLITE_OMIT_AUTHORIZATION
1996 db->xAuth = xAuth;
1997#endif
dan9d324822018-08-30 20:03:44 +00001998}
1999
dancf8f2892018-08-09 20:47:01 +00002000/*
dan6a5a13d2021-02-17 20:08:22 +00002001** The implementation of internal UDF sqlite_drop_column().
2002**
dan6e6d9832021-02-16 20:43:36 +00002003** Arguments:
2004**
2005** argv[0]: An integer - the index of the schema containing the table
2006** argv[1]: CREATE TABLE statement to modify.
2007** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00002008**
2009** The value returned is a string containing the CREATE TABLE statement
2010** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00002011*/
2012static void dropColumnFunc(
2013 sqlite3_context *context,
2014 int NotUsed,
2015 sqlite3_value **argv
2016){
2017 sqlite3 *db = sqlite3_context_db_handle(context);
2018 int iSchema = sqlite3_value_int(argv[0]);
2019 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
2020 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00002021 const char *zDb = db->aDb[iSchema].zDbSName;
2022 int rc;
2023 Parse sParse;
2024 RenameToken *pCol;
2025 Table *pTab;
2026 const char *zEnd;
2027 char *zNew = 0;
2028
dan678f3b32021-02-18 20:27:46 +00002029#ifndef SQLITE_OMIT_AUTHORIZATION
2030 sqlite3_xauth xAuth = db->xAuth;
2031 db->xAuth = 0;
2032#endif
2033
drh05edf722021-03-04 19:44:01 +00002034 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00002035 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2036 if( rc!=SQLITE_OK ) goto drop_column_done;
2037 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002038 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002039 /* This can happen if the sqlite_schema table is corrupt */
2040 rc = SQLITE_CORRUPT_BKPT;
2041 goto drop_column_done;
2042 }
dan6e6d9832021-02-16 20:43:36 +00002043
2044 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
2045 if( iCol<pTab->nCol-1 ){
2046 RenameToken *pEnd;
2047 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
2048 zEnd = (const char*)pEnd->t.z;
2049 }else{
drhf38524d2021-08-02 16:41:57 +00002050 assert( !IsVirtual(pTab) );
2051 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
drh60fe2352021-02-19 09:46:52 +00002052 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002053 }
2054
danc2a878e2021-02-17 20:46:44 +00002055 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002056 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2057 sqlite3_free(zNew);
2058
2059drop_column_done:
2060 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002061#ifndef SQLITE_OMIT_AUTHORIZATION
2062 db->xAuth = xAuth;
2063#endif
danf4a72782021-02-19 14:13:40 +00002064 if( rc!=SQLITE_OK ){
2065 sqlite3_result_error_code(context, rc);
2066 }
dan6e6d9832021-02-16 20:43:36 +00002067}
2068
dan6a5a13d2021-02-17 20:08:22 +00002069/*
2070** This function is called by the parser upon parsing an
2071**
2072** ALTER TABLE pSrc DROP COLUMN pName
2073**
2074** statement. Argument pSrc contains the possibly qualified name of the
2075** table being edited, and token pName the name of the column to drop.
2076*/
dan6e6d9832021-02-16 20:43:36 +00002077void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002078 sqlite3 *db = pParse->db; /* Database handle */
2079 Table *pTab; /* Table to modify */
2080 int iDb; /* Index of db containing pTab in aDb[] */
2081 const char *zDb; /* Database containing pTab ("main" etc.) */
2082 char *zCol = 0; /* Name of column to drop */
2083 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002084
2085 /* Look up the table being altered. */
2086 assert( pParse->pNewTable==0 );
2087 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002088 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002089 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2090 if( !pTab ) goto exit_drop_column;
2091
dan6a5a13d2021-02-17 20:08:22 +00002092 /* Make sure this is not an attempt to ALTER a view, virtual table or
2093 ** system table. */
2094 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2095 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002096
2097 /* Find the index of the column being dropped. */
2098 zCol = sqlite3NameFromToken(db, pName);
2099 if( zCol==0 ){
2100 assert( db->mallocFailed );
2101 goto exit_drop_column;
2102 }
2103 iCol = sqlite3ColumnIndex(pTab, zCol);
2104 if( iCol<0 ){
2105 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2106 goto exit_drop_column;
2107 }
2108
2109 /* Do not allow the user to drop a PRIMARY KEY column or a column
2110 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002111 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2112 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2113 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2114 zCol
2115 );
dan6e6d9832021-02-16 20:43:36 +00002116 goto exit_drop_column;
2117 }
dan6e6d9832021-02-16 20:43:36 +00002118
drh239c84f2021-02-19 09:09:07 +00002119 /* Do not allow the number of columns to go to zero */
2120 if( pTab->nCol<=1 ){
2121 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2122 goto exit_drop_column;
2123 }
2124
dan6a5a13d2021-02-17 20:08:22 +00002125 /* Edit the sqlite_schema table */
2126 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2127 assert( iDb>=0 );
2128 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002129 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2130 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002131 sqlite3NestedParse(pParse,
2132 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002133 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002134 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002135 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002136 );
2137
2138 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002139 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002140 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002141
2142 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002143 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002144 int i;
2145 int addr;
2146 int reg;
2147 int regRec;
2148 Index *pPk = 0;
2149 int nField = 0; /* Number of non-virtual columns after drop */
2150 int iCur;
2151 Vdbe *v = sqlite3GetVdbe(pParse);
2152 iCur = pParse->nTab++;
2153 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002154 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002155 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002156 if( HasRowid(pTab) ){
2157 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002158 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002159 }else{
2160 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002161 pParse->nMem += pPk->nColumn;
2162 for(i=0; i<pPk->nKeyCol; i++){
2163 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2164 }
2165 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002166 }
dancc263012021-04-06 21:20:39 +00002167 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002168 for(i=0; i<pTab->nCol; i++){
2169 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2170 int regOut;
2171 if( pPk ){
2172 int iPos = sqlite3TableColumnToIndex(pPk, i);
2173 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002174 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002175 regOut = reg+1+iPos-(iPos>iColPos);
2176 }else{
2177 regOut = reg+1+nField;
2178 }
dan0a746cc2021-04-18 05:30:39 +00002179 if( i==pTab->iPKey ){
2180 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2181 }else{
2182 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2183 }
dan6a5a13d2021-02-17 20:08:22 +00002184 nField++;
2185 }
2186 }
drh55b8b732021-07-22 18:22:51 +00002187 if( nField==0 ){
2188 /* dbsqlfuzz 5f09e7bcc78b4954d06bf9f2400d7715f48d1fef */
2189 pParse->nMem++;
2190 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1);
2191 nField = 1;
2192 }
dan6a5a13d2021-02-17 20:08:22 +00002193 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2194 if( pPk ){
2195 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2196 }else{
2197 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2198 }
dan0a746cc2021-04-18 05:30:39 +00002199 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002200
drh03361402021-02-18 23:53:47 +00002201 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002202 sqlite3VdbeJumpHere(v, addr);
2203 }
dan6e6d9832021-02-16 20:43:36 +00002204
2205exit_drop_column:
2206 sqlite3DbFree(db, zCol);
2207 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002208}
2209
2210/*
dancf8f2892018-08-09 20:47:01 +00002211** Register built-in functions used to help implement ALTER TABLE
2212*/
2213void sqlite3AlterFunctions(void){
2214 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002215 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2216 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002217 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002218 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002219 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002220 };
2221 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2222}
drhd0e4a6c2005-02-15 20:47:57 +00002223#endif /* SQLITE_ALTER_TABLE */