blob: 9c5b46261a4e116748a78f9eab995964b71cd989 [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
178 if( pTab->pSelect ){
179 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];
340 pDflt = pCol->pDflt;
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 }
374 if( (db->flags&SQLITE_ForeignKeys) && pNew->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: */
danielk197719a8e7e2005-03-17 05:03:38 +0000418 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000419 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000420 "sql = printf('%%.%ds, ',sql) || %Q"
421 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000422 "WHERE type = 'table' AND name = %Q",
drh37114fb2021-01-01 20:04:34 +0000423 zDb, pNew->addColOffset, zCol, pNew->addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000424 zTab
425 );
drh633e6d52008-07-28 19:34:53 +0000426 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000427 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000428 }
429
dan09236502018-09-01 16:05:50 +0000430 v = sqlite3GetVdbe(pParse);
431 if( v ){
drhb4d9b2b2021-07-20 07:35:07 +0000432 /* Make sure the schema version is at least 3. But do not upgrade
433 ** from less than 3 to 4, as that will corrupt any preexisting DESC
434 ** index.
435 */
dan09236502018-09-01 16:05:50 +0000436 r1 = sqlite3GetTempReg(pParse);
437 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
438 sqlite3VdbeUsesBtree(v, iDb);
439 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
440 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
441 VdbeCoverage(v);
442 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
443 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000444
drhb4d9b2b2021-07-20 07:35:07 +0000445 /* Reload the table definition */
446 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
447
448 /* Verify that constraints are still satisfied */
drh0f91a532021-07-20 08:23:54 +0000449 if( pNew->pCheck!=0
drhb4d9b2b2021-07-20 07:35:07 +0000450 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
451 ){
452 sqlite3NestedParse(pParse,
453 "SELECT CASE WHEN quick_check GLOB 'CHECK*'"
454 " THEN raise(ABORT,'CHECK constraint failed')"
drh0f91a532021-07-20 08:23:54 +0000455 " ELSE raise(ABORT,'NOT NULL constraint failed')"
drhb4d9b2b2021-07-20 07:35:07 +0000456 " END"
drh0f91a532021-07-20 08:23:54 +0000457 " FROM pragma_quick_check(\"%w\",\"%w\")"
458 " WHERE quick_check GLOB 'CHECK*' OR quick_check GLOB 'NULL*'",
drhb4d9b2b2021-07-20 07:35:07 +0000459 zTab, zDb
460 );
461 }
462 }
danielk197719a8e7e2005-03-17 05:03:38 +0000463}
464
drhfdd6e852005-12-16 01:06:16 +0000465/*
danielk197719a8e7e2005-03-17 05:03:38 +0000466** This function is called by the parser after the table-name in
467** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
468** pSrc is the full-name of the table being altered.
469**
470** This routine makes a (partial) copy of the Table structure
471** for the table being altered and sets Parse.pNewTable to point
472** to it. Routines called by the parser as the column definition
473** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
474** the copy. The copy of the Table structure is deleted by tokenize.c
475** after parsing is finished.
476**
477** Routine sqlite3AlterFinishAddColumn() will be called to complete
478** coding the "ALTER TABLE ... ADD" statement.
479*/
480void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
481 Table *pNew;
482 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000483 int iDb;
484 int i;
485 int nAlloc;
drh17435752007-08-16 04:30:38 +0000486 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000487
488 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000489 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000490 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000491 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000492 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000493 if( !pTab ) goto exit_begin_add_column;
494
danielk19775ee9d692006-06-21 12:36:25 +0000495#ifndef SQLITE_OMIT_VIRTUALTABLE
496 if( IsVirtual(pTab) ){
497 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
498 goto exit_begin_add_column;
499 }
500#endif
501
danielk197719a8e7e2005-03-17 05:03:38 +0000502 /* Make sure this is not an attempt to ALTER a view. */
503 if( pTab->pSelect ){
504 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
505 goto exit_begin_add_column;
506 }
dan397a78d2018-12-18 20:31:14 +0000507 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000508 goto exit_begin_add_column;
509 }
danielk197719a8e7e2005-03-17 05:03:38 +0000510
dan03e025e2019-10-07 18:43:21 +0000511 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000512 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000513 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000514
515 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000516 ** sqlite3AddColumn() function and friends to modify. But modify
517 ** the name by adding an "sqlite_altertab_" prefix. By adding this
518 ** prefix, we insure that the name will not collide with an existing
519 ** table because user table are not allowed to have the "sqlite_"
520 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000521 */
drh17435752007-08-16 04:30:38 +0000522 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000523 if( !pNew ) goto exit_begin_add_column;
524 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000525 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000526 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000527 assert( pNew->nCol>0 );
528 nAlloc = (((pNew->nCol-1)/8)*8)+8;
529 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000530 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000531 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000532 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000533 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000534 goto exit_begin_add_column;
535 }
536 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
537 for(i=0; i<pNew->nCol; i++){
538 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000539 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000540 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000541 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000542 pCol->pDflt = 0;
543 }
drh17435752007-08-16 04:30:38 +0000544 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000545 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000546 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000547
danielk197719a8e7e2005-03-17 05:03:38 +0000548exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000549 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000550 return;
551}
dancf8f2892018-08-09 20:47:01 +0000552
drh4a2c7472018-08-13 15:09:48 +0000553/*
dan9d705572018-08-20 16:16:05 +0000554** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
555** command. This function checks if the table is a view or virtual
556** table (columns of views or virtual tables may not be renamed). If so,
557** it loads an error message into pParse and returns non-zero.
558**
559** Or, if pTab is not a view or virtual table, zero is returned.
560*/
561#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000562static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000563 const char *zType = 0;
564#ifndef SQLITE_OMIT_VIEW
565 if( pTab->pSelect ){
566 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000567 }
dan9d705572018-08-20 16:16:05 +0000568#endif
569#ifndef SQLITE_OMIT_VIRTUALTABLE
570 if( IsVirtual(pTab) ){
571 zType = "virtual table";
572 }
573#endif
574 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000575 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
576 (bDrop ? "drop column from" : "rename columns of"),
577 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000578 );
579 return 1;
580 }
581 return 0;
582}
583#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000584# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000585#endif
586
587/*
drh4a2c7472018-08-13 15:09:48 +0000588** Handles the following parser reduction:
589**
590** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
591*/
dancf8f2892018-08-09 20:47:01 +0000592void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000593 Parse *pParse, /* Parsing context */
594 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
595 Token *pOld, /* Name of column being changed */
596 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000597){
drh4a2c7472018-08-13 15:09:48 +0000598 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000599 Table *pTab; /* Table being updated */
600 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000601 char *zOld = 0; /* Old column name */
602 char *zNew = 0; /* New column name */
603 const char *zDb; /* Name of schema containing the table */
604 int iSchema; /* Index of the schema */
605 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000606
drh4a2c7472018-08-13 15:09:48 +0000607 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000608 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
609 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000610
611 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000612 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000613 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000614
615 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000616 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
617 assert( iSchema>=0 );
618 zDb = db->aDb[iSchema].zDbSName;
619
drh0d019b92018-08-25 16:14:46 +0000620#ifndef SQLITE_OMIT_AUTHORIZATION
621 /* Invoke the authorization callback. */
622 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
623 goto exit_rename_column;
624 }
625#endif
626
drh4a2c7472018-08-13 15:09:48 +0000627 /* Make sure the old name really is a column name in the table to be
628 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000629 zOld = sqlite3NameFromToken(db, pOld);
630 if( !zOld ) goto exit_rename_column;
631 for(iCol=0; iCol<pTab->nCol; iCol++){
632 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
633 }
634 if( iCol==pTab->nCol ){
635 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
636 goto exit_rename_column;
637 }
638
dan2ad080a2021-03-16 16:14:48 +0000639 /* Ensure the schema contains no double-quoted strings */
640 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
641 renameFixQuotes(pParse, zDb, iSchema==1);
642
drh4a2c7472018-08-13 15:09:48 +0000643 /* Do the rename operation using a recursive UPDATE statement that
644 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000645 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000646 */
dan1f3b2842019-03-15 16:17:32 +0000647 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000648 zNew = sqlite3NameFromToken(db, pNew);
649 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000650 assert( pNew->n>0 );
651 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000652 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000653 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000654 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000655 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
656 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000657 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000658 zDb,
danb87a9a82018-09-01 20:23:28 +0000659 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000660 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000661 );
662
dan9d324822018-08-30 20:03:44 +0000663 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000664 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000665 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000666 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000667 zDb, pTab->zName, iCol, zNew, bQuote
668 );
669
dane325ffe2018-08-11 13:40:20 +0000670 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000671 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000672 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000673
dancf8f2892018-08-09 20:47:01 +0000674 exit_rename_column:
675 sqlite3SrcListDelete(db, pSrc);
676 sqlite3DbFree(db, zOld);
677 sqlite3DbFree(db, zNew);
678 return;
679}
680
drh4a2c7472018-08-13 15:09:48 +0000681/*
682** Each RenameToken object maps an element of the parse tree into
683** the token that generated that element. The parse tree element
684** might be one of:
685**
686** * A pointer to an Expr that represents an ID
687** * The name of a table column in Column.zName
688**
689** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000690** Each new object is created by sqlite3RenameTokenMap().
691** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000692** routine is used to keep the mapping current.
693**
694** After the parse finishes, renameTokenFind() routine can be used
695** to look up the actual token value that created some element in
696** the parse tree.
697*/
dancf8f2892018-08-09 20:47:01 +0000698struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000699 void *p; /* Parse tree element created by token t */
700 Token t; /* The token that created parse tree element p */
701 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000702};
703
drh4a2c7472018-08-13 15:09:48 +0000704/*
705** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
706** down into the Walker.
707*/
dan5496d6a2018-08-13 17:14:26 +0000708typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000709struct RenameCtx {
710 RenameToken *pList; /* List of tokens to overwrite */
711 int nList; /* Number of tokens in pList */
712 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000713 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000714 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000715};
716
dan8900a482018-09-05 14:36:05 +0000717#ifdef SQLITE_DEBUG
718/*
719** This function is only for debugging. It performs two tasks:
720**
721** 1. Checks that pointer pPtr does not already appear in the
722** rename-token list.
723**
724** 2. Dereferences each pointer in the rename-token list.
725**
726** The second is most effective when debugging under valgrind or
727** address-sanitizer or similar. If any of these pointers no longer
728** point to valid objects, an exception is raised by the memory-checking
729** tool.
730**
731** The point of this is to prevent comparisons of invalid pointer values.
732** Even though this always seems to work, it is undefined according to the
733** C standard. Example of undefined comparison:
734**
735** sqlite3_free(x);
736** if( x==y ) ...
737**
738** Technically, as x no longer points into a valid object or to the byte
739** following a valid object, it may not be used in comparison operations.
740*/
drh16b870d2018-09-12 15:51:56 +0000741static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000742 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
743 RenameToken *p;
744 u8 i = 0;
745 for(p=pParse->pRename; p; p=p->pNext){
746 if( p->p ){
747 assert( p->p!=pPtr );
748 i += *(u8*)(p->p);
749 }
danc9461ec2018-08-29 21:00:16 +0000750 }
751 }
752}
dan8900a482018-09-05 14:36:05 +0000753#else
754# define renameTokenCheckAll(x,y)
755#endif
danc9461ec2018-08-29 21:00:16 +0000756
drh4a2c7472018-08-13 15:09:48 +0000757/*
drh49b269e2018-11-26 15:00:25 +0000758** Remember that the parser tree element pPtr was created using
759** the token pToken.
dan07e95232018-08-21 16:32:53 +0000760**
drh49b269e2018-11-26 15:00:25 +0000761** In other words, construct a new RenameToken object and add it
762** to the list of RenameToken objects currently being built up
763** in pParse->pRename.
764**
765** The pPtr argument is returned so that this routine can be used
766** with tail recursion in tokenExpr() routine, for a small performance
767** improvement.
drh4a2c7472018-08-13 15:09:48 +0000768*/
dan07e95232018-08-21 16:32:53 +0000769void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000770 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000771 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000772 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000773 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000774 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
775 if( pNew ){
776 pNew->p = pPtr;
777 pNew->t = *pToken;
778 pNew->pNext = pParse->pRename;
779 pParse->pRename = pNew;
780 }
dancf8f2892018-08-09 20:47:01 +0000781 }
danc9461ec2018-08-29 21:00:16 +0000782
dand145e5f2018-08-21 08:29:48 +0000783 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000784}
785
drh4a2c7472018-08-13 15:09:48 +0000786/*
dan07e95232018-08-21 16:32:53 +0000787** It is assumed that there is already a RenameToken object associated
788** with parse tree element pFrom. This function remaps the associated token
789** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000790*/
dan07e95232018-08-21 16:32:53 +0000791void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000792 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000793 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000794 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000795 if( p->p==pFrom ){
796 p->p = pTo;
797 break;
798 }
799 }
dancf8f2892018-08-09 20:47:01 +0000800}
801
drh4a2c7472018-08-13 15:09:48 +0000802/*
dan8900a482018-09-05 14:36:05 +0000803** Walker callback used by sqlite3RenameExprUnmap().
804*/
805static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
806 Parse *pParse = pWalker->pParse;
807 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
808 return WRC_Continue;
809}
810
811/*
dan8f407622019-12-04 14:26:38 +0000812** Iterate through the Select objects that are part of WITH clauses attached
813** to select statement pSelect.
814*/
815static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000816 With *pWith = pSelect->pWith;
817 if( pWith ){
dan26d61e52021-06-11 11:14:24 +0000818 Parse *pParse = pWalker->pParse;
dan8f407622019-12-04 14:26:38 +0000819 int i;
drh35e6cd02021-06-11 13:18:56 +0000820 With *pCopy = 0;
dan26d61e52021-06-11 11:14:24 +0000821 assert( pWith->nCte>0 );
drh35e6cd02021-06-11 13:18:56 +0000822 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
823 /* Push a copy of the With object onto the with-stack. We use a copy
824 ** here as the original will be expanded and resolved (flags SF_Expanded
825 ** and SF_Resolved) below. And the parser code that uses the with-stack
826 ** fails if the Select objects on it have already been expanded and
827 ** resolved. */
828 pCopy = sqlite3WithDup(pParse->db, pWith);
drh24ce9442021-06-12 17:45:32 +0000829 pCopy = sqlite3WithPush(pParse, pCopy, 1);
drh35e6cd02021-06-11 13:18:56 +0000830 }
831 for(i=0; i<pWith->nCte; i++){
832 Select *p = pWith->a[i].pSelect;
833 NameContext sNC;
834 memset(&sNC, 0, sizeof(sNC));
835 sNC.pParse = pParse;
836 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
837 sqlite3WalkSelect(pWalker, p);
838 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
839 }
840 if( pCopy && pParse->pWith==pCopy ){
dand03d3a92021-06-11 12:14:58 +0000841 pParse->pWith = pCopy->pOuter;
dan26d61e52021-06-11 11:14:24 +0000842 }
dan8f407622019-12-04 14:26:38 +0000843 }
844}
845
846/*
danfb99e382020-04-03 11:20:40 +0000847** Unmap all tokens in the IdList object passed as the second argument.
848*/
849static void unmapColumnIdlistNames(
850 Parse *pParse,
851 IdList *pIdList
852){
853 if( pIdList ){
854 int ii;
855 for(ii=0; ii<pIdList->nId; ii++){
856 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
857 }
858 }
859}
860
861/*
dan0b277a92019-06-11 12:03:10 +0000862** Walker callback used by sqlite3RenameExprUnmap().
863*/
864static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000865 Parse *pParse = pWalker->pParse;
866 int i;
drhd63b69b2019-12-04 15:08:58 +0000867 if( pParse->nErr ) return WRC_Abort;
danac67f562021-06-14 20:08:48 +0000868 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000869 testcase( p->selFlags & SF_View );
870 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000871 return WRC_Prune;
872 }
drhbdf4cf02019-06-15 15:21:49 +0000873 if( ALWAYS(p->pEList) ){
874 ExprList *pList = p->pEList;
875 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000876 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000877 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000878 }
879 }
880 }
drh2c3f4652019-06-11 16:43:58 +0000881 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000882 SrcList *pSrc = p->pSrc;
883 for(i=0; i<pSrc->nSrc; i++){
884 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000885 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000886 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000887 }
888 }
dan8f407622019-12-04 14:26:38 +0000889
890 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000891 return WRC_Continue;
892}
893
894/*
dan8900a482018-09-05 14:36:05 +0000895** Remove all nodes that are part of expression pExpr from the rename list.
896*/
897void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000898 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000899 Walker sWalker;
900 memset(&sWalker, 0, sizeof(Walker));
901 sWalker.pParse = pParse;
902 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000903 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000904 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000905 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000906 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000907}
908
909/*
dane8ab40d2018-09-12 08:51:48 +0000910** Remove all nodes that are part of expression-list pEList from the
911** rename list.
912*/
913void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
914 if( pEList ){
915 int i;
916 Walker sWalker;
917 memset(&sWalker, 0, sizeof(Walker));
918 sWalker.pParse = pParse;
919 sWalker.xExprCallback = renameUnmapExprCb;
920 sqlite3WalkExprList(&sWalker, pEList);
921 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000922 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000923 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
924 }
dane8ab40d2018-09-12 08:51:48 +0000925 }
926 }
927}
928
929/*
drh4a2c7472018-08-13 15:09:48 +0000930** Free the list of RenameToken objects given in the second argument
931*/
dancf8f2892018-08-09 20:47:01 +0000932static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
933 RenameToken *pNext;
934 RenameToken *p;
935 for(p=pToken; p; p=pNext){
936 pNext = p->pNext;
937 sqlite3DbFree(db, p);
938 }
939}
940
dan987db762018-08-14 20:18:50 +0000941/*
942** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000943** object associated with parse tree element pPtr. If found, return a pointer
944** to it. Otherwise, return NULL.
945**
946** If the second argument passed to this function is not NULL and a matching
947** RenameToken object is found, remove it from the Parse object and add it to
948** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000949*/
dan6e6d9832021-02-16 20:43:36 +0000950static RenameToken *renameTokenFind(
951 Parse *pParse,
952 struct RenameCtx *pCtx,
953 void *pPtr
954){
dancf8f2892018-08-09 20:47:01 +0000955 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000956 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000957 return 0;
958 }
dancf8f2892018-08-09 20:47:01 +0000959 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
960 if( (*pp)->p==pPtr ){
961 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000962 if( pCtx ){
963 *pp = pToken->pNext;
964 pToken->pNext = pCtx->pList;
965 pCtx->pList = pToken;
966 pCtx->nList++;
967 }
968 return pToken;
dancf8f2892018-08-09 20:47:01 +0000969 }
970 }
dan6e6d9832021-02-16 20:43:36 +0000971 return 0;
dancf8f2892018-08-09 20:47:01 +0000972}
973
dan24fedb92018-08-18 17:35:38 +0000974/*
975** This is a Walker select callback. It does nothing. It is only required
976** because without a dummy callback, sqlite3WalkExpr() and similar do not
977** descend into sub-select statements.
978*/
dan987db762018-08-14 20:18:50 +0000979static int renameColumnSelectCb(Walker *pWalker, Select *p){
danac67f562021-06-14 20:08:48 +0000980 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000981 testcase( p->selFlags & SF_View );
982 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000983 return WRC_Prune;
984 }
danea412512018-12-05 13:49:04 +0000985 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000986 return WRC_Continue;
987}
988
dan987db762018-08-14 20:18:50 +0000989/*
990** This is a Walker expression callback.
991**
992** For every TK_COLUMN node in the expression tree, search to see
993** if the column being references is the column being renamed by an
994** ALTER TABLE statement. If it is, then attach its associated
995** RenameToken object to the list of RenameToken objects being
996** constructed in RenameCtx object at pWalker->u.pRename.
997*/
dancf8f2892018-08-09 20:47:01 +0000998static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000999 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +00001000 if( pExpr->op==TK_TRIGGER
1001 && pExpr->iColumn==p->iCol
1002 && pWalker->pParse->pTriggerTab==p->pTab
1003 ){
dan5be60c52018-08-15 20:28:39 +00001004 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +00001005 }else if( pExpr->op==TK_COLUMN
1006 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +00001007 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +00001008 ){
dan5496d6a2018-08-13 17:14:26 +00001009 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +00001010 }
1011 return WRC_Continue;
1012}
1013
dan987db762018-08-14 20:18:50 +00001014/*
1015** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001016** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001017** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001018** RenameContext. "Last" means the last RenameToken encountered when
1019** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001020** return all column name tokens in the order that they are encountered
1021** in the SQL statement.
1022*/
dan5496d6a2018-08-13 17:14:26 +00001023static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001024 RenameToken *pBest = pCtx->pList;
1025 RenameToken *pToken;
1026 RenameToken **pp;
1027
1028 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1029 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1030 }
1031 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1032 *pp = pBest->pNext;
1033
1034 return pBest;
1035}
1036
dan6fe7f232018-08-10 19:19:33 +00001037/*
dan24fedb92018-08-18 17:35:38 +00001038** An error occured while parsing or otherwise processing a database
1039** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1040** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1041** sub-routine is currently stored in pParse->zErrMsg. This function
1042** adds context to the error message and then stores it in pCtx.
1043*/
danb0137382018-08-20 20:01:01 +00001044static void renameColumnParseError(
1045 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001046 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001047 sqlite3_value *pType,
1048 sqlite3_value *pObject,
1049 Parse *pParse
1050){
drh79a5ee92018-08-23 19:32:04 +00001051 const char *zT = (const char*)sqlite3_value_text(pType);
1052 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001053 char *zErr;
danb0137382018-08-20 20:01:01 +00001054
dan16953462021-02-18 19:25:44 +00001055 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1056 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001057 pParse->zErrMsg
1058 );
dan24fedb92018-08-18 17:35:38 +00001059 sqlite3_result_error(pCtx, zErr, -1);
1060 sqlite3_free(zErr);
1061}
1062
1063/*
dan06249392018-08-21 15:06:59 +00001064** For each name in the the expression-list pEList (i.e. each
1065** pEList->a[i].zName) that matches the string in zOld, extract the
1066** corresponding rename-token from Parse object pParse and add it
1067** to the RenameCtx pCtx.
1068*/
1069static void renameColumnElistNames(
1070 Parse *pParse,
1071 RenameCtx *pCtx,
1072 ExprList *pEList,
1073 const char *zOld
1074){
1075 if( pEList ){
1076 int i;
1077 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001078 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001079 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1080 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001081 && 0==sqlite3_stricmp(zName, zOld)
1082 ){
dan06249392018-08-21 15:06:59 +00001083 renameTokenFind(pParse, pCtx, (void*)zName);
1084 }
1085 }
1086 }
1087}
1088
1089/*
1090** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1091** that matches the string in zOld, extract the corresponding rename-token
1092** from Parse object pParse and add it to the RenameCtx pCtx.
1093*/
1094static void renameColumnIdlistNames(
1095 Parse *pParse,
1096 RenameCtx *pCtx,
1097 IdList *pIdList,
1098 const char *zOld
1099){
1100 if( pIdList ){
1101 int i;
1102 for(i=0; i<pIdList->nId; i++){
1103 char *zName = pIdList->a[i].zName;
1104 if( 0==sqlite3_stricmp(zName, zOld) ){
1105 renameTokenFind(pParse, pCtx, (void*)zName);
1106 }
1107 }
1108 }
1109}
1110
danfb99e382020-04-03 11:20:40 +00001111
dandd1a9c82018-09-05 08:28:30 +00001112/*
1113** Parse the SQL statement zSql using Parse object (*p). The Parse object
1114** is initialized by this function before it is used.
1115*/
danc9461ec2018-08-29 21:00:16 +00001116static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001117 Parse *p, /* Memory to use for Parse object */
1118 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001119 sqlite3 *db, /* Database handle */
1120 const char *zSql, /* SQL to parse */
1121 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001122){
1123 int rc;
1124 char *zErr = 0;
1125
1126 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1127
1128 /* Parse the SQL statement passed as the first argument. If no error
1129 ** occurs and the parse does not result in a new table, index or
1130 ** trigger object, the database must be corrupt. */
1131 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001132 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001133 p->db = db;
1134 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001135 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001136 assert( p->zErrMsg==0 );
1137 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001138 p->zErrMsg = zErr;
1139 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1140 if( rc==SQLITE_OK
1141 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1142 ){
1143 rc = SQLITE_CORRUPT_BKPT;
1144 }
1145
1146#ifdef SQLITE_DEBUG
1147 /* Ensure that all mappings in the Parse.pRename list really do map to
1148 ** a part of the input string. */
1149 if( rc==SQLITE_OK ){
1150 int nSql = sqlite3Strlen30(zSql);
1151 RenameToken *pToken;
1152 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1153 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1154 }
1155 }
1156#endif
1157
1158 db->init.iDb = 0;
1159 return rc;
1160}
1161
dandd1a9c82018-09-05 08:28:30 +00001162/*
1163** This function edits SQL statement zSql, replacing each token identified
1164** by the linked list pRename with the text of zNew. If argument bQuote is
1165** true, then zNew is always quoted first. If no error occurs, the result
1166** is loaded into context object pCtx as the result.
1167**
1168** Or, if an error occurs (i.e. an OOM condition), an error is left in
1169** pCtx and an SQLite error code returned.
1170*/
danc9461ec2018-08-29 21:00:16 +00001171static int renameEditSql(
1172 sqlite3_context *pCtx, /* Return result here */
1173 RenameCtx *pRename, /* Rename context */
1174 const char *zSql, /* SQL statement to edit */
1175 const char *zNew, /* New token text */
1176 int bQuote /* True to always quote token */
1177){
drh236bcdf2021-06-16 11:32:54 +00001178 i64 nNew = sqlite3Strlen30(zNew);
1179 i64 nSql = sqlite3Strlen30(zSql);
danc9461ec2018-08-29 21:00:16 +00001180 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1181 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001182 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001183 char *zOut;
drh236bcdf2021-06-16 11:32:54 +00001184 i64 nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001185 char *zBuf1 = 0;
1186 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001187
dan1e240722021-03-15 20:22:34 +00001188 if( zNew ){
1189 /* Set zQuot to point to a buffer containing a quoted copy of the
1190 ** identifier zNew. If the corresponding identifier in the original
1191 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1192 ** point to zQuot so that all substitutions are made using the
1193 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001194 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001195 if( zQuot==0 ){
1196 return SQLITE_NOMEM;
1197 }else{
dan1d14ffe2021-03-23 22:15:34 +00001198 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001199 }
1200
1201 assert( nQuot>=nNew );
1202 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001203 }else{
dan1e240722021-03-15 20:22:34 +00001204 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1205 if( zOut ){
1206 zBuf1 = &zOut[nSql*2+1];
1207 zBuf2 = &zOut[nSql*4+2];
1208 }
danc9461ec2018-08-29 21:00:16 +00001209 }
1210
1211 /* At this point pRename->pList contains a list of RenameToken objects
1212 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001213 ** with the new column name, or with single-quoted versions of themselves.
1214 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001215 if( zOut ){
1216 int nOut = nSql;
1217 memcpy(zOut, zSql, nSql);
1218 while( pRename->pList ){
1219 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001220 u32 nReplace;
1221 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001222 RenameToken *pBest = renameColumnTokenNext(pRename);
1223
1224 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001225 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001226 nReplace = nNew;
1227 zReplace = zNew;
1228 }else{
1229 nReplace = nQuot;
1230 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001231 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001232 }
danc9461ec2018-08-29 21:00:16 +00001233 }else{
dan1e240722021-03-15 20:22:34 +00001234 /* Dequote the double-quoted token. Then requote it again, this time
1235 ** using single quotes. If the character immediately following the
1236 ** original token within the input SQL was a single quote ('), then
1237 ** add another space after the new, single-quoted version of the
1238 ** token. This is so that (SELECT "string"'alias') maps to
1239 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1240 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1241 zBuf1[pBest->t.n] = 0;
1242 sqlite3Dequote(zBuf1);
1243 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1244 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1245 );
1246 zReplace = zBuf2;
1247 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001248 }
1249
1250 iOff = pBest->t.z - zSql;
1251 if( pBest->t.n!=nReplace ){
1252 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1253 nOut - (iOff + pBest->t.n)
1254 );
1255 nOut += nReplace - pBest->t.n;
1256 zOut[nOut] = '\0';
1257 }
1258 memcpy(&zOut[iOff], zReplace, nReplace);
1259 sqlite3DbFree(db, pBest);
1260 }
1261
1262 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1263 sqlite3DbFree(db, zOut);
1264 }else{
1265 rc = SQLITE_NOMEM;
1266 }
1267
1268 sqlite3_free(zQuot);
1269 return rc;
1270}
1271
dandd1a9c82018-09-05 08:28:30 +00001272/*
1273** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1274** it was read from the schema of database zDb. Return SQLITE_OK if
1275** successful. Otherwise, return an SQLite error code and leave an error
1276** message in the Parse object.
1277*/
drha7c74002020-07-18 18:44:59 +00001278static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001279 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001280 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001281 TriggerStep *pStep;
1282 NameContext sNC;
1283 int rc = SQLITE_OK;
1284
1285 memset(&sNC, 0, sizeof(sNC));
1286 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001287 assert( pNew->pTabSchema );
1288 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1289 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1290 );
1291 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001292 /* ALWAYS() because if the table of the trigger does not exist, the
1293 ** error would have been hit before this point */
1294 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001295 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1296 }
danc9461ec2018-08-29 21:00:16 +00001297
1298 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001299 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001300 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001301 }
1302
dand5e6fef2018-09-07 15:50:31 +00001303 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001304 if( pStep->pSelect ){
1305 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1306 if( pParse->nErr ) rc = pParse->rc;
1307 }
dand5e6fef2018-09-07 15:50:31 +00001308 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001309 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1310 if( pSrc ){
1311 int i;
drha3e64952020-08-12 16:19:12 +00001312 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001313 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001314 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001315 if( p->pSelect ){
1316 sqlite3SelectPrep(pParse, p->pSelect, 0);
1317 sqlite3ExpandSubquery(pParse, p);
1318 assert( i>0 );
1319 assert( pStep->pFrom->a[i-1].pSelect );
1320 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001321 }else{
dan7a39fae2020-10-31 16:33:01 +00001322 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1323 if( p->pTab==0 ){
1324 rc = SQLITE_ERROR;
1325 }else{
1326 p->pTab->nTabRef++;
1327 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1328 }
dane7877b22020-07-14 19:51:01 +00001329 }
1330 }
1331 sNC.pSrcList = pSrc;
1332 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001333 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1334 }
1335 if( rc==SQLITE_OK ){
1336 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1337 }
1338 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001339 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001340 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001341 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001342 sNC.uNC.pUpsert = pUpsert;
1343 sNC.ncFlags = NC_UUpsert;
1344 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1345 if( rc==SQLITE_OK ){
1346 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1347 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1348 }
1349 if( rc==SQLITE_OK ){
1350 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1351 }
1352 if( rc==SQLITE_OK ){
1353 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1354 }
1355 sNC.ncFlags = 0;
1356 }
dan0e14e982019-01-18 16:06:18 +00001357 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001358 sqlite3SrcListDelete(db, pSrc);
1359 }else{
1360 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001361 }
1362 }
1363 }
1364 return rc;
1365}
1366
dandd1a9c82018-09-05 08:28:30 +00001367/*
1368** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1369** objects that are part of the trigger passed as the second argument.
1370*/
danc9461ec2018-08-29 21:00:16 +00001371static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1372 TriggerStep *pStep;
1373
1374 /* Find tokens to edit in WHEN clause */
1375 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1376
1377 /* Find tokens to edit in trigger steps */
1378 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1379 sqlite3WalkSelect(pWalker, pStep->pSelect);
1380 sqlite3WalkExpr(pWalker, pStep->pWhere);
1381 sqlite3WalkExprList(pWalker, pStep->pExprList);
1382 if( pStep->pUpsert ){
1383 Upsert *pUpsert = pStep->pUpsert;
1384 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1385 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1386 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1387 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1388 }
dan7a39fae2020-10-31 16:33:01 +00001389 if( pStep->pFrom ){
1390 int i;
1391 for(i=0; i<pStep->pFrom->nSrc; i++){
1392 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1393 }
1394 }
danc9461ec2018-08-29 21:00:16 +00001395 }
1396}
1397
dandd1a9c82018-09-05 08:28:30 +00001398/*
1399** Free the contents of Parse object (*pParse). Do not free the memory
1400** occupied by the Parse object itself.
1401*/
dan141e1192018-08-31 18:23:53 +00001402static void renameParseCleanup(Parse *pParse){
1403 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001404 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001405 if( pParse->pVdbe ){
1406 sqlite3VdbeFinalize(pParse->pVdbe);
1407 }
1408 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001409 while( (pIdx = pParse->pNewIndex)!=0 ){
1410 pParse->pNewIndex = pIdx->pNext;
1411 sqlite3FreeIndex(db, pIdx);
1412 }
dan141e1192018-08-31 18:23:53 +00001413 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1414 sqlite3DbFree(db, pParse->zErrMsg);
1415 renameTokenFree(db, pParse->pRename);
1416 sqlite3ParserReset(pParse);
1417}
1418
dan06249392018-08-21 15:06:59 +00001419/*
dan987db762018-08-14 20:18:50 +00001420** SQL function:
1421**
1422** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1423**
1424** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001425** 1. type: Type of object ("table", "view" etc.)
1426** 2. object: Name of object
1427** 3. Database: Database name (e.g. "main")
1428** 4. Table: Table name
1429** 5. iCol: Index of column to rename
1430** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001431** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001432** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001433**
1434** Do a column rename operation on the CREATE statement given in zSql.
1435** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1436** into zNew. The name should be quoted if bQuote is true.
1437**
1438** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001439** It is only accessible to SQL created using sqlite3NestedParse(). It is
1440** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001441*/
dancf8f2892018-08-09 20:47:01 +00001442static void renameColumnFunc(
1443 sqlite3_context *context,
1444 int NotUsed,
1445 sqlite3_value **argv
1446){
1447 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001448 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001449 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001450 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1451 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1452 int iCol = sqlite3_value_int(argv[5]);
1453 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001454 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001455 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001456 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001457 int rc;
dancf8f2892018-08-09 20:47:01 +00001458 Parse sParse;
1459 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001460 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001461 int i;
dan987db762018-08-14 20:18:50 +00001462 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001463#ifndef SQLITE_OMIT_AUTHORIZATION
1464 sqlite3_xauth xAuth = db->xAuth;
1465#endif
dancf8f2892018-08-09 20:47:01 +00001466
drh38d99642018-08-18 18:27:18 +00001467 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001468 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001469 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001470 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001471 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001472 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001473 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001474 if( pTab==0 || iCol>=pTab->nCol ){
1475 sqlite3BtreeLeaveAll(db);
1476 return;
1477 }
dan987db762018-08-14 20:18:50 +00001478 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001479 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001480 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001481
dan141e1192018-08-31 18:23:53 +00001482#ifndef SQLITE_OMIT_AUTHORIZATION
1483 db->xAuth = 0;
1484#endif
drhb2ab3dc2019-12-20 14:08:34 +00001485 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001486
dancf8f2892018-08-09 20:47:01 +00001487 /* Find tokens that need to be replaced. */
1488 memset(&sWalker, 0, sizeof(Walker));
1489 sWalker.pParse = &sParse;
1490 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001491 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001492 sWalker.u.pRename = &sCtx;
1493
dan0cbb0b12018-08-16 19:49:16 +00001494 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001495 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001496 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001497 Select *pSelect = sParse.pNewTable->pSelect;
1498 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001499 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001500 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001501 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001502 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1503 if( rc==SQLITE_OK ){
1504 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001505 }
dan987db762018-08-14 20:18:50 +00001506 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1507 }else{
1508 /* A regular table */
1509 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1510 FKey *pFKey;
1511 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001512 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001513 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001514 if( iCol<sParse.pNewTable->nCol ){
1515 renameTokenFind(
1516 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1517 );
1518 }
dan987db762018-08-14 20:18:50 +00001519 if( sCtx.iCol<0 ){
1520 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001521 }
dan987db762018-08-14 20:18:50 +00001522 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1523 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1524 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1525 }
drh885eeb62019-01-09 02:02:24 +00001526 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1527 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1528 }
drhb9bcf7c2019-10-19 13:29:10 +00001529#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001530 for(i=0; i<sParse.pNewTable->nCol; i++){
1531 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1532 }
drhb9bcf7c2019-10-19 13:29:10 +00001533#endif
dan776a5782021-03-16 11:11:07 +00001534 }
dan987db762018-08-14 20:18:50 +00001535
1536 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1537 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001538 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001539 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1540 }
1541 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1542 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1543 ){
1544 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1545 }
dan6fe7f232018-08-10 19:19:33 +00001546 }
dancf8f2892018-08-09 20:47:01 +00001547 }
1548 }
dan5496d6a2018-08-13 17:14:26 +00001549 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001550 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1551 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001552 }else{
dan5be60c52018-08-15 20:28:39 +00001553 /* A trigger */
1554 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001555 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001556 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001557
danc9461ec2018-08-29 21:00:16 +00001558 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1559 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001560 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001561 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001562 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001563 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1564 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001565 }
danc9461ec2018-08-29 21:00:16 +00001566 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1567 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001568 }
1569 }
1570 }
1571
dan5be60c52018-08-15 20:28:39 +00001572
1573 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001574 if( sParse.pTriggerTab==pTab ){
1575 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001576 }
dan5be60c52018-08-15 20:28:39 +00001577
danc9461ec2018-08-29 21:00:16 +00001578 /* Find tokens to edit in various expressions and selects */
1579 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001580 }
1581
dan987db762018-08-14 20:18:50 +00001582 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001583 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001584
drh5fc22cd2018-08-13 13:43:11 +00001585renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001586 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001587 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001588 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001589 }else{
1590 sqlite3_result_error_code(context, rc);
1591 }
1592 }
1593
dan141e1192018-08-31 18:23:53 +00001594 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001595 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001596#ifndef SQLITE_OMIT_AUTHORIZATION
1597 db->xAuth = xAuth;
1598#endif
drhda76adc2018-08-25 02:04:05 +00001599 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001600}
1601
dandd1a9c82018-09-05 08:28:30 +00001602/*
1603** Walker expression callback used by "RENAME TABLE".
1604*/
danc9461ec2018-08-29 21:00:16 +00001605static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1606 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001607 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1608 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001609 }
1610 return WRC_Continue;
1611}
1612
1613/*
dandd1a9c82018-09-05 08:28:30 +00001614** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001615*/
1616static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1617 int i;
1618 RenameCtx *p = pWalker->u.pRename;
1619 SrcList *pSrc = pSelect->pSrc;
danac67f562021-06-14 20:08:48 +00001620 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1621 testcase( pSelect->selFlags & SF_View );
1622 testcase( pSelect->selFlags & SF_CopyCte );
1623 return WRC_Prune;
1624 }
drh9da977f2021-04-20 12:14:12 +00001625 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001626 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001627 return WRC_Abort;
1628 }
danc9461ec2018-08-29 21:00:16 +00001629 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001630 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001631 if( pItem->pTab==p->pTab ){
1632 renameTokenFind(pWalker->pParse, p, pItem->zName);
1633 }
1634 }
danea412512018-12-05 13:49:04 +00001635 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001636
1637 return WRC_Continue;
1638}
1639
1640
1641/*
1642** This C function implements an SQL user function that is used by SQL code
1643** generated by the ALTER TABLE ... RENAME command to modify the definition
1644** of any foreign key constraints that use the table being renamed as the
1645** parent table. It is passed three arguments:
1646**
dan141e1192018-08-31 18:23:53 +00001647** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001648** 1. type: Type of object ("table", "view" etc.)
1649** 2. object: Name of object
1650** 3: The complete text of the schema statement being modified,
1651** 4: The old name of the table being renamed, and
1652** 5: The new name of the table being renamed.
1653** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001654**
dan141e1192018-08-31 18:23:53 +00001655** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001656**
dan141e1192018-08-31 18:23:53 +00001657** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001658** -> 'CREATE TABLE t1(a REFERENCES t3)'
1659*/
1660static void renameTableFunc(
1661 sqlite3_context *context,
1662 int NotUsed,
1663 sqlite3_value **argv
1664){
1665 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001666 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001667 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1668 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1669 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1670 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001671 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001672
dan141e1192018-08-31 18:23:53 +00001673 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001674 Parse sParse;
1675 int rc;
1676 int bQuote = 1;
1677 RenameCtx sCtx;
1678 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001679
dan141e1192018-08-31 18:23:53 +00001680#ifndef SQLITE_OMIT_AUTHORIZATION
1681 sqlite3_xauth xAuth = db->xAuth;
1682 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001683#endif
1684
dan141e1192018-08-31 18:23:53 +00001685 sqlite3BtreeEnterAll(db);
1686
1687 memset(&sCtx, 0, sizeof(RenameCtx));
1688 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1689 memset(&sWalker, 0, sizeof(Walker));
1690 sWalker.pParse = &sParse;
1691 sWalker.xExprCallback = renameTableExprCb;
1692 sWalker.xSelectCallback = renameTableSelectCb;
1693 sWalker.u.pRename = &sCtx;
1694
drhb2ab3dc2019-12-20 14:08:34 +00001695 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001696
1697 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001698 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001699 if( sParse.pNewTable ){
1700 Table *pTab = sParse.pNewTable;
1701
1702 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001703 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001704 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001705 NameContext sNC;
1706 memset(&sNC, 0, sizeof(sNC));
1707 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001708
dan38096962019-12-09 08:13:43 +00001709 assert( pSelect->selFlags & SF_View );
1710 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001711 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001712 if( sParse.nErr ){
1713 rc = sParse.rc;
1714 }else{
1715 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1716 }
dan674b8942018-09-20 08:28:01 +00001717 }
dan141e1192018-08-31 18:23:53 +00001718 }else{
1719 /* Modify any FK definitions to point to the new table. */
1720#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001721 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001722 FKey *pFKey;
1723 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1724 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1725 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1726 }
dan141e1192018-08-31 18:23:53 +00001727 }
1728 }
1729#endif
1730
1731 /* If this is the table being altered, fix any table refs in CHECK
1732 ** expressions. Also update the name that appears right after the
1733 ** "CREATE [VIRTUAL] TABLE" bit. */
1734 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1735 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001736 if( isLegacy==0 ){
1737 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1738 }
dan141e1192018-08-31 18:23:53 +00001739 renameTokenFind(&sParse, &sCtx, pTab->zName);
1740 }
danc9461ec2018-08-29 21:00:16 +00001741 }
1742 }
danc9461ec2018-08-29 21:00:16 +00001743
dan141e1192018-08-31 18:23:53 +00001744 else if( sParse.pNewIndex ){
1745 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001746 if( isLegacy==0 ){
1747 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1748 }
dan141e1192018-08-31 18:23:53 +00001749 }
danc9461ec2018-08-29 21:00:16 +00001750
1751#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001752 else{
dan141e1192018-08-31 18:23:53 +00001753 Trigger *pTrigger = sParse.pNewTrigger;
1754 TriggerStep *pStep;
1755 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1756 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1757 ){
1758 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1759 }
danc9461ec2018-08-29 21:00:16 +00001760
dan674b8942018-09-20 08:28:01 +00001761 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001762 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001763 if( rc==SQLITE_OK ){
1764 renameWalkTrigger(&sWalker, pTrigger);
1765 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1766 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1767 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1768 }
dan141e1192018-08-31 18:23:53 +00001769 }
dan0ccda962018-08-30 16:26:48 +00001770 }
danc9461ec2018-08-29 21:00:16 +00001771 }
1772 }
dan141e1192018-08-31 18:23:53 +00001773#endif
danc9461ec2018-08-29 21:00:16 +00001774 }
dan141e1192018-08-31 18:23:53 +00001775
1776 if( rc==SQLITE_OK ){
1777 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1778 }
1779 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001780 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001781 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001782 }else{
1783 sqlite3_result_error_code(context, rc);
1784 }
dan141e1192018-08-31 18:23:53 +00001785 }
1786
1787 renameParseCleanup(&sParse);
1788 renameTokenFree(db, sCtx.pList);
1789 sqlite3BtreeLeaveAll(db);
1790#ifndef SQLITE_OMIT_AUTHORIZATION
1791 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001792#endif
1793 }
1794
danc9461ec2018-08-29 21:00:16 +00001795 return;
1796}
1797
dan1e240722021-03-15 20:22:34 +00001798static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1799 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1800 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1801 }
1802 return WRC_Continue;
1803}
1804
1805/*
1806** The implementation of an SQL scalar function that rewrites DDL statements
1807** so that any string literals that use double-quotes are modified so that
1808** they use single quotes.
1809**
1810** Two arguments must be passed:
1811**
1812** 0: Database name ("main", "temp" etc.).
1813** 1: SQL statement to edit.
1814**
1815** The returned value is the modified SQL statement. For example, given
1816** the database schema:
1817**
1818** CREATE TABLE t1(a, b, c);
1819**
1820** SELECT sqlite_rename_quotefix('main',
1821** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1822** );
1823**
1824** returns the string:
1825**
1826** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1827*/
1828static void renameQuotefixFunc(
1829 sqlite3_context *context,
1830 int NotUsed,
1831 sqlite3_value **argv
1832){
1833 sqlite3 *db = sqlite3_context_db_handle(context);
1834 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1835 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1836
1837#ifndef SQLITE_OMIT_AUTHORIZATION
1838 sqlite3_xauth xAuth = db->xAuth;
1839 db->xAuth = 0;
1840#endif
1841
1842 sqlite3BtreeEnterAll(db);
1843
1844 UNUSED_PARAMETER(NotUsed);
1845 if( zDb && zInput ){
1846 int rc;
1847 Parse sParse;
1848 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1849
1850 if( rc==SQLITE_OK ){
1851 RenameCtx sCtx;
1852 Walker sWalker;
1853
1854 /* Walker to find tokens that need to be replaced. */
1855 memset(&sCtx, 0, sizeof(RenameCtx));
1856 memset(&sWalker, 0, sizeof(Walker));
1857 sWalker.pParse = &sParse;
1858 sWalker.xExprCallback = renameQuotefixExprCb;
1859 sWalker.xSelectCallback = renameColumnSelectCb;
1860 sWalker.u.pRename = &sCtx;
1861
1862 if( sParse.pNewTable ){
1863 Select *pSelect = sParse.pNewTable->pSelect;
1864 if( pSelect ){
1865 pSelect->selFlags &= ~SF_View;
1866 sParse.rc = SQLITE_OK;
1867 sqlite3SelectPrep(&sParse, pSelect, 0);
1868 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1869 if( rc==SQLITE_OK ){
1870 sqlite3WalkSelect(&sWalker, pSelect);
1871 }
1872 }else{
1873 int i;
1874 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1875#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1876 for(i=0; i<sParse.pNewTable->nCol; i++){
1877 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1878 }
1879#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1880 }
1881 }else if( sParse.pNewIndex ){
1882 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1883 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1884 }else{
1885#ifndef SQLITE_OMIT_TRIGGER
1886 rc = renameResolveTrigger(&sParse);
1887 if( rc==SQLITE_OK ){
1888 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1889 }
1890#endif /* SQLITE_OMIT_TRIGGER */
1891 }
1892
1893 if( rc==SQLITE_OK ){
1894 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1895 }
dan1fffa732021-03-16 18:24:49 +00001896 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001897 }
1898 if( rc!=SQLITE_OK ){
1899 sqlite3_result_error_code(context, rc);
1900 }
1901 renameParseCleanup(&sParse);
1902 }
1903
1904#ifndef SQLITE_OMIT_AUTHORIZATION
1905 db->xAuth = xAuth;
1906#endif
1907
1908 sqlite3BtreeLeaveAll(db);
1909}
1910
dandd1a9c82018-09-05 08:28:30 +00001911/*
1912** An SQL user function that checks that there are no parse or symbol
1913** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1914** After an ALTER TABLE .. RENAME operation is performed and the schema
1915** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001916** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001917**
1918** 0: Database name ("main", "temp" etc.).
1919** 1: SQL statement.
1920** 2: Object type ("view", "table", "trigger" or "index").
1921** 3: Object name.
1922** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001923** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001924** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001925**
1926** Unless it finds an error, this function normally returns NULL. However, it
1927** returns integer value 1 if:
1928**
1929** * the SQL argument creates a trigger, and
1930** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001931*/
dan9d324822018-08-30 20:03:44 +00001932static void renameTableTest(
1933 sqlite3_context *context,
1934 int NotUsed,
1935 sqlite3_value **argv
1936){
1937 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001938 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1939 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001940 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001941 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001942 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001943 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001944
dan141e1192018-08-31 18:23:53 +00001945#ifndef SQLITE_OMIT_AUTHORIZATION
1946 sqlite3_xauth xAuth = db->xAuth;
1947 db->xAuth = 0;
1948#endif
1949
drh5b1da302018-09-01 20:02:07 +00001950 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001951
dan09236502018-09-01 16:05:50 +00001952 if( zDb && zInput ){
1953 int rc;
1954 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001955 int flags = db->flags;
1956 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001957 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001958 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001959 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001960 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001961 NameContext sNC;
1962 memset(&sNC, 0, sizeof(sNC));
1963 sNC.pParse = &sParse;
1964 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1965 if( sParse.nErr ) rc = sParse.rc;
1966 }
1967
1968 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001969 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001970 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001971 }
drh3b700452018-09-07 19:12:08 +00001972 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001973 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1974 int i2 = sqlite3FindDbName(db, zDb);
1975 if( i1==i2 ) sqlite3_result_int(context, 1);
1976 }
dan09236502018-09-01 16:05:50 +00001977 }
dan9d324822018-08-30 20:03:44 +00001978 }
1979
dan16953462021-02-18 19:25:44 +00001980 if( rc!=SQLITE_OK && zWhen ){
1981 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001982 }
dan09236502018-09-01 16:05:50 +00001983 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001984 }
1985
dan141e1192018-08-31 18:23:53 +00001986#ifndef SQLITE_OMIT_AUTHORIZATION
1987 db->xAuth = xAuth;
1988#endif
dan9d324822018-08-30 20:03:44 +00001989}
1990
dancf8f2892018-08-09 20:47:01 +00001991/*
dan6a5a13d2021-02-17 20:08:22 +00001992** The implementation of internal UDF sqlite_drop_column().
1993**
dan6e6d9832021-02-16 20:43:36 +00001994** Arguments:
1995**
1996** argv[0]: An integer - the index of the schema containing the table
1997** argv[1]: CREATE TABLE statement to modify.
1998** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00001999**
2000** The value returned is a string containing the CREATE TABLE statement
2001** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00002002*/
2003static void dropColumnFunc(
2004 sqlite3_context *context,
2005 int NotUsed,
2006 sqlite3_value **argv
2007){
2008 sqlite3 *db = sqlite3_context_db_handle(context);
2009 int iSchema = sqlite3_value_int(argv[0]);
2010 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
2011 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00002012 const char *zDb = db->aDb[iSchema].zDbSName;
2013 int rc;
2014 Parse sParse;
2015 RenameToken *pCol;
2016 Table *pTab;
2017 const char *zEnd;
2018 char *zNew = 0;
2019
dan678f3b32021-02-18 20:27:46 +00002020#ifndef SQLITE_OMIT_AUTHORIZATION
2021 sqlite3_xauth xAuth = db->xAuth;
2022 db->xAuth = 0;
2023#endif
2024
drh05edf722021-03-04 19:44:01 +00002025 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00002026 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2027 if( rc!=SQLITE_OK ) goto drop_column_done;
2028 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002029 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002030 /* This can happen if the sqlite_schema table is corrupt */
2031 rc = SQLITE_CORRUPT_BKPT;
2032 goto drop_column_done;
2033 }
dan6e6d9832021-02-16 20:43:36 +00002034
2035 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
2036 if( iCol<pTab->nCol-1 ){
2037 RenameToken *pEnd;
2038 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
2039 zEnd = (const char*)pEnd->t.z;
2040 }else{
dan578277c2021-02-19 18:39:32 +00002041 zEnd = (const char*)&zSql[pTab->addColOffset];
drh60fe2352021-02-19 09:46:52 +00002042 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002043 }
2044
danc2a878e2021-02-17 20:46:44 +00002045 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002046 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2047 sqlite3_free(zNew);
2048
2049drop_column_done:
2050 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002051#ifndef SQLITE_OMIT_AUTHORIZATION
2052 db->xAuth = xAuth;
2053#endif
danf4a72782021-02-19 14:13:40 +00002054 if( rc!=SQLITE_OK ){
2055 sqlite3_result_error_code(context, rc);
2056 }
dan6e6d9832021-02-16 20:43:36 +00002057}
2058
dan6a5a13d2021-02-17 20:08:22 +00002059/*
2060** This function is called by the parser upon parsing an
2061**
2062** ALTER TABLE pSrc DROP COLUMN pName
2063**
2064** statement. Argument pSrc contains the possibly qualified name of the
2065** table being edited, and token pName the name of the column to drop.
2066*/
dan6e6d9832021-02-16 20:43:36 +00002067void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002068 sqlite3 *db = pParse->db; /* Database handle */
2069 Table *pTab; /* Table to modify */
2070 int iDb; /* Index of db containing pTab in aDb[] */
2071 const char *zDb; /* Database containing pTab ("main" etc.) */
2072 char *zCol = 0; /* Name of column to drop */
2073 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002074
2075 /* Look up the table being altered. */
2076 assert( pParse->pNewTable==0 );
2077 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002078 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002079 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2080 if( !pTab ) goto exit_drop_column;
2081
dan6a5a13d2021-02-17 20:08:22 +00002082 /* Make sure this is not an attempt to ALTER a view, virtual table or
2083 ** system table. */
2084 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2085 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002086
2087 /* Find the index of the column being dropped. */
2088 zCol = sqlite3NameFromToken(db, pName);
2089 if( zCol==0 ){
2090 assert( db->mallocFailed );
2091 goto exit_drop_column;
2092 }
2093 iCol = sqlite3ColumnIndex(pTab, zCol);
2094 if( iCol<0 ){
2095 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2096 goto exit_drop_column;
2097 }
2098
2099 /* Do not allow the user to drop a PRIMARY KEY column or a column
2100 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002101 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2102 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2103 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2104 zCol
2105 );
dan6e6d9832021-02-16 20:43:36 +00002106 goto exit_drop_column;
2107 }
dan6e6d9832021-02-16 20:43:36 +00002108
drh239c84f2021-02-19 09:09:07 +00002109 /* Do not allow the number of columns to go to zero */
2110 if( pTab->nCol<=1 ){
2111 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2112 goto exit_drop_column;
2113 }
2114
dan6a5a13d2021-02-17 20:08:22 +00002115 /* Edit the sqlite_schema table */
2116 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2117 assert( iDb>=0 );
2118 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002119 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2120 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002121 sqlite3NestedParse(pParse,
2122 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002123 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002124 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002125 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002126 );
2127
2128 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002129 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002130 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002131
2132 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002133 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002134 int i;
2135 int addr;
2136 int reg;
2137 int regRec;
2138 Index *pPk = 0;
2139 int nField = 0; /* Number of non-virtual columns after drop */
2140 int iCur;
2141 Vdbe *v = sqlite3GetVdbe(pParse);
2142 iCur = pParse->nTab++;
2143 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002144 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002145 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002146 if( HasRowid(pTab) ){
2147 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002148 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002149 }else{
2150 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002151 pParse->nMem += pPk->nColumn;
2152 for(i=0; i<pPk->nKeyCol; i++){
2153 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2154 }
2155 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002156 }
dancc263012021-04-06 21:20:39 +00002157 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002158 for(i=0; i<pTab->nCol; i++){
2159 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2160 int regOut;
2161 if( pPk ){
2162 int iPos = sqlite3TableColumnToIndex(pPk, i);
2163 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002164 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002165 regOut = reg+1+iPos-(iPos>iColPos);
2166 }else{
2167 regOut = reg+1+nField;
2168 }
dan0a746cc2021-04-18 05:30:39 +00002169 if( i==pTab->iPKey ){
2170 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2171 }else{
2172 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2173 }
dan6a5a13d2021-02-17 20:08:22 +00002174 nField++;
2175 }
2176 }
dan6a5a13d2021-02-17 20:08:22 +00002177 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2178 if( pPk ){
2179 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2180 }else{
2181 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2182 }
dan0a746cc2021-04-18 05:30:39 +00002183 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002184
drh03361402021-02-18 23:53:47 +00002185 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002186 sqlite3VdbeJumpHere(v, addr);
2187 }
dan6e6d9832021-02-16 20:43:36 +00002188
2189exit_drop_column:
2190 sqlite3DbFree(db, zCol);
2191 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002192}
2193
2194/*
dancf8f2892018-08-09 20:47:01 +00002195** Register built-in functions used to help implement ALTER TABLE
2196*/
2197void sqlite3AlterFunctions(void){
2198 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002199 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2200 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002201 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002202 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002203 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002204 };
2205 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2206}
drhd0e4a6c2005-02-15 20:47:57 +00002207#endif /* SQLITE_ALTER_TABLE */