blob: f1482cdf083423d9d1e9894f4570e4031b5c4810 [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
drh86396212016-07-14 19:13:11 +0000430 /* Make sure the schema version is at least 3. But do not upgrade
431 ** from less than 3 to 4, as that will corrupt any preexisting DESC
432 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000433 */
dan09236502018-09-01 16:05:50 +0000434 v = sqlite3GetVdbe(pParse);
435 if( v ){
436 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);
444 }
danielk197719a8e7e2005-03-17 05:03:38 +0000445
dan09236502018-09-01 16:05:50 +0000446 /* Reload the table definition */
dan6a5a13d2021-02-17 20:08:22 +0000447 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
danielk197719a8e7e2005-03-17 05:03:38 +0000448}
449
drhfdd6e852005-12-16 01:06:16 +0000450/*
danielk197719a8e7e2005-03-17 05:03:38 +0000451** This function is called by the parser after the table-name in
452** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
453** pSrc is the full-name of the table being altered.
454**
455** This routine makes a (partial) copy of the Table structure
456** for the table being altered and sets Parse.pNewTable to point
457** to it. Routines called by the parser as the column definition
458** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
459** the copy. The copy of the Table structure is deleted by tokenize.c
460** after parsing is finished.
461**
462** Routine sqlite3AlterFinishAddColumn() will be called to complete
463** coding the "ALTER TABLE ... ADD" statement.
464*/
465void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
466 Table *pNew;
467 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000468 int iDb;
469 int i;
470 int nAlloc;
drh17435752007-08-16 04:30:38 +0000471 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000472
473 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000474 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000475 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000476 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000477 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000478 if( !pTab ) goto exit_begin_add_column;
479
danielk19775ee9d692006-06-21 12:36:25 +0000480#ifndef SQLITE_OMIT_VIRTUALTABLE
481 if( IsVirtual(pTab) ){
482 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
483 goto exit_begin_add_column;
484 }
485#endif
486
danielk197719a8e7e2005-03-17 05:03:38 +0000487 /* Make sure this is not an attempt to ALTER a view. */
488 if( pTab->pSelect ){
489 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
490 goto exit_begin_add_column;
491 }
dan397a78d2018-12-18 20:31:14 +0000492 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000493 goto exit_begin_add_column;
494 }
danielk197719a8e7e2005-03-17 05:03:38 +0000495
dan03e025e2019-10-07 18:43:21 +0000496 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000497 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000498 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000499
500 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000501 ** sqlite3AddColumn() function and friends to modify. But modify
502 ** the name by adding an "sqlite_altertab_" prefix. By adding this
503 ** prefix, we insure that the name will not collide with an existing
504 ** table because user table are not allowed to have the "sqlite_"
505 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000506 */
drh17435752007-08-16 04:30:38 +0000507 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000508 if( !pNew ) goto exit_begin_add_column;
509 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000510 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000511 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000512 assert( pNew->nCol>0 );
513 nAlloc = (((pNew->nCol-1)/8)*8)+8;
514 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000515 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000516 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000517 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000518 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000519 goto exit_begin_add_column;
520 }
521 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
522 for(i=0; i<pNew->nCol; i++){
523 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000524 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000525 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000526 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000527 pCol->pDflt = 0;
528 }
drh17435752007-08-16 04:30:38 +0000529 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000530 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000531 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000532
danielk197719a8e7e2005-03-17 05:03:38 +0000533exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000534 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000535 return;
536}
dancf8f2892018-08-09 20:47:01 +0000537
drh4a2c7472018-08-13 15:09:48 +0000538/*
dan9d705572018-08-20 16:16:05 +0000539** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
540** command. This function checks if the table is a view or virtual
541** table (columns of views or virtual tables may not be renamed). If so,
542** it loads an error message into pParse and returns non-zero.
543**
544** Or, if pTab is not a view or virtual table, zero is returned.
545*/
546#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000547static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000548 const char *zType = 0;
549#ifndef SQLITE_OMIT_VIEW
550 if( pTab->pSelect ){
551 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000552 }
dan9d705572018-08-20 16:16:05 +0000553#endif
554#ifndef SQLITE_OMIT_VIRTUALTABLE
555 if( IsVirtual(pTab) ){
556 zType = "virtual table";
557 }
558#endif
559 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000560 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
561 (bDrop ? "drop column from" : "rename columns of"),
562 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000563 );
564 return 1;
565 }
566 return 0;
567}
568#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000569# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000570#endif
571
572/*
drh4a2c7472018-08-13 15:09:48 +0000573** Handles the following parser reduction:
574**
575** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
576*/
dancf8f2892018-08-09 20:47:01 +0000577void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000578 Parse *pParse, /* Parsing context */
579 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
580 Token *pOld, /* Name of column being changed */
581 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000582){
drh4a2c7472018-08-13 15:09:48 +0000583 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000584 Table *pTab; /* Table being updated */
585 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000586 char *zOld = 0; /* Old column name */
587 char *zNew = 0; /* New column name */
588 const char *zDb; /* Name of schema containing the table */
589 int iSchema; /* Index of the schema */
590 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000591
drh4a2c7472018-08-13 15:09:48 +0000592 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000593 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
594 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000595
596 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000597 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000598 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000599
600 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000601 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
602 assert( iSchema>=0 );
603 zDb = db->aDb[iSchema].zDbSName;
604
drh0d019b92018-08-25 16:14:46 +0000605#ifndef SQLITE_OMIT_AUTHORIZATION
606 /* Invoke the authorization callback. */
607 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
608 goto exit_rename_column;
609 }
610#endif
611
drh4a2c7472018-08-13 15:09:48 +0000612 /* Make sure the old name really is a column name in the table to be
613 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000614 zOld = sqlite3NameFromToken(db, pOld);
615 if( !zOld ) goto exit_rename_column;
616 for(iCol=0; iCol<pTab->nCol; iCol++){
617 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
618 }
619 if( iCol==pTab->nCol ){
620 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
621 goto exit_rename_column;
622 }
623
dan2ad080a2021-03-16 16:14:48 +0000624 /* Ensure the schema contains no double-quoted strings */
625 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
626 renameFixQuotes(pParse, zDb, iSchema==1);
627
drh4a2c7472018-08-13 15:09:48 +0000628 /* Do the rename operation using a recursive UPDATE statement that
629 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000630 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000631 */
dan1f3b2842019-03-15 16:17:32 +0000632 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000633 zNew = sqlite3NameFromToken(db, pNew);
634 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000635 assert( pNew->n>0 );
636 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000637 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000638 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000639 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000640 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
641 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000642 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000643 zDb,
danb87a9a82018-09-01 20:23:28 +0000644 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000645 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000646 );
647
dan9d324822018-08-30 20:03:44 +0000648 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000649 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000650 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000651 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000652 zDb, pTab->zName, iCol, zNew, bQuote
653 );
654
dane325ffe2018-08-11 13:40:20 +0000655 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000656 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000657 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000658
dancf8f2892018-08-09 20:47:01 +0000659 exit_rename_column:
660 sqlite3SrcListDelete(db, pSrc);
661 sqlite3DbFree(db, zOld);
662 sqlite3DbFree(db, zNew);
663 return;
664}
665
drh4a2c7472018-08-13 15:09:48 +0000666/*
667** Each RenameToken object maps an element of the parse tree into
668** the token that generated that element. The parse tree element
669** might be one of:
670**
671** * A pointer to an Expr that represents an ID
672** * The name of a table column in Column.zName
673**
674** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000675** Each new object is created by sqlite3RenameTokenMap().
676** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000677** routine is used to keep the mapping current.
678**
679** After the parse finishes, renameTokenFind() routine can be used
680** to look up the actual token value that created some element in
681** the parse tree.
682*/
dancf8f2892018-08-09 20:47:01 +0000683struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000684 void *p; /* Parse tree element created by token t */
685 Token t; /* The token that created parse tree element p */
686 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000687};
688
drh4a2c7472018-08-13 15:09:48 +0000689/*
690** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
691** down into the Walker.
692*/
dan5496d6a2018-08-13 17:14:26 +0000693typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000694struct RenameCtx {
695 RenameToken *pList; /* List of tokens to overwrite */
696 int nList; /* Number of tokens in pList */
697 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000698 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000699 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000700};
701
dan8900a482018-09-05 14:36:05 +0000702#ifdef SQLITE_DEBUG
703/*
704** This function is only for debugging. It performs two tasks:
705**
706** 1. Checks that pointer pPtr does not already appear in the
707** rename-token list.
708**
709** 2. Dereferences each pointer in the rename-token list.
710**
711** The second is most effective when debugging under valgrind or
712** address-sanitizer or similar. If any of these pointers no longer
713** point to valid objects, an exception is raised by the memory-checking
714** tool.
715**
716** The point of this is to prevent comparisons of invalid pointer values.
717** Even though this always seems to work, it is undefined according to the
718** C standard. Example of undefined comparison:
719**
720** sqlite3_free(x);
721** if( x==y ) ...
722**
723** Technically, as x no longer points into a valid object or to the byte
724** following a valid object, it may not be used in comparison operations.
725*/
drh16b870d2018-09-12 15:51:56 +0000726static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000727 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
728 RenameToken *p;
729 u8 i = 0;
730 for(p=pParse->pRename; p; p=p->pNext){
731 if( p->p ){
732 assert( p->p!=pPtr );
733 i += *(u8*)(p->p);
734 }
danc9461ec2018-08-29 21:00:16 +0000735 }
736 }
737}
dan8900a482018-09-05 14:36:05 +0000738#else
739# define renameTokenCheckAll(x,y)
740#endif
danc9461ec2018-08-29 21:00:16 +0000741
drh4a2c7472018-08-13 15:09:48 +0000742/*
drh49b269e2018-11-26 15:00:25 +0000743** Remember that the parser tree element pPtr was created using
744** the token pToken.
dan07e95232018-08-21 16:32:53 +0000745**
drh49b269e2018-11-26 15:00:25 +0000746** In other words, construct a new RenameToken object and add it
747** to the list of RenameToken objects currently being built up
748** in pParse->pRename.
749**
750** The pPtr argument is returned so that this routine can be used
751** with tail recursion in tokenExpr() routine, for a small performance
752** improvement.
drh4a2c7472018-08-13 15:09:48 +0000753*/
dan07e95232018-08-21 16:32:53 +0000754void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000755 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000756 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000757 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000758 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000759 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
760 if( pNew ){
761 pNew->p = pPtr;
762 pNew->t = *pToken;
763 pNew->pNext = pParse->pRename;
764 pParse->pRename = pNew;
765 }
dancf8f2892018-08-09 20:47:01 +0000766 }
danc9461ec2018-08-29 21:00:16 +0000767
dand145e5f2018-08-21 08:29:48 +0000768 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000769}
770
drh4a2c7472018-08-13 15:09:48 +0000771/*
dan07e95232018-08-21 16:32:53 +0000772** It is assumed that there is already a RenameToken object associated
773** with parse tree element pFrom. This function remaps the associated token
774** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000775*/
dan07e95232018-08-21 16:32:53 +0000776void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000777 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000778 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000779 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000780 if( p->p==pFrom ){
781 p->p = pTo;
782 break;
783 }
784 }
dancf8f2892018-08-09 20:47:01 +0000785}
786
drh4a2c7472018-08-13 15:09:48 +0000787/*
dan8900a482018-09-05 14:36:05 +0000788** Walker callback used by sqlite3RenameExprUnmap().
789*/
790static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
791 Parse *pParse = pWalker->pParse;
792 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
793 return WRC_Continue;
794}
795
796/*
dan8f407622019-12-04 14:26:38 +0000797** Iterate through the Select objects that are part of WITH clauses attached
798** to select statement pSelect.
799*/
800static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000801 With *pWith = pSelect->pWith;
802 if( pWith ){
dan26d61e52021-06-11 11:14:24 +0000803 Parse *pParse = pWalker->pParse;
dan8f407622019-12-04 14:26:38 +0000804 int i;
drh35e6cd02021-06-11 13:18:56 +0000805 With *pCopy = 0;
dan26d61e52021-06-11 11:14:24 +0000806 assert( pWith->nCte>0 );
drh35e6cd02021-06-11 13:18:56 +0000807 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
808 /* Push a copy of the With object onto the with-stack. We use a copy
809 ** here as the original will be expanded and resolved (flags SF_Expanded
810 ** and SF_Resolved) below. And the parser code that uses the with-stack
811 ** fails if the Select objects on it have already been expanded and
812 ** resolved. */
813 pCopy = sqlite3WithDup(pParse->db, pWith);
drh24ce9442021-06-12 17:45:32 +0000814 pCopy = sqlite3WithPush(pParse, pCopy, 1);
drh35e6cd02021-06-11 13:18:56 +0000815 }
816 for(i=0; i<pWith->nCte; i++){
817 Select *p = pWith->a[i].pSelect;
818 NameContext sNC;
819 memset(&sNC, 0, sizeof(sNC));
820 sNC.pParse = pParse;
821 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC);
822 sqlite3WalkSelect(pWalker, p);
823 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
824 }
825 if( pCopy && pParse->pWith==pCopy ){
dand03d3a92021-06-11 12:14:58 +0000826 pParse->pWith = pCopy->pOuter;
dan26d61e52021-06-11 11:14:24 +0000827 }
dan8f407622019-12-04 14:26:38 +0000828 }
829}
830
831/*
danfb99e382020-04-03 11:20:40 +0000832** Unmap all tokens in the IdList object passed as the second argument.
833*/
834static void unmapColumnIdlistNames(
835 Parse *pParse,
836 IdList *pIdList
837){
838 if( pIdList ){
839 int ii;
840 for(ii=0; ii<pIdList->nId; ii++){
841 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
842 }
843 }
844}
845
846/*
dan0b277a92019-06-11 12:03:10 +0000847** Walker callback used by sqlite3RenameExprUnmap().
848*/
849static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000850 Parse *pParse = pWalker->pParse;
851 int i;
drhd63b69b2019-12-04 15:08:58 +0000852 if( pParse->nErr ) return WRC_Abort;
danac67f562021-06-14 20:08:48 +0000853 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000854 testcase( p->selFlags & SF_View );
855 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000856 return WRC_Prune;
857 }
drhbdf4cf02019-06-15 15:21:49 +0000858 if( ALWAYS(p->pEList) ){
859 ExprList *pList = p->pEList;
860 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000861 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000862 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000863 }
864 }
865 }
drh2c3f4652019-06-11 16:43:58 +0000866 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000867 SrcList *pSrc = p->pSrc;
868 for(i=0; i<pSrc->nSrc; i++){
869 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000870 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000871 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000872 }
873 }
dan8f407622019-12-04 14:26:38 +0000874
875 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000876 return WRC_Continue;
877}
878
879/*
dan8900a482018-09-05 14:36:05 +0000880** Remove all nodes that are part of expression pExpr from the rename list.
881*/
882void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000883 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000884 Walker sWalker;
885 memset(&sWalker, 0, sizeof(Walker));
886 sWalker.pParse = pParse;
887 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000888 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000889 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000890 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000891 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000892}
893
894/*
dane8ab40d2018-09-12 08:51:48 +0000895** Remove all nodes that are part of expression-list pEList from the
896** rename list.
897*/
898void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
899 if( pEList ){
900 int i;
901 Walker sWalker;
902 memset(&sWalker, 0, sizeof(Walker));
903 sWalker.pParse = pParse;
904 sWalker.xExprCallback = renameUnmapExprCb;
905 sqlite3WalkExprList(&sWalker, pEList);
906 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000907 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000908 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
909 }
dane8ab40d2018-09-12 08:51:48 +0000910 }
911 }
912}
913
914/*
drh4a2c7472018-08-13 15:09:48 +0000915** Free the list of RenameToken objects given in the second argument
916*/
dancf8f2892018-08-09 20:47:01 +0000917static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
918 RenameToken *pNext;
919 RenameToken *p;
920 for(p=pToken; p; p=pNext){
921 pNext = p->pNext;
922 sqlite3DbFree(db, p);
923 }
924}
925
dan987db762018-08-14 20:18:50 +0000926/*
927** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000928** object associated with parse tree element pPtr. If found, return a pointer
929** to it. Otherwise, return NULL.
930**
931** If the second argument passed to this function is not NULL and a matching
932** RenameToken object is found, remove it from the Parse object and add it to
933** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000934*/
dan6e6d9832021-02-16 20:43:36 +0000935static RenameToken *renameTokenFind(
936 Parse *pParse,
937 struct RenameCtx *pCtx,
938 void *pPtr
939){
dancf8f2892018-08-09 20:47:01 +0000940 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000941 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000942 return 0;
943 }
dancf8f2892018-08-09 20:47:01 +0000944 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
945 if( (*pp)->p==pPtr ){
946 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000947 if( pCtx ){
948 *pp = pToken->pNext;
949 pToken->pNext = pCtx->pList;
950 pCtx->pList = pToken;
951 pCtx->nList++;
952 }
953 return pToken;
dancf8f2892018-08-09 20:47:01 +0000954 }
955 }
dan6e6d9832021-02-16 20:43:36 +0000956 return 0;
dancf8f2892018-08-09 20:47:01 +0000957}
958
dan24fedb92018-08-18 17:35:38 +0000959/*
960** This is a Walker select callback. It does nothing. It is only required
961** because without a dummy callback, sqlite3WalkExpr() and similar do not
962** descend into sub-select statements.
963*/
dan987db762018-08-14 20:18:50 +0000964static int renameColumnSelectCb(Walker *pWalker, Select *p){
danac67f562021-06-14 20:08:48 +0000965 if( p->selFlags & (SF_View|SF_CopyCte) ){
drh11e489d2021-06-14 20:49:33 +0000966 testcase( p->selFlags & SF_View );
967 testcase( p->selFlags & SF_CopyCte );
danac67f562021-06-14 20:08:48 +0000968 return WRC_Prune;
969 }
danea412512018-12-05 13:49:04 +0000970 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000971 return WRC_Continue;
972}
973
dan987db762018-08-14 20:18:50 +0000974/*
975** This is a Walker expression callback.
976**
977** For every TK_COLUMN node in the expression tree, search to see
978** if the column being references is the column being renamed by an
979** ALTER TABLE statement. If it is, then attach its associated
980** RenameToken object to the list of RenameToken objects being
981** constructed in RenameCtx object at pWalker->u.pRename.
982*/
dancf8f2892018-08-09 20:47:01 +0000983static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000984 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000985 if( pExpr->op==TK_TRIGGER
986 && pExpr->iColumn==p->iCol
987 && pWalker->pParse->pTriggerTab==p->pTab
988 ){
dan5be60c52018-08-15 20:28:39 +0000989 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000990 }else if( pExpr->op==TK_COLUMN
991 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000992 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000993 ){
dan5496d6a2018-08-13 17:14:26 +0000994 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000995 }
996 return WRC_Continue;
997}
998
dan987db762018-08-14 20:18:50 +0000999/*
1000** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001001** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001002** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001003** RenameContext. "Last" means the last RenameToken encountered when
1004** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001005** return all column name tokens in the order that they are encountered
1006** in the SQL statement.
1007*/
dan5496d6a2018-08-13 17:14:26 +00001008static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001009 RenameToken *pBest = pCtx->pList;
1010 RenameToken *pToken;
1011 RenameToken **pp;
1012
1013 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1014 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1015 }
1016 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1017 *pp = pBest->pNext;
1018
1019 return pBest;
1020}
1021
dan6fe7f232018-08-10 19:19:33 +00001022/*
dan24fedb92018-08-18 17:35:38 +00001023** An error occured while parsing or otherwise processing a database
1024** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1025** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1026** sub-routine is currently stored in pParse->zErrMsg. This function
1027** adds context to the error message and then stores it in pCtx.
1028*/
danb0137382018-08-20 20:01:01 +00001029static void renameColumnParseError(
1030 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001031 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001032 sqlite3_value *pType,
1033 sqlite3_value *pObject,
1034 Parse *pParse
1035){
drh79a5ee92018-08-23 19:32:04 +00001036 const char *zT = (const char*)sqlite3_value_text(pType);
1037 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001038 char *zErr;
danb0137382018-08-20 20:01:01 +00001039
dan16953462021-02-18 19:25:44 +00001040 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1041 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001042 pParse->zErrMsg
1043 );
dan24fedb92018-08-18 17:35:38 +00001044 sqlite3_result_error(pCtx, zErr, -1);
1045 sqlite3_free(zErr);
1046}
1047
1048/*
dan06249392018-08-21 15:06:59 +00001049** For each name in the the expression-list pEList (i.e. each
1050** pEList->a[i].zName) that matches the string in zOld, extract the
1051** corresponding rename-token from Parse object pParse and add it
1052** to the RenameCtx pCtx.
1053*/
1054static void renameColumnElistNames(
1055 Parse *pParse,
1056 RenameCtx *pCtx,
1057 ExprList *pEList,
1058 const char *zOld
1059){
1060 if( pEList ){
1061 int i;
1062 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001063 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001064 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1065 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001066 && 0==sqlite3_stricmp(zName, zOld)
1067 ){
dan06249392018-08-21 15:06:59 +00001068 renameTokenFind(pParse, pCtx, (void*)zName);
1069 }
1070 }
1071 }
1072}
1073
1074/*
1075** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1076** that matches the string in zOld, extract the corresponding rename-token
1077** from Parse object pParse and add it to the RenameCtx pCtx.
1078*/
1079static void renameColumnIdlistNames(
1080 Parse *pParse,
1081 RenameCtx *pCtx,
1082 IdList *pIdList,
1083 const char *zOld
1084){
1085 if( pIdList ){
1086 int i;
1087 for(i=0; i<pIdList->nId; i++){
1088 char *zName = pIdList->a[i].zName;
1089 if( 0==sqlite3_stricmp(zName, zOld) ){
1090 renameTokenFind(pParse, pCtx, (void*)zName);
1091 }
1092 }
1093 }
1094}
1095
danfb99e382020-04-03 11:20:40 +00001096
dandd1a9c82018-09-05 08:28:30 +00001097/*
1098** Parse the SQL statement zSql using Parse object (*p). The Parse object
1099** is initialized by this function before it is used.
1100*/
danc9461ec2018-08-29 21:00:16 +00001101static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001102 Parse *p, /* Memory to use for Parse object */
1103 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001104 sqlite3 *db, /* Database handle */
1105 const char *zSql, /* SQL to parse */
1106 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001107){
1108 int rc;
1109 char *zErr = 0;
1110
1111 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1112
1113 /* Parse the SQL statement passed as the first argument. If no error
1114 ** occurs and the parse does not result in a new table, index or
1115 ** trigger object, the database must be corrupt. */
1116 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001117 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001118 p->db = db;
1119 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001120 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001121 assert( p->zErrMsg==0 );
1122 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001123 p->zErrMsg = zErr;
1124 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1125 if( rc==SQLITE_OK
1126 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1127 ){
1128 rc = SQLITE_CORRUPT_BKPT;
1129 }
1130
1131#ifdef SQLITE_DEBUG
1132 /* Ensure that all mappings in the Parse.pRename list really do map to
1133 ** a part of the input string. */
1134 if( rc==SQLITE_OK ){
1135 int nSql = sqlite3Strlen30(zSql);
1136 RenameToken *pToken;
1137 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1138 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1139 }
1140 }
1141#endif
1142
1143 db->init.iDb = 0;
1144 return rc;
1145}
1146
dandd1a9c82018-09-05 08:28:30 +00001147/*
1148** This function edits SQL statement zSql, replacing each token identified
1149** by the linked list pRename with the text of zNew. If argument bQuote is
1150** true, then zNew is always quoted first. If no error occurs, the result
1151** is loaded into context object pCtx as the result.
1152**
1153** Or, if an error occurs (i.e. an OOM condition), an error is left in
1154** pCtx and an SQLite error code returned.
1155*/
danc9461ec2018-08-29 21:00:16 +00001156static int renameEditSql(
1157 sqlite3_context *pCtx, /* Return result here */
1158 RenameCtx *pRename, /* Rename context */
1159 const char *zSql, /* SQL statement to edit */
1160 const char *zNew, /* New token text */
1161 int bQuote /* True to always quote token */
1162){
1163 int nNew = sqlite3Strlen30(zNew);
1164 int nSql = sqlite3Strlen30(zSql);
1165 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1166 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001167 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001168 char *zOut;
drh29821b42021-03-24 17:04:32 +00001169 int nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001170 char *zBuf1 = 0;
1171 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001172
dan1e240722021-03-15 20:22:34 +00001173 if( zNew ){
1174 /* Set zQuot to point to a buffer containing a quoted copy of the
1175 ** identifier zNew. If the corresponding identifier in the original
1176 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1177 ** point to zQuot so that all substitutions are made using the
1178 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001179 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001180 if( zQuot==0 ){
1181 return SQLITE_NOMEM;
1182 }else{
dan1d14ffe2021-03-23 22:15:34 +00001183 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001184 }
1185
1186 assert( nQuot>=nNew );
1187 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001188 }else{
dan1e240722021-03-15 20:22:34 +00001189 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1190 if( zOut ){
1191 zBuf1 = &zOut[nSql*2+1];
1192 zBuf2 = &zOut[nSql*4+2];
1193 }
danc9461ec2018-08-29 21:00:16 +00001194 }
1195
1196 /* At this point pRename->pList contains a list of RenameToken objects
1197 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001198 ** with the new column name, or with single-quoted versions of themselves.
1199 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001200 if( zOut ){
1201 int nOut = nSql;
1202 memcpy(zOut, zSql, nSql);
1203 while( pRename->pList ){
1204 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001205 u32 nReplace;
1206 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001207 RenameToken *pBest = renameColumnTokenNext(pRename);
1208
1209 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001210 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001211 nReplace = nNew;
1212 zReplace = zNew;
1213 }else{
1214 nReplace = nQuot;
1215 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001216 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001217 }
danc9461ec2018-08-29 21:00:16 +00001218 }else{
dan1e240722021-03-15 20:22:34 +00001219 /* Dequote the double-quoted token. Then requote it again, this time
1220 ** using single quotes. If the character immediately following the
1221 ** original token within the input SQL was a single quote ('), then
1222 ** add another space after the new, single-quoted version of the
1223 ** token. This is so that (SELECT "string"'alias') maps to
1224 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1225 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1226 zBuf1[pBest->t.n] = 0;
1227 sqlite3Dequote(zBuf1);
1228 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1229 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1230 );
1231 zReplace = zBuf2;
1232 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001233 }
1234
1235 iOff = pBest->t.z - zSql;
1236 if( pBest->t.n!=nReplace ){
1237 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1238 nOut - (iOff + pBest->t.n)
1239 );
1240 nOut += nReplace - pBest->t.n;
1241 zOut[nOut] = '\0';
1242 }
1243 memcpy(&zOut[iOff], zReplace, nReplace);
1244 sqlite3DbFree(db, pBest);
1245 }
1246
1247 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1248 sqlite3DbFree(db, zOut);
1249 }else{
1250 rc = SQLITE_NOMEM;
1251 }
1252
1253 sqlite3_free(zQuot);
1254 return rc;
1255}
1256
dandd1a9c82018-09-05 08:28:30 +00001257/*
1258** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1259** it was read from the schema of database zDb. Return SQLITE_OK if
1260** successful. Otherwise, return an SQLite error code and leave an error
1261** message in the Parse object.
1262*/
drha7c74002020-07-18 18:44:59 +00001263static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001264 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001265 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001266 TriggerStep *pStep;
1267 NameContext sNC;
1268 int rc = SQLITE_OK;
1269
1270 memset(&sNC, 0, sizeof(sNC));
1271 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001272 assert( pNew->pTabSchema );
1273 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1274 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1275 );
1276 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001277 /* ALWAYS() because if the table of the trigger does not exist, the
1278 ** error would have been hit before this point */
1279 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001280 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1281 }
danc9461ec2018-08-29 21:00:16 +00001282
1283 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001284 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001285 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001286 }
1287
dand5e6fef2018-09-07 15:50:31 +00001288 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001289 if( pStep->pSelect ){
1290 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1291 if( pParse->nErr ) rc = pParse->rc;
1292 }
dand5e6fef2018-09-07 15:50:31 +00001293 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001294 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1295 if( pSrc ){
1296 int i;
drha3e64952020-08-12 16:19:12 +00001297 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001298 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001299 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001300 if( p->pSelect ){
1301 sqlite3SelectPrep(pParse, p->pSelect, 0);
1302 sqlite3ExpandSubquery(pParse, p);
1303 assert( i>0 );
1304 assert( pStep->pFrom->a[i-1].pSelect );
1305 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001306 }else{
dan7a39fae2020-10-31 16:33:01 +00001307 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1308 if( p->pTab==0 ){
1309 rc = SQLITE_ERROR;
1310 }else{
1311 p->pTab->nTabRef++;
1312 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1313 }
dane7877b22020-07-14 19:51:01 +00001314 }
1315 }
1316 sNC.pSrcList = pSrc;
1317 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001318 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1319 }
1320 if( rc==SQLITE_OK ){
1321 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1322 }
1323 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001324 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001325 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001326 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001327 sNC.uNC.pUpsert = pUpsert;
1328 sNC.ncFlags = NC_UUpsert;
1329 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1330 if( rc==SQLITE_OK ){
1331 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1332 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1333 }
1334 if( rc==SQLITE_OK ){
1335 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1336 }
1337 if( rc==SQLITE_OK ){
1338 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1339 }
1340 sNC.ncFlags = 0;
1341 }
dan0e14e982019-01-18 16:06:18 +00001342 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001343 sqlite3SrcListDelete(db, pSrc);
1344 }else{
1345 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001346 }
1347 }
1348 }
1349 return rc;
1350}
1351
dandd1a9c82018-09-05 08:28:30 +00001352/*
1353** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1354** objects that are part of the trigger passed as the second argument.
1355*/
danc9461ec2018-08-29 21:00:16 +00001356static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1357 TriggerStep *pStep;
1358
1359 /* Find tokens to edit in WHEN clause */
1360 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1361
1362 /* Find tokens to edit in trigger steps */
1363 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1364 sqlite3WalkSelect(pWalker, pStep->pSelect);
1365 sqlite3WalkExpr(pWalker, pStep->pWhere);
1366 sqlite3WalkExprList(pWalker, pStep->pExprList);
1367 if( pStep->pUpsert ){
1368 Upsert *pUpsert = pStep->pUpsert;
1369 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1370 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1371 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1372 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1373 }
dan7a39fae2020-10-31 16:33:01 +00001374 if( pStep->pFrom ){
1375 int i;
1376 for(i=0; i<pStep->pFrom->nSrc; i++){
1377 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1378 }
1379 }
danc9461ec2018-08-29 21:00:16 +00001380 }
1381}
1382
dandd1a9c82018-09-05 08:28:30 +00001383/*
1384** Free the contents of Parse object (*pParse). Do not free the memory
1385** occupied by the Parse object itself.
1386*/
dan141e1192018-08-31 18:23:53 +00001387static void renameParseCleanup(Parse *pParse){
1388 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001389 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001390 if( pParse->pVdbe ){
1391 sqlite3VdbeFinalize(pParse->pVdbe);
1392 }
1393 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001394 while( (pIdx = pParse->pNewIndex)!=0 ){
1395 pParse->pNewIndex = pIdx->pNext;
1396 sqlite3FreeIndex(db, pIdx);
1397 }
dan141e1192018-08-31 18:23:53 +00001398 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1399 sqlite3DbFree(db, pParse->zErrMsg);
1400 renameTokenFree(db, pParse->pRename);
1401 sqlite3ParserReset(pParse);
1402}
1403
dan06249392018-08-21 15:06:59 +00001404/*
dan987db762018-08-14 20:18:50 +00001405** SQL function:
1406**
1407** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1408**
1409** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001410** 1. type: Type of object ("table", "view" etc.)
1411** 2. object: Name of object
1412** 3. Database: Database name (e.g. "main")
1413** 4. Table: Table name
1414** 5. iCol: Index of column to rename
1415** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001416** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001417** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001418**
1419** Do a column rename operation on the CREATE statement given in zSql.
1420** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1421** into zNew. The name should be quoted if bQuote is true.
1422**
1423** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001424** It is only accessible to SQL created using sqlite3NestedParse(). It is
1425** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001426*/
dancf8f2892018-08-09 20:47:01 +00001427static void renameColumnFunc(
1428 sqlite3_context *context,
1429 int NotUsed,
1430 sqlite3_value **argv
1431){
1432 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001433 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001434 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001435 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1436 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1437 int iCol = sqlite3_value_int(argv[5]);
1438 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001439 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001440 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001441 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001442 int rc;
dancf8f2892018-08-09 20:47:01 +00001443 Parse sParse;
1444 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001445 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001446 int i;
dan987db762018-08-14 20:18:50 +00001447 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001448#ifndef SQLITE_OMIT_AUTHORIZATION
1449 sqlite3_xauth xAuth = db->xAuth;
1450#endif
dancf8f2892018-08-09 20:47:01 +00001451
drh38d99642018-08-18 18:27:18 +00001452 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001453 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001454 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001455 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001456 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001457 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001458 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001459 if( pTab==0 || iCol>=pTab->nCol ){
1460 sqlite3BtreeLeaveAll(db);
1461 return;
1462 }
dan987db762018-08-14 20:18:50 +00001463 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001464 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001465 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001466
dan141e1192018-08-31 18:23:53 +00001467#ifndef SQLITE_OMIT_AUTHORIZATION
1468 db->xAuth = 0;
1469#endif
drhb2ab3dc2019-12-20 14:08:34 +00001470 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001471
dancf8f2892018-08-09 20:47:01 +00001472 /* Find tokens that need to be replaced. */
1473 memset(&sWalker, 0, sizeof(Walker));
1474 sWalker.pParse = &sParse;
1475 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001476 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001477 sWalker.u.pRename = &sCtx;
1478
dan0cbb0b12018-08-16 19:49:16 +00001479 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001480 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001481 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001482 Select *pSelect = sParse.pNewTable->pSelect;
1483 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001484 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001485 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001486 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001487 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1488 if( rc==SQLITE_OK ){
1489 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001490 }
dan987db762018-08-14 20:18:50 +00001491 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1492 }else{
1493 /* A regular table */
1494 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1495 FKey *pFKey;
1496 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001497 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001498 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001499 if( iCol<sParse.pNewTable->nCol ){
1500 renameTokenFind(
1501 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1502 );
1503 }
dan987db762018-08-14 20:18:50 +00001504 if( sCtx.iCol<0 ){
1505 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001506 }
dan987db762018-08-14 20:18:50 +00001507 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1508 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1509 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1510 }
drh885eeb62019-01-09 02:02:24 +00001511 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1512 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1513 }
drhb9bcf7c2019-10-19 13:29:10 +00001514#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001515 for(i=0; i<sParse.pNewTable->nCol; i++){
1516 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1517 }
drhb9bcf7c2019-10-19 13:29:10 +00001518#endif
dan776a5782021-03-16 11:11:07 +00001519 }
dan987db762018-08-14 20:18:50 +00001520
1521 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1522 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001523 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001524 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1525 }
1526 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1527 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1528 ){
1529 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1530 }
dan6fe7f232018-08-10 19:19:33 +00001531 }
dancf8f2892018-08-09 20:47:01 +00001532 }
1533 }
dan5496d6a2018-08-13 17:14:26 +00001534 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001535 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1536 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001537 }else{
dan5be60c52018-08-15 20:28:39 +00001538 /* A trigger */
1539 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001540 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001541 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001542
danc9461ec2018-08-29 21:00:16 +00001543 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1544 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001545 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001546 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001547 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001548 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1549 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001550 }
danc9461ec2018-08-29 21:00:16 +00001551 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1552 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001553 }
1554 }
1555 }
1556
dan5be60c52018-08-15 20:28:39 +00001557
1558 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001559 if( sParse.pTriggerTab==pTab ){
1560 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001561 }
dan5be60c52018-08-15 20:28:39 +00001562
danc9461ec2018-08-29 21:00:16 +00001563 /* Find tokens to edit in various expressions and selects */
1564 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001565 }
1566
dan987db762018-08-14 20:18:50 +00001567 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001568 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001569
drh5fc22cd2018-08-13 13:43:11 +00001570renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001571 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001572 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001573 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001574 }else{
1575 sqlite3_result_error_code(context, rc);
1576 }
1577 }
1578
dan141e1192018-08-31 18:23:53 +00001579 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001580 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001581#ifndef SQLITE_OMIT_AUTHORIZATION
1582 db->xAuth = xAuth;
1583#endif
drhda76adc2018-08-25 02:04:05 +00001584 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001585}
1586
dandd1a9c82018-09-05 08:28:30 +00001587/*
1588** Walker expression callback used by "RENAME TABLE".
1589*/
danc9461ec2018-08-29 21:00:16 +00001590static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1591 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001592 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1593 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001594 }
1595 return WRC_Continue;
1596}
1597
1598/*
dandd1a9c82018-09-05 08:28:30 +00001599** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001600*/
1601static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1602 int i;
1603 RenameCtx *p = pWalker->u.pRename;
1604 SrcList *pSrc = pSelect->pSrc;
danac67f562021-06-14 20:08:48 +00001605 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
1606 testcase( pSelect->selFlags & SF_View );
1607 testcase( pSelect->selFlags & SF_CopyCte );
1608 return WRC_Prune;
1609 }
drh9da977f2021-04-20 12:14:12 +00001610 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001611 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001612 return WRC_Abort;
1613 }
danc9461ec2018-08-29 21:00:16 +00001614 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001615 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001616 if( pItem->pTab==p->pTab ){
1617 renameTokenFind(pWalker->pParse, p, pItem->zName);
1618 }
1619 }
danea412512018-12-05 13:49:04 +00001620 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001621
1622 return WRC_Continue;
1623}
1624
1625
1626/*
1627** This C function implements an SQL user function that is used by SQL code
1628** generated by the ALTER TABLE ... RENAME command to modify the definition
1629** of any foreign key constraints that use the table being renamed as the
1630** parent table. It is passed three arguments:
1631**
dan141e1192018-08-31 18:23:53 +00001632** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001633** 1. type: Type of object ("table", "view" etc.)
1634** 2. object: Name of object
1635** 3: The complete text of the schema statement being modified,
1636** 4: The old name of the table being renamed, and
1637** 5: The new name of the table being renamed.
1638** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001639**
dan141e1192018-08-31 18:23:53 +00001640** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001641**
dan141e1192018-08-31 18:23:53 +00001642** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001643** -> 'CREATE TABLE t1(a REFERENCES t3)'
1644*/
1645static void renameTableFunc(
1646 sqlite3_context *context,
1647 int NotUsed,
1648 sqlite3_value **argv
1649){
1650 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001651 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001652 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1653 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1654 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1655 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001656 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001657
dan141e1192018-08-31 18:23:53 +00001658 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001659 Parse sParse;
1660 int rc;
1661 int bQuote = 1;
1662 RenameCtx sCtx;
1663 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001664
dan141e1192018-08-31 18:23:53 +00001665#ifndef SQLITE_OMIT_AUTHORIZATION
1666 sqlite3_xauth xAuth = db->xAuth;
1667 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001668#endif
1669
dan141e1192018-08-31 18:23:53 +00001670 sqlite3BtreeEnterAll(db);
1671
1672 memset(&sCtx, 0, sizeof(RenameCtx));
1673 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1674 memset(&sWalker, 0, sizeof(Walker));
1675 sWalker.pParse = &sParse;
1676 sWalker.xExprCallback = renameTableExprCb;
1677 sWalker.xSelectCallback = renameTableSelectCb;
1678 sWalker.u.pRename = &sCtx;
1679
drhb2ab3dc2019-12-20 14:08:34 +00001680 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001681
1682 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001683 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001684 if( sParse.pNewTable ){
1685 Table *pTab = sParse.pNewTable;
1686
1687 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001688 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001689 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001690 NameContext sNC;
1691 memset(&sNC, 0, sizeof(sNC));
1692 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001693
dan38096962019-12-09 08:13:43 +00001694 assert( pSelect->selFlags & SF_View );
1695 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001696 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001697 if( sParse.nErr ){
1698 rc = sParse.rc;
1699 }else{
1700 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1701 }
dan674b8942018-09-20 08:28:01 +00001702 }
dan141e1192018-08-31 18:23:53 +00001703 }else{
1704 /* Modify any FK definitions to point to the new table. */
1705#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001706 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001707 FKey *pFKey;
1708 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1709 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1710 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1711 }
dan141e1192018-08-31 18:23:53 +00001712 }
1713 }
1714#endif
1715
1716 /* If this is the table being altered, fix any table refs in CHECK
1717 ** expressions. Also update the name that appears right after the
1718 ** "CREATE [VIRTUAL] TABLE" bit. */
1719 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1720 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001721 if( isLegacy==0 ){
1722 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1723 }
dan141e1192018-08-31 18:23:53 +00001724 renameTokenFind(&sParse, &sCtx, pTab->zName);
1725 }
danc9461ec2018-08-29 21:00:16 +00001726 }
1727 }
danc9461ec2018-08-29 21:00:16 +00001728
dan141e1192018-08-31 18:23:53 +00001729 else if( sParse.pNewIndex ){
1730 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001731 if( isLegacy==0 ){
1732 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1733 }
dan141e1192018-08-31 18:23:53 +00001734 }
danc9461ec2018-08-29 21:00:16 +00001735
1736#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001737 else{
dan141e1192018-08-31 18:23:53 +00001738 Trigger *pTrigger = sParse.pNewTrigger;
1739 TriggerStep *pStep;
1740 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1741 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1742 ){
1743 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1744 }
danc9461ec2018-08-29 21:00:16 +00001745
dan674b8942018-09-20 08:28:01 +00001746 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001747 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001748 if( rc==SQLITE_OK ){
1749 renameWalkTrigger(&sWalker, pTrigger);
1750 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1751 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1752 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1753 }
dan141e1192018-08-31 18:23:53 +00001754 }
dan0ccda962018-08-30 16:26:48 +00001755 }
danc9461ec2018-08-29 21:00:16 +00001756 }
1757 }
dan141e1192018-08-31 18:23:53 +00001758#endif
danc9461ec2018-08-29 21:00:16 +00001759 }
dan141e1192018-08-31 18:23:53 +00001760
1761 if( rc==SQLITE_OK ){
1762 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1763 }
1764 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001765 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001766 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001767 }else{
1768 sqlite3_result_error_code(context, rc);
1769 }
dan141e1192018-08-31 18:23:53 +00001770 }
1771
1772 renameParseCleanup(&sParse);
1773 renameTokenFree(db, sCtx.pList);
1774 sqlite3BtreeLeaveAll(db);
1775#ifndef SQLITE_OMIT_AUTHORIZATION
1776 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001777#endif
1778 }
1779
danc9461ec2018-08-29 21:00:16 +00001780 return;
1781}
1782
dan1e240722021-03-15 20:22:34 +00001783static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1784 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1785 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1786 }
1787 return WRC_Continue;
1788}
1789
1790/*
1791** The implementation of an SQL scalar function that rewrites DDL statements
1792** so that any string literals that use double-quotes are modified so that
1793** they use single quotes.
1794**
1795** Two arguments must be passed:
1796**
1797** 0: Database name ("main", "temp" etc.).
1798** 1: SQL statement to edit.
1799**
1800** The returned value is the modified SQL statement. For example, given
1801** the database schema:
1802**
1803** CREATE TABLE t1(a, b, c);
1804**
1805** SELECT sqlite_rename_quotefix('main',
1806** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1807** );
1808**
1809** returns the string:
1810**
1811** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1812*/
1813static void renameQuotefixFunc(
1814 sqlite3_context *context,
1815 int NotUsed,
1816 sqlite3_value **argv
1817){
1818 sqlite3 *db = sqlite3_context_db_handle(context);
1819 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1820 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1821
1822#ifndef SQLITE_OMIT_AUTHORIZATION
1823 sqlite3_xauth xAuth = db->xAuth;
1824 db->xAuth = 0;
1825#endif
1826
1827 sqlite3BtreeEnterAll(db);
1828
1829 UNUSED_PARAMETER(NotUsed);
1830 if( zDb && zInput ){
1831 int rc;
1832 Parse sParse;
1833 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1834
1835 if( rc==SQLITE_OK ){
1836 RenameCtx sCtx;
1837 Walker sWalker;
1838
1839 /* Walker to find tokens that need to be replaced. */
1840 memset(&sCtx, 0, sizeof(RenameCtx));
1841 memset(&sWalker, 0, sizeof(Walker));
1842 sWalker.pParse = &sParse;
1843 sWalker.xExprCallback = renameQuotefixExprCb;
1844 sWalker.xSelectCallback = renameColumnSelectCb;
1845 sWalker.u.pRename = &sCtx;
1846
1847 if( sParse.pNewTable ){
1848 Select *pSelect = sParse.pNewTable->pSelect;
1849 if( pSelect ){
1850 pSelect->selFlags &= ~SF_View;
1851 sParse.rc = SQLITE_OK;
1852 sqlite3SelectPrep(&sParse, pSelect, 0);
1853 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1854 if( rc==SQLITE_OK ){
1855 sqlite3WalkSelect(&sWalker, pSelect);
1856 }
1857 }else{
1858 int i;
1859 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1860#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1861 for(i=0; i<sParse.pNewTable->nCol; i++){
1862 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1863 }
1864#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1865 }
1866 }else if( sParse.pNewIndex ){
1867 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1868 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1869 }else{
1870#ifndef SQLITE_OMIT_TRIGGER
1871 rc = renameResolveTrigger(&sParse);
1872 if( rc==SQLITE_OK ){
1873 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1874 }
1875#endif /* SQLITE_OMIT_TRIGGER */
1876 }
1877
1878 if( rc==SQLITE_OK ){
1879 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1880 }
dan1fffa732021-03-16 18:24:49 +00001881 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001882 }
1883 if( rc!=SQLITE_OK ){
1884 sqlite3_result_error_code(context, rc);
1885 }
1886 renameParseCleanup(&sParse);
1887 }
1888
1889#ifndef SQLITE_OMIT_AUTHORIZATION
1890 db->xAuth = xAuth;
1891#endif
1892
1893 sqlite3BtreeLeaveAll(db);
1894}
1895
dandd1a9c82018-09-05 08:28:30 +00001896/*
1897** An SQL user function that checks that there are no parse or symbol
1898** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1899** After an ALTER TABLE .. RENAME operation is performed and the schema
1900** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001901** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001902**
1903** 0: Database name ("main", "temp" etc.).
1904** 1: SQL statement.
1905** 2: Object type ("view", "table", "trigger" or "index").
1906** 3: Object name.
1907** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001908** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001909** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001910**
1911** Unless it finds an error, this function normally returns NULL. However, it
1912** returns integer value 1 if:
1913**
1914** * the SQL argument creates a trigger, and
1915** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001916*/
dan9d324822018-08-30 20:03:44 +00001917static void renameTableTest(
1918 sqlite3_context *context,
1919 int NotUsed,
1920 sqlite3_value **argv
1921){
1922 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001923 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1924 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001925 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001926 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001927 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001928 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001929
dan141e1192018-08-31 18:23:53 +00001930#ifndef SQLITE_OMIT_AUTHORIZATION
1931 sqlite3_xauth xAuth = db->xAuth;
1932 db->xAuth = 0;
1933#endif
1934
drh5b1da302018-09-01 20:02:07 +00001935 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001936
dan09236502018-09-01 16:05:50 +00001937 if( zDb && zInput ){
1938 int rc;
1939 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001940 int flags = db->flags;
1941 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001942 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001943 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001944 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001945 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001946 NameContext sNC;
1947 memset(&sNC, 0, sizeof(sNC));
1948 sNC.pParse = &sParse;
1949 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1950 if( sParse.nErr ) rc = sParse.rc;
1951 }
1952
1953 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001954 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001955 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001956 }
drh3b700452018-09-07 19:12:08 +00001957 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001958 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1959 int i2 = sqlite3FindDbName(db, zDb);
1960 if( i1==i2 ) sqlite3_result_int(context, 1);
1961 }
dan09236502018-09-01 16:05:50 +00001962 }
dan9d324822018-08-30 20:03:44 +00001963 }
1964
dan16953462021-02-18 19:25:44 +00001965 if( rc!=SQLITE_OK && zWhen ){
1966 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001967 }
dan09236502018-09-01 16:05:50 +00001968 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001969 }
1970
dan141e1192018-08-31 18:23:53 +00001971#ifndef SQLITE_OMIT_AUTHORIZATION
1972 db->xAuth = xAuth;
1973#endif
dan9d324822018-08-30 20:03:44 +00001974}
1975
dancf8f2892018-08-09 20:47:01 +00001976/*
dan6a5a13d2021-02-17 20:08:22 +00001977** The implementation of internal UDF sqlite_drop_column().
1978**
dan6e6d9832021-02-16 20:43:36 +00001979** Arguments:
1980**
1981** argv[0]: An integer - the index of the schema containing the table
1982** argv[1]: CREATE TABLE statement to modify.
1983** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00001984**
1985** The value returned is a string containing the CREATE TABLE statement
1986** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00001987*/
1988static void dropColumnFunc(
1989 sqlite3_context *context,
1990 int NotUsed,
1991 sqlite3_value **argv
1992){
1993 sqlite3 *db = sqlite3_context_db_handle(context);
1994 int iSchema = sqlite3_value_int(argv[0]);
1995 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1996 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00001997 const char *zDb = db->aDb[iSchema].zDbSName;
1998 int rc;
1999 Parse sParse;
2000 RenameToken *pCol;
2001 Table *pTab;
2002 const char *zEnd;
2003 char *zNew = 0;
2004
dan678f3b32021-02-18 20:27:46 +00002005#ifndef SQLITE_OMIT_AUTHORIZATION
2006 sqlite3_xauth xAuth = db->xAuth;
2007 db->xAuth = 0;
2008#endif
2009
drh05edf722021-03-04 19:44:01 +00002010 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00002011 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2012 if( rc!=SQLITE_OK ) goto drop_column_done;
2013 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002014 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002015 /* This can happen if the sqlite_schema table is corrupt */
2016 rc = SQLITE_CORRUPT_BKPT;
2017 goto drop_column_done;
2018 }
dan6e6d9832021-02-16 20:43:36 +00002019
2020 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
2021 if( iCol<pTab->nCol-1 ){
2022 RenameToken *pEnd;
2023 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
2024 zEnd = (const char*)pEnd->t.z;
2025 }else{
dan578277c2021-02-19 18:39:32 +00002026 zEnd = (const char*)&zSql[pTab->addColOffset];
drh60fe2352021-02-19 09:46:52 +00002027 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002028 }
2029
danc2a878e2021-02-17 20:46:44 +00002030 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002031 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2032 sqlite3_free(zNew);
2033
2034drop_column_done:
2035 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002036#ifndef SQLITE_OMIT_AUTHORIZATION
2037 db->xAuth = xAuth;
2038#endif
danf4a72782021-02-19 14:13:40 +00002039 if( rc!=SQLITE_OK ){
2040 sqlite3_result_error_code(context, rc);
2041 }
dan6e6d9832021-02-16 20:43:36 +00002042}
2043
dan6a5a13d2021-02-17 20:08:22 +00002044/*
2045** This function is called by the parser upon parsing an
2046**
2047** ALTER TABLE pSrc DROP COLUMN pName
2048**
2049** statement. Argument pSrc contains the possibly qualified name of the
2050** table being edited, and token pName the name of the column to drop.
2051*/
dan6e6d9832021-02-16 20:43:36 +00002052void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002053 sqlite3 *db = pParse->db; /* Database handle */
2054 Table *pTab; /* Table to modify */
2055 int iDb; /* Index of db containing pTab in aDb[] */
2056 const char *zDb; /* Database containing pTab ("main" etc.) */
2057 char *zCol = 0; /* Name of column to drop */
2058 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002059
2060 /* Look up the table being altered. */
2061 assert( pParse->pNewTable==0 );
2062 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002063 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002064 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2065 if( !pTab ) goto exit_drop_column;
2066
dan6a5a13d2021-02-17 20:08:22 +00002067 /* Make sure this is not an attempt to ALTER a view, virtual table or
2068 ** system table. */
2069 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2070 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002071
2072 /* Find the index of the column being dropped. */
2073 zCol = sqlite3NameFromToken(db, pName);
2074 if( zCol==0 ){
2075 assert( db->mallocFailed );
2076 goto exit_drop_column;
2077 }
2078 iCol = sqlite3ColumnIndex(pTab, zCol);
2079 if( iCol<0 ){
2080 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2081 goto exit_drop_column;
2082 }
2083
2084 /* Do not allow the user to drop a PRIMARY KEY column or a column
2085 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002086 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2087 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2088 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2089 zCol
2090 );
dan6e6d9832021-02-16 20:43:36 +00002091 goto exit_drop_column;
2092 }
dan6e6d9832021-02-16 20:43:36 +00002093
drh239c84f2021-02-19 09:09:07 +00002094 /* Do not allow the number of columns to go to zero */
2095 if( pTab->nCol<=1 ){
2096 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2097 goto exit_drop_column;
2098 }
2099
dan6a5a13d2021-02-17 20:08:22 +00002100 /* Edit the sqlite_schema table */
2101 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2102 assert( iDb>=0 );
2103 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002104 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2105 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002106 sqlite3NestedParse(pParse,
2107 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002108 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002109 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002110 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002111 );
2112
2113 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002114 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002115 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002116
2117 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002118 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002119 int i;
2120 int addr;
2121 int reg;
2122 int regRec;
2123 Index *pPk = 0;
2124 int nField = 0; /* Number of non-virtual columns after drop */
2125 int iCur;
2126 Vdbe *v = sqlite3GetVdbe(pParse);
2127 iCur = pParse->nTab++;
2128 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002129 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002130 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002131 if( HasRowid(pTab) ){
2132 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002133 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002134 }else{
2135 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002136 pParse->nMem += pPk->nColumn;
2137 for(i=0; i<pPk->nKeyCol; i++){
2138 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2139 }
2140 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002141 }
dancc263012021-04-06 21:20:39 +00002142 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002143 for(i=0; i<pTab->nCol; i++){
2144 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2145 int regOut;
2146 if( pPk ){
2147 int iPos = sqlite3TableColumnToIndex(pPk, i);
2148 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002149 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002150 regOut = reg+1+iPos-(iPos>iColPos);
2151 }else{
2152 regOut = reg+1+nField;
2153 }
dan0a746cc2021-04-18 05:30:39 +00002154 if( i==pTab->iPKey ){
2155 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2156 }else{
2157 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2158 }
dan6a5a13d2021-02-17 20:08:22 +00002159 nField++;
2160 }
2161 }
dan6a5a13d2021-02-17 20:08:22 +00002162 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2163 if( pPk ){
2164 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2165 }else{
2166 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2167 }
dan0a746cc2021-04-18 05:30:39 +00002168 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002169
drh03361402021-02-18 23:53:47 +00002170 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002171 sqlite3VdbeJumpHere(v, addr);
2172 }
dan6e6d9832021-02-16 20:43:36 +00002173
2174exit_drop_column:
2175 sqlite3DbFree(db, zCol);
2176 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002177}
2178
2179/*
dancf8f2892018-08-09 20:47:01 +00002180** Register built-in functions used to help implement ALTER TABLE
2181*/
2182void sqlite3AlterFunctions(void){
2183 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002184 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2185 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002186 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002187 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002188 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002189 };
2190 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2191}
drhd0e4a6c2005-02-15 20:47:57 +00002192#endif /* SQLITE_ALTER_TABLE */