blob: de0dd4e4d4f8179ba1004046caed48d456a50706 [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);
dand03d3a92021-06-11 12:14:58 +0000814 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;
drh736d11e2021-05-01 12:09:36 +0000853 if( p->selFlags & SF_View ) return WRC_Prune;
drhbdf4cf02019-06-15 15:21:49 +0000854 if( ALWAYS(p->pEList) ){
855 ExprList *pList = p->pEList;
856 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000857 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000858 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000859 }
860 }
861 }
drh2c3f4652019-06-11 16:43:58 +0000862 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000863 SrcList *pSrc = p->pSrc;
864 for(i=0; i<pSrc->nSrc; i++){
865 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000866 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000867 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000868 }
869 }
dan8f407622019-12-04 14:26:38 +0000870
871 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000872 return WRC_Continue;
873}
874
875/*
dan8900a482018-09-05 14:36:05 +0000876** Remove all nodes that are part of expression pExpr from the rename list.
877*/
878void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000879 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000880 Walker sWalker;
881 memset(&sWalker, 0, sizeof(Walker));
882 sWalker.pParse = pParse;
883 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000884 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000885 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000886 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000887 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000888}
889
890/*
dane8ab40d2018-09-12 08:51:48 +0000891** Remove all nodes that are part of expression-list pEList from the
892** rename list.
893*/
894void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
895 if( pEList ){
896 int i;
897 Walker sWalker;
898 memset(&sWalker, 0, sizeof(Walker));
899 sWalker.pParse = pParse;
900 sWalker.xExprCallback = renameUnmapExprCb;
901 sqlite3WalkExprList(&sWalker, pEList);
902 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000903 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000904 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
905 }
dane8ab40d2018-09-12 08:51:48 +0000906 }
907 }
908}
909
910/*
drh4a2c7472018-08-13 15:09:48 +0000911** Free the list of RenameToken objects given in the second argument
912*/
dancf8f2892018-08-09 20:47:01 +0000913static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
914 RenameToken *pNext;
915 RenameToken *p;
916 for(p=pToken; p; p=pNext){
917 pNext = p->pNext;
918 sqlite3DbFree(db, p);
919 }
920}
921
dan987db762018-08-14 20:18:50 +0000922/*
923** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000924** object associated with parse tree element pPtr. If found, return a pointer
925** to it. Otherwise, return NULL.
926**
927** If the second argument passed to this function is not NULL and a matching
928** RenameToken object is found, remove it from the Parse object and add it to
929** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000930*/
dan6e6d9832021-02-16 20:43:36 +0000931static RenameToken *renameTokenFind(
932 Parse *pParse,
933 struct RenameCtx *pCtx,
934 void *pPtr
935){
dancf8f2892018-08-09 20:47:01 +0000936 RenameToken **pp;
drh06258a42021-06-04 23:26:56 +0000937 if( NEVER(pPtr==0) ){
drh65b93052021-04-22 16:54:34 +0000938 return 0;
939 }
dancf8f2892018-08-09 20:47:01 +0000940 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
941 if( (*pp)->p==pPtr ){
942 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000943 if( pCtx ){
944 *pp = pToken->pNext;
945 pToken->pNext = pCtx->pList;
946 pCtx->pList = pToken;
947 pCtx->nList++;
948 }
949 return pToken;
dancf8f2892018-08-09 20:47:01 +0000950 }
951 }
dan6e6d9832021-02-16 20:43:36 +0000952 return 0;
dancf8f2892018-08-09 20:47:01 +0000953}
954
dan24fedb92018-08-18 17:35:38 +0000955/*
956** This is a Walker select callback. It does nothing. It is only required
957** because without a dummy callback, sqlite3WalkExpr() and similar do not
958** descend into sub-select statements.
959*/
dan987db762018-08-14 20:18:50 +0000960static int renameColumnSelectCb(Walker *pWalker, Select *p){
dan38096962019-12-09 08:13:43 +0000961 if( p->selFlags & SF_View ) return WRC_Prune;
danea412512018-12-05 13:49:04 +0000962 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000963 return WRC_Continue;
964}
965
dan987db762018-08-14 20:18:50 +0000966/*
967** This is a Walker expression callback.
968**
969** For every TK_COLUMN node in the expression tree, search to see
970** if the column being references is the column being renamed by an
971** ALTER TABLE statement. If it is, then attach its associated
972** RenameToken object to the list of RenameToken objects being
973** constructed in RenameCtx object at pWalker->u.pRename.
974*/
dancf8f2892018-08-09 20:47:01 +0000975static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000976 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000977 if( pExpr->op==TK_TRIGGER
978 && pExpr->iColumn==p->iCol
979 && pWalker->pParse->pTriggerTab==p->pTab
980 ){
dan5be60c52018-08-15 20:28:39 +0000981 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000982 }else if( pExpr->op==TK_COLUMN
983 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000984 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000985 ){
dan5496d6a2018-08-13 17:14:26 +0000986 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000987 }
988 return WRC_Continue;
989}
990
dan987db762018-08-14 20:18:50 +0000991/*
992** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000993** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000994** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000995** RenameContext. "Last" means the last RenameToken encountered when
996** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000997** return all column name tokens in the order that they are encountered
998** in the SQL statement.
999*/
dan5496d6a2018-08-13 17:14:26 +00001000static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001001 RenameToken *pBest = pCtx->pList;
1002 RenameToken *pToken;
1003 RenameToken **pp;
1004
1005 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1006 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1007 }
1008 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1009 *pp = pBest->pNext;
1010
1011 return pBest;
1012}
1013
dan6fe7f232018-08-10 19:19:33 +00001014/*
dan24fedb92018-08-18 17:35:38 +00001015** An error occured while parsing or otherwise processing a database
1016** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1017** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1018** sub-routine is currently stored in pParse->zErrMsg. This function
1019** adds context to the error message and then stores it in pCtx.
1020*/
danb0137382018-08-20 20:01:01 +00001021static void renameColumnParseError(
1022 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001023 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001024 sqlite3_value *pType,
1025 sqlite3_value *pObject,
1026 Parse *pParse
1027){
drh79a5ee92018-08-23 19:32:04 +00001028 const char *zT = (const char*)sqlite3_value_text(pType);
1029 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001030 char *zErr;
danb0137382018-08-20 20:01:01 +00001031
dan16953462021-02-18 19:25:44 +00001032 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1033 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001034 pParse->zErrMsg
1035 );
dan24fedb92018-08-18 17:35:38 +00001036 sqlite3_result_error(pCtx, zErr, -1);
1037 sqlite3_free(zErr);
1038}
1039
1040/*
dan06249392018-08-21 15:06:59 +00001041** For each name in the the expression-list pEList (i.e. each
1042** pEList->a[i].zName) that matches the string in zOld, extract the
1043** corresponding rename-token from Parse object pParse and add it
1044** to the RenameCtx pCtx.
1045*/
1046static void renameColumnElistNames(
1047 Parse *pParse,
1048 RenameCtx *pCtx,
1049 ExprList *pEList,
1050 const char *zOld
1051){
1052 if( pEList ){
1053 int i;
1054 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001055 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001056 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1057 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001058 && 0==sqlite3_stricmp(zName, zOld)
1059 ){
dan06249392018-08-21 15:06:59 +00001060 renameTokenFind(pParse, pCtx, (void*)zName);
1061 }
1062 }
1063 }
1064}
1065
1066/*
1067** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1068** that matches the string in zOld, extract the corresponding rename-token
1069** from Parse object pParse and add it to the RenameCtx pCtx.
1070*/
1071static void renameColumnIdlistNames(
1072 Parse *pParse,
1073 RenameCtx *pCtx,
1074 IdList *pIdList,
1075 const char *zOld
1076){
1077 if( pIdList ){
1078 int i;
1079 for(i=0; i<pIdList->nId; i++){
1080 char *zName = pIdList->a[i].zName;
1081 if( 0==sqlite3_stricmp(zName, zOld) ){
1082 renameTokenFind(pParse, pCtx, (void*)zName);
1083 }
1084 }
1085 }
1086}
1087
danfb99e382020-04-03 11:20:40 +00001088
dandd1a9c82018-09-05 08:28:30 +00001089/*
1090** Parse the SQL statement zSql using Parse object (*p). The Parse object
1091** is initialized by this function before it is used.
1092*/
danc9461ec2018-08-29 21:00:16 +00001093static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001094 Parse *p, /* Memory to use for Parse object */
1095 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001096 sqlite3 *db, /* Database handle */
1097 const char *zSql, /* SQL to parse */
1098 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001099){
1100 int rc;
1101 char *zErr = 0;
1102
1103 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1104
1105 /* Parse the SQL statement passed as the first argument. If no error
1106 ** occurs and the parse does not result in a new table, index or
1107 ** trigger object, the database must be corrupt. */
1108 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001109 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001110 p->db = db;
1111 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001112 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001113 assert( p->zErrMsg==0 );
1114 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001115 p->zErrMsg = zErr;
1116 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1117 if( rc==SQLITE_OK
1118 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1119 ){
1120 rc = SQLITE_CORRUPT_BKPT;
1121 }
1122
1123#ifdef SQLITE_DEBUG
1124 /* Ensure that all mappings in the Parse.pRename list really do map to
1125 ** a part of the input string. */
1126 if( rc==SQLITE_OK ){
1127 int nSql = sqlite3Strlen30(zSql);
1128 RenameToken *pToken;
1129 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1130 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1131 }
1132 }
1133#endif
1134
1135 db->init.iDb = 0;
1136 return rc;
1137}
1138
dandd1a9c82018-09-05 08:28:30 +00001139/*
1140** This function edits SQL statement zSql, replacing each token identified
1141** by the linked list pRename with the text of zNew. If argument bQuote is
1142** true, then zNew is always quoted first. If no error occurs, the result
1143** is loaded into context object pCtx as the result.
1144**
1145** Or, if an error occurs (i.e. an OOM condition), an error is left in
1146** pCtx and an SQLite error code returned.
1147*/
danc9461ec2018-08-29 21:00:16 +00001148static int renameEditSql(
1149 sqlite3_context *pCtx, /* Return result here */
1150 RenameCtx *pRename, /* Rename context */
1151 const char *zSql, /* SQL statement to edit */
1152 const char *zNew, /* New token text */
1153 int bQuote /* True to always quote token */
1154){
1155 int nNew = sqlite3Strlen30(zNew);
1156 int nSql = sqlite3Strlen30(zSql);
1157 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1158 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001159 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001160 char *zOut;
drh29821b42021-03-24 17:04:32 +00001161 int nQuot = 0;
dan1e240722021-03-15 20:22:34 +00001162 char *zBuf1 = 0;
1163 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001164
dan1e240722021-03-15 20:22:34 +00001165 if( zNew ){
1166 /* Set zQuot to point to a buffer containing a quoted copy of the
1167 ** identifier zNew. If the corresponding identifier in the original
1168 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1169 ** point to zQuot so that all substitutions are made using the
1170 ** quoted version of the new column name. */
dan1d14ffe2021-03-23 22:15:34 +00001171 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew);
dan1e240722021-03-15 20:22:34 +00001172 if( zQuot==0 ){
1173 return SQLITE_NOMEM;
1174 }else{
dan1d14ffe2021-03-23 22:15:34 +00001175 nQuot = sqlite3Strlen30(zQuot)-1;
dan1e240722021-03-15 20:22:34 +00001176 }
1177
1178 assert( nQuot>=nNew );
1179 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001180 }else{
dan1e240722021-03-15 20:22:34 +00001181 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1182 if( zOut ){
1183 zBuf1 = &zOut[nSql*2+1];
1184 zBuf2 = &zOut[nSql*4+2];
1185 }
danc9461ec2018-08-29 21:00:16 +00001186 }
1187
1188 /* At this point pRename->pList contains a list of RenameToken objects
1189 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001190 ** with the new column name, or with single-quoted versions of themselves.
1191 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001192 if( zOut ){
1193 int nOut = nSql;
1194 memcpy(zOut, zSql, nSql);
1195 while( pRename->pList ){
1196 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001197 u32 nReplace;
1198 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001199 RenameToken *pBest = renameColumnTokenNext(pRename);
1200
1201 if( zNew ){
dan1d14ffe2021-03-23 22:15:34 +00001202 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
dan1e240722021-03-15 20:22:34 +00001203 nReplace = nNew;
1204 zReplace = zNew;
1205 }else{
1206 nReplace = nQuot;
1207 zReplace = zQuot;
dan1d14ffe2021-03-23 22:15:34 +00001208 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
dan1e240722021-03-15 20:22:34 +00001209 }
danc9461ec2018-08-29 21:00:16 +00001210 }else{
dan1e240722021-03-15 20:22:34 +00001211 /* Dequote the double-quoted token. Then requote it again, this time
1212 ** using single quotes. If the character immediately following the
1213 ** original token within the input SQL was a single quote ('), then
1214 ** add another space after the new, single-quoted version of the
1215 ** token. This is so that (SELECT "string"'alias') maps to
1216 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1217 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1218 zBuf1[pBest->t.n] = 0;
1219 sqlite3Dequote(zBuf1);
1220 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1221 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1222 );
1223 zReplace = zBuf2;
1224 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001225 }
1226
1227 iOff = pBest->t.z - zSql;
1228 if( pBest->t.n!=nReplace ){
1229 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1230 nOut - (iOff + pBest->t.n)
1231 );
1232 nOut += nReplace - pBest->t.n;
1233 zOut[nOut] = '\0';
1234 }
1235 memcpy(&zOut[iOff], zReplace, nReplace);
1236 sqlite3DbFree(db, pBest);
1237 }
1238
1239 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1240 sqlite3DbFree(db, zOut);
1241 }else{
1242 rc = SQLITE_NOMEM;
1243 }
1244
1245 sqlite3_free(zQuot);
1246 return rc;
1247}
1248
dandd1a9c82018-09-05 08:28:30 +00001249/*
1250** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1251** it was read from the schema of database zDb. Return SQLITE_OK if
1252** successful. Otherwise, return an SQLite error code and leave an error
1253** message in the Parse object.
1254*/
drha7c74002020-07-18 18:44:59 +00001255static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001256 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001257 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001258 TriggerStep *pStep;
1259 NameContext sNC;
1260 int rc = SQLITE_OK;
1261
1262 memset(&sNC, 0, sizeof(sNC));
1263 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001264 assert( pNew->pTabSchema );
1265 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1266 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1267 );
1268 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001269 /* ALWAYS() because if the table of the trigger does not exist, the
1270 ** error would have been hit before this point */
1271 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001272 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1273 }
danc9461ec2018-08-29 21:00:16 +00001274
1275 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001276 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001277 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001278 }
1279
dand5e6fef2018-09-07 15:50:31 +00001280 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001281 if( pStep->pSelect ){
1282 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1283 if( pParse->nErr ) rc = pParse->rc;
1284 }
dand5e6fef2018-09-07 15:50:31 +00001285 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001286 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1287 if( pSrc ){
1288 int i;
drha3e64952020-08-12 16:19:12 +00001289 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001290 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001291 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001292 if( p->pSelect ){
1293 sqlite3SelectPrep(pParse, p->pSelect, 0);
1294 sqlite3ExpandSubquery(pParse, p);
1295 assert( i>0 );
1296 assert( pStep->pFrom->a[i-1].pSelect );
1297 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001298 }else{
dan7a39fae2020-10-31 16:33:01 +00001299 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1300 if( p->pTab==0 ){
1301 rc = SQLITE_ERROR;
1302 }else{
1303 p->pTab->nTabRef++;
1304 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1305 }
dane7877b22020-07-14 19:51:01 +00001306 }
1307 }
1308 sNC.pSrcList = pSrc;
1309 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001310 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1311 }
1312 if( rc==SQLITE_OK ){
1313 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1314 }
1315 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001316 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001317 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001318 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001319 sNC.uNC.pUpsert = pUpsert;
1320 sNC.ncFlags = NC_UUpsert;
1321 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1322 if( rc==SQLITE_OK ){
1323 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1324 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1325 }
1326 if( rc==SQLITE_OK ){
1327 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1328 }
1329 if( rc==SQLITE_OK ){
1330 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1331 }
1332 sNC.ncFlags = 0;
1333 }
dan0e14e982019-01-18 16:06:18 +00001334 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001335 sqlite3SrcListDelete(db, pSrc);
1336 }else{
1337 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001338 }
1339 }
1340 }
1341 return rc;
1342}
1343
dandd1a9c82018-09-05 08:28:30 +00001344/*
1345** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1346** objects that are part of the trigger passed as the second argument.
1347*/
danc9461ec2018-08-29 21:00:16 +00001348static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1349 TriggerStep *pStep;
1350
1351 /* Find tokens to edit in WHEN clause */
1352 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1353
1354 /* Find tokens to edit in trigger steps */
1355 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1356 sqlite3WalkSelect(pWalker, pStep->pSelect);
1357 sqlite3WalkExpr(pWalker, pStep->pWhere);
1358 sqlite3WalkExprList(pWalker, pStep->pExprList);
1359 if( pStep->pUpsert ){
1360 Upsert *pUpsert = pStep->pUpsert;
1361 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1362 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1363 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1364 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1365 }
dan7a39fae2020-10-31 16:33:01 +00001366 if( pStep->pFrom ){
1367 int i;
1368 for(i=0; i<pStep->pFrom->nSrc; i++){
1369 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1370 }
1371 }
danc9461ec2018-08-29 21:00:16 +00001372 }
1373}
1374
dandd1a9c82018-09-05 08:28:30 +00001375/*
1376** Free the contents of Parse object (*pParse). Do not free the memory
1377** occupied by the Parse object itself.
1378*/
dan141e1192018-08-31 18:23:53 +00001379static void renameParseCleanup(Parse *pParse){
1380 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001381 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001382 if( pParse->pVdbe ){
1383 sqlite3VdbeFinalize(pParse->pVdbe);
1384 }
1385 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001386 while( (pIdx = pParse->pNewIndex)!=0 ){
1387 pParse->pNewIndex = pIdx->pNext;
1388 sqlite3FreeIndex(db, pIdx);
1389 }
dan141e1192018-08-31 18:23:53 +00001390 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1391 sqlite3DbFree(db, pParse->zErrMsg);
1392 renameTokenFree(db, pParse->pRename);
1393 sqlite3ParserReset(pParse);
1394}
1395
dan06249392018-08-21 15:06:59 +00001396/*
dan987db762018-08-14 20:18:50 +00001397** SQL function:
1398**
1399** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1400**
1401** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001402** 1. type: Type of object ("table", "view" etc.)
1403** 2. object: Name of object
1404** 3. Database: Database name (e.g. "main")
1405** 4. Table: Table name
1406** 5. iCol: Index of column to rename
1407** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001408** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001409** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001410**
1411** Do a column rename operation on the CREATE statement given in zSql.
1412** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1413** into zNew. The name should be quoted if bQuote is true.
1414**
1415** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001416** It is only accessible to SQL created using sqlite3NestedParse(). It is
1417** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001418*/
dancf8f2892018-08-09 20:47:01 +00001419static void renameColumnFunc(
1420 sqlite3_context *context,
1421 int NotUsed,
1422 sqlite3_value **argv
1423){
1424 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001425 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001426 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001427 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1428 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1429 int iCol = sqlite3_value_int(argv[5]);
1430 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001431 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001432 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001433 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001434 int rc;
dancf8f2892018-08-09 20:47:01 +00001435 Parse sParse;
1436 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001437 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001438 int i;
dan987db762018-08-14 20:18:50 +00001439 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001440#ifndef SQLITE_OMIT_AUTHORIZATION
1441 sqlite3_xauth xAuth = db->xAuth;
1442#endif
dancf8f2892018-08-09 20:47:01 +00001443
drh38d99642018-08-18 18:27:18 +00001444 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001445 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001446 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001447 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001448 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001449 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001450 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001451 if( pTab==0 || iCol>=pTab->nCol ){
1452 sqlite3BtreeLeaveAll(db);
1453 return;
1454 }
dan987db762018-08-14 20:18:50 +00001455 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001456 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001457 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001458
dan141e1192018-08-31 18:23:53 +00001459#ifndef SQLITE_OMIT_AUTHORIZATION
1460 db->xAuth = 0;
1461#endif
drhb2ab3dc2019-12-20 14:08:34 +00001462 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001463
dancf8f2892018-08-09 20:47:01 +00001464 /* Find tokens that need to be replaced. */
1465 memset(&sWalker, 0, sizeof(Walker));
1466 sWalker.pParse = &sParse;
1467 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001468 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001469 sWalker.u.pRename = &sCtx;
1470
dan0cbb0b12018-08-16 19:49:16 +00001471 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001472 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001473 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001474 Select *pSelect = sParse.pNewTable->pSelect;
1475 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001476 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001477 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001478 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001479 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1480 if( rc==SQLITE_OK ){
1481 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001482 }
dan987db762018-08-14 20:18:50 +00001483 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1484 }else{
1485 /* A regular table */
1486 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1487 FKey *pFKey;
1488 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001489 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001490 if( bFKOnly==0 ){
drh06258a42021-06-04 23:26:56 +00001491 if( iCol<sParse.pNewTable->nCol ){
1492 renameTokenFind(
1493 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1494 );
1495 }
dan987db762018-08-14 20:18:50 +00001496 if( sCtx.iCol<0 ){
1497 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001498 }
dan987db762018-08-14 20:18:50 +00001499 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1500 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1501 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1502 }
drh885eeb62019-01-09 02:02:24 +00001503 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1504 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1505 }
drhb9bcf7c2019-10-19 13:29:10 +00001506#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001507 for(i=0; i<sParse.pNewTable->nCol; i++){
1508 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1509 }
drhb9bcf7c2019-10-19 13:29:10 +00001510#endif
dan776a5782021-03-16 11:11:07 +00001511 }
dan987db762018-08-14 20:18:50 +00001512
1513 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1514 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001515 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001516 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1517 }
1518 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1519 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1520 ){
1521 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1522 }
dan6fe7f232018-08-10 19:19:33 +00001523 }
dancf8f2892018-08-09 20:47:01 +00001524 }
1525 }
dan5496d6a2018-08-13 17:14:26 +00001526 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001527 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1528 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001529 }else{
dan5be60c52018-08-15 20:28:39 +00001530 /* A trigger */
1531 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001532 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001533 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001534
danc9461ec2018-08-29 21:00:16 +00001535 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1536 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001537 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001538 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001539 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001540 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1541 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001542 }
danc9461ec2018-08-29 21:00:16 +00001543 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1544 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001545 }
1546 }
1547 }
1548
dan5be60c52018-08-15 20:28:39 +00001549
1550 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001551 if( sParse.pTriggerTab==pTab ){
1552 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001553 }
dan5be60c52018-08-15 20:28:39 +00001554
danc9461ec2018-08-29 21:00:16 +00001555 /* Find tokens to edit in various expressions and selects */
1556 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001557 }
1558
dan987db762018-08-14 20:18:50 +00001559 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001560 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001561
drh5fc22cd2018-08-13 13:43:11 +00001562renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001563 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001564 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001565 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001566 }else{
1567 sqlite3_result_error_code(context, rc);
1568 }
1569 }
1570
dan141e1192018-08-31 18:23:53 +00001571 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001572 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001573#ifndef SQLITE_OMIT_AUTHORIZATION
1574 db->xAuth = xAuth;
1575#endif
drhda76adc2018-08-25 02:04:05 +00001576 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001577}
1578
dandd1a9c82018-09-05 08:28:30 +00001579/*
1580** Walker expression callback used by "RENAME TABLE".
1581*/
danc9461ec2018-08-29 21:00:16 +00001582static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1583 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001584 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1585 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001586 }
1587 return WRC_Continue;
1588}
1589
1590/*
dandd1a9c82018-09-05 08:28:30 +00001591** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001592*/
1593static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1594 int i;
1595 RenameCtx *p = pWalker->u.pRename;
1596 SrcList *pSrc = pSelect->pSrc;
dan38096962019-12-09 08:13:43 +00001597 if( pSelect->selFlags & SF_View ) return WRC_Prune;
drh9da977f2021-04-20 12:14:12 +00001598 if( NEVER(pSrc==0) ){
drh92a28242019-10-09 15:37:58 +00001599 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001600 return WRC_Abort;
1601 }
danc9461ec2018-08-29 21:00:16 +00001602 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001603 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001604 if( pItem->pTab==p->pTab ){
1605 renameTokenFind(pWalker->pParse, p, pItem->zName);
1606 }
1607 }
danea412512018-12-05 13:49:04 +00001608 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001609
1610 return WRC_Continue;
1611}
1612
1613
1614/*
1615** This C function implements an SQL user function that is used by SQL code
1616** generated by the ALTER TABLE ... RENAME command to modify the definition
1617** of any foreign key constraints that use the table being renamed as the
1618** parent table. It is passed three arguments:
1619**
dan141e1192018-08-31 18:23:53 +00001620** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001621** 1. type: Type of object ("table", "view" etc.)
1622** 2. object: Name of object
1623** 3: The complete text of the schema statement being modified,
1624** 4: The old name of the table being renamed, and
1625** 5: The new name of the table being renamed.
1626** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001627**
dan141e1192018-08-31 18:23:53 +00001628** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001629**
dan141e1192018-08-31 18:23:53 +00001630** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001631** -> 'CREATE TABLE t1(a REFERENCES t3)'
1632*/
1633static void renameTableFunc(
1634 sqlite3_context *context,
1635 int NotUsed,
1636 sqlite3_value **argv
1637){
1638 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001639 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001640 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1641 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1642 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1643 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001644 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001645
dan141e1192018-08-31 18:23:53 +00001646 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001647 Parse sParse;
1648 int rc;
1649 int bQuote = 1;
1650 RenameCtx sCtx;
1651 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001652
dan141e1192018-08-31 18:23:53 +00001653#ifndef SQLITE_OMIT_AUTHORIZATION
1654 sqlite3_xauth xAuth = db->xAuth;
1655 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001656#endif
1657
dan141e1192018-08-31 18:23:53 +00001658 sqlite3BtreeEnterAll(db);
1659
1660 memset(&sCtx, 0, sizeof(RenameCtx));
1661 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1662 memset(&sWalker, 0, sizeof(Walker));
1663 sWalker.pParse = &sParse;
1664 sWalker.xExprCallback = renameTableExprCb;
1665 sWalker.xSelectCallback = renameTableSelectCb;
1666 sWalker.u.pRename = &sCtx;
1667
drhb2ab3dc2019-12-20 14:08:34 +00001668 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001669
1670 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001671 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001672 if( sParse.pNewTable ){
1673 Table *pTab = sParse.pNewTable;
1674
1675 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001676 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001677 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001678 NameContext sNC;
1679 memset(&sNC, 0, sizeof(sNC));
1680 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001681
dan38096962019-12-09 08:13:43 +00001682 assert( pSelect->selFlags & SF_View );
1683 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001684 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001685 if( sParse.nErr ){
1686 rc = sParse.rc;
1687 }else{
1688 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1689 }
dan674b8942018-09-20 08:28:01 +00001690 }
dan141e1192018-08-31 18:23:53 +00001691 }else{
1692 /* Modify any FK definitions to point to the new table. */
1693#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001694 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001695 FKey *pFKey;
1696 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1697 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1698 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1699 }
dan141e1192018-08-31 18:23:53 +00001700 }
1701 }
1702#endif
1703
1704 /* If this is the table being altered, fix any table refs in CHECK
1705 ** expressions. Also update the name that appears right after the
1706 ** "CREATE [VIRTUAL] TABLE" bit. */
1707 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1708 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001709 if( isLegacy==0 ){
1710 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1711 }
dan141e1192018-08-31 18:23:53 +00001712 renameTokenFind(&sParse, &sCtx, pTab->zName);
1713 }
danc9461ec2018-08-29 21:00:16 +00001714 }
1715 }
danc9461ec2018-08-29 21:00:16 +00001716
dan141e1192018-08-31 18:23:53 +00001717 else if( sParse.pNewIndex ){
1718 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001719 if( isLegacy==0 ){
1720 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1721 }
dan141e1192018-08-31 18:23:53 +00001722 }
danc9461ec2018-08-29 21:00:16 +00001723
1724#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001725 else{
dan141e1192018-08-31 18:23:53 +00001726 Trigger *pTrigger = sParse.pNewTrigger;
1727 TriggerStep *pStep;
1728 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1729 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1730 ){
1731 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1732 }
danc9461ec2018-08-29 21:00:16 +00001733
dan674b8942018-09-20 08:28:01 +00001734 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001735 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001736 if( rc==SQLITE_OK ){
1737 renameWalkTrigger(&sWalker, pTrigger);
1738 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1739 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1740 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1741 }
dan141e1192018-08-31 18:23:53 +00001742 }
dan0ccda962018-08-30 16:26:48 +00001743 }
danc9461ec2018-08-29 21:00:16 +00001744 }
1745 }
dan141e1192018-08-31 18:23:53 +00001746#endif
danc9461ec2018-08-29 21:00:16 +00001747 }
dan141e1192018-08-31 18:23:53 +00001748
1749 if( rc==SQLITE_OK ){
1750 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1751 }
1752 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001753 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001754 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001755 }else{
1756 sqlite3_result_error_code(context, rc);
1757 }
dan141e1192018-08-31 18:23:53 +00001758 }
1759
1760 renameParseCleanup(&sParse);
1761 renameTokenFree(db, sCtx.pList);
1762 sqlite3BtreeLeaveAll(db);
1763#ifndef SQLITE_OMIT_AUTHORIZATION
1764 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001765#endif
1766 }
1767
danc9461ec2018-08-29 21:00:16 +00001768 return;
1769}
1770
dan1e240722021-03-15 20:22:34 +00001771static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1772 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1773 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1774 }
1775 return WRC_Continue;
1776}
1777
1778/*
1779** The implementation of an SQL scalar function that rewrites DDL statements
1780** so that any string literals that use double-quotes are modified so that
1781** they use single quotes.
1782**
1783** Two arguments must be passed:
1784**
1785** 0: Database name ("main", "temp" etc.).
1786** 1: SQL statement to edit.
1787**
1788** The returned value is the modified SQL statement. For example, given
1789** the database schema:
1790**
1791** CREATE TABLE t1(a, b, c);
1792**
1793** SELECT sqlite_rename_quotefix('main',
1794** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1795** );
1796**
1797** returns the string:
1798**
1799** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1800*/
1801static void renameQuotefixFunc(
1802 sqlite3_context *context,
1803 int NotUsed,
1804 sqlite3_value **argv
1805){
1806 sqlite3 *db = sqlite3_context_db_handle(context);
1807 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1808 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1809
1810#ifndef SQLITE_OMIT_AUTHORIZATION
1811 sqlite3_xauth xAuth = db->xAuth;
1812 db->xAuth = 0;
1813#endif
1814
1815 sqlite3BtreeEnterAll(db);
1816
1817 UNUSED_PARAMETER(NotUsed);
1818 if( zDb && zInput ){
1819 int rc;
1820 Parse sParse;
1821 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1822
1823 if( rc==SQLITE_OK ){
1824 RenameCtx sCtx;
1825 Walker sWalker;
1826
1827 /* Walker to find tokens that need to be replaced. */
1828 memset(&sCtx, 0, sizeof(RenameCtx));
1829 memset(&sWalker, 0, sizeof(Walker));
1830 sWalker.pParse = &sParse;
1831 sWalker.xExprCallback = renameQuotefixExprCb;
1832 sWalker.xSelectCallback = renameColumnSelectCb;
1833 sWalker.u.pRename = &sCtx;
1834
1835 if( sParse.pNewTable ){
1836 Select *pSelect = sParse.pNewTable->pSelect;
1837 if( pSelect ){
1838 pSelect->selFlags &= ~SF_View;
1839 sParse.rc = SQLITE_OK;
1840 sqlite3SelectPrep(&sParse, pSelect, 0);
1841 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1842 if( rc==SQLITE_OK ){
1843 sqlite3WalkSelect(&sWalker, pSelect);
1844 }
1845 }else{
1846 int i;
1847 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1848#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1849 for(i=0; i<sParse.pNewTable->nCol; i++){
1850 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1851 }
1852#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1853 }
1854 }else if( sParse.pNewIndex ){
1855 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1856 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1857 }else{
1858#ifndef SQLITE_OMIT_TRIGGER
1859 rc = renameResolveTrigger(&sParse);
1860 if( rc==SQLITE_OK ){
1861 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1862 }
1863#endif /* SQLITE_OMIT_TRIGGER */
1864 }
1865
1866 if( rc==SQLITE_OK ){
1867 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1868 }
dan1fffa732021-03-16 18:24:49 +00001869 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001870 }
1871 if( rc!=SQLITE_OK ){
1872 sqlite3_result_error_code(context, rc);
1873 }
1874 renameParseCleanup(&sParse);
1875 }
1876
1877#ifndef SQLITE_OMIT_AUTHORIZATION
1878 db->xAuth = xAuth;
1879#endif
1880
1881 sqlite3BtreeLeaveAll(db);
1882}
1883
dandd1a9c82018-09-05 08:28:30 +00001884/*
1885** An SQL user function that checks that there are no parse or symbol
1886** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1887** After an ALTER TABLE .. RENAME operation is performed and the schema
1888** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001889** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001890**
1891** 0: Database name ("main", "temp" etc.).
1892** 1: SQL statement.
1893** 2: Object type ("view", "table", "trigger" or "index").
1894** 3: Object name.
1895** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001896** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001897** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001898**
1899** Unless it finds an error, this function normally returns NULL. However, it
1900** returns integer value 1 if:
1901**
1902** * the SQL argument creates a trigger, and
1903** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001904*/
dan9d324822018-08-30 20:03:44 +00001905static void renameTableTest(
1906 sqlite3_context *context,
1907 int NotUsed,
1908 sqlite3_value **argv
1909){
1910 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001911 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1912 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001913 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001914 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001915 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001916 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001917
dan141e1192018-08-31 18:23:53 +00001918#ifndef SQLITE_OMIT_AUTHORIZATION
1919 sqlite3_xauth xAuth = db->xAuth;
1920 db->xAuth = 0;
1921#endif
1922
drh5b1da302018-09-01 20:02:07 +00001923 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001924
dan09236502018-09-01 16:05:50 +00001925 if( zDb && zInput ){
1926 int rc;
1927 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001928 int flags = db->flags;
1929 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001930 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001931 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001932 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001933 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001934 NameContext sNC;
1935 memset(&sNC, 0, sizeof(sNC));
1936 sNC.pParse = &sParse;
1937 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1938 if( sParse.nErr ) rc = sParse.rc;
1939 }
1940
1941 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001942 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001943 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001944 }
drh3b700452018-09-07 19:12:08 +00001945 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001946 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1947 int i2 = sqlite3FindDbName(db, zDb);
1948 if( i1==i2 ) sqlite3_result_int(context, 1);
1949 }
dan09236502018-09-01 16:05:50 +00001950 }
dan9d324822018-08-30 20:03:44 +00001951 }
1952
dan16953462021-02-18 19:25:44 +00001953 if( rc!=SQLITE_OK && zWhen ){
1954 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001955 }
dan09236502018-09-01 16:05:50 +00001956 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001957 }
1958
dan141e1192018-08-31 18:23:53 +00001959#ifndef SQLITE_OMIT_AUTHORIZATION
1960 db->xAuth = xAuth;
1961#endif
dan9d324822018-08-30 20:03:44 +00001962}
1963
dancf8f2892018-08-09 20:47:01 +00001964/*
dan6a5a13d2021-02-17 20:08:22 +00001965** The implementation of internal UDF sqlite_drop_column().
1966**
dan6e6d9832021-02-16 20:43:36 +00001967** Arguments:
1968**
1969** argv[0]: An integer - the index of the schema containing the table
1970** argv[1]: CREATE TABLE statement to modify.
1971** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00001972**
1973** The value returned is a string containing the CREATE TABLE statement
1974** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00001975*/
1976static void dropColumnFunc(
1977 sqlite3_context *context,
1978 int NotUsed,
1979 sqlite3_value **argv
1980){
1981 sqlite3 *db = sqlite3_context_db_handle(context);
1982 int iSchema = sqlite3_value_int(argv[0]);
1983 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1984 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00001985 const char *zDb = db->aDb[iSchema].zDbSName;
1986 int rc;
1987 Parse sParse;
1988 RenameToken *pCol;
1989 Table *pTab;
1990 const char *zEnd;
1991 char *zNew = 0;
1992
dan678f3b32021-02-18 20:27:46 +00001993#ifndef SQLITE_OMIT_AUTHORIZATION
1994 sqlite3_xauth xAuth = db->xAuth;
1995 db->xAuth = 0;
1996#endif
1997
drh05edf722021-03-04 19:44:01 +00001998 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00001999 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
2000 if( rc!=SQLITE_OK ) goto drop_column_done;
2001 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00002002 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00002003 /* This can happen if the sqlite_schema table is corrupt */
2004 rc = SQLITE_CORRUPT_BKPT;
2005 goto drop_column_done;
2006 }
dan6e6d9832021-02-16 20:43:36 +00002007
2008 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
2009 if( iCol<pTab->nCol-1 ){
2010 RenameToken *pEnd;
2011 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
2012 zEnd = (const char*)pEnd->t.z;
2013 }else{
dan578277c2021-02-19 18:39:32 +00002014 zEnd = (const char*)&zSql[pTab->addColOffset];
drh60fe2352021-02-19 09:46:52 +00002015 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00002016 }
2017
danc2a878e2021-02-17 20:46:44 +00002018 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002019 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2020 sqlite3_free(zNew);
2021
2022drop_column_done:
2023 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002024#ifndef SQLITE_OMIT_AUTHORIZATION
2025 db->xAuth = xAuth;
2026#endif
danf4a72782021-02-19 14:13:40 +00002027 if( rc!=SQLITE_OK ){
2028 sqlite3_result_error_code(context, rc);
2029 }
dan6e6d9832021-02-16 20:43:36 +00002030}
2031
dan6a5a13d2021-02-17 20:08:22 +00002032/*
2033** This function is called by the parser upon parsing an
2034**
2035** ALTER TABLE pSrc DROP COLUMN pName
2036**
2037** statement. Argument pSrc contains the possibly qualified name of the
2038** table being edited, and token pName the name of the column to drop.
2039*/
dan6e6d9832021-02-16 20:43:36 +00002040void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002041 sqlite3 *db = pParse->db; /* Database handle */
2042 Table *pTab; /* Table to modify */
2043 int iDb; /* Index of db containing pTab in aDb[] */
2044 const char *zDb; /* Database containing pTab ("main" etc.) */
2045 char *zCol = 0; /* Name of column to drop */
2046 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002047
2048 /* Look up the table being altered. */
2049 assert( pParse->pNewTable==0 );
2050 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002051 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002052 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2053 if( !pTab ) goto exit_drop_column;
2054
dan6a5a13d2021-02-17 20:08:22 +00002055 /* Make sure this is not an attempt to ALTER a view, virtual table or
2056 ** system table. */
2057 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2058 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002059
2060 /* Find the index of the column being dropped. */
2061 zCol = sqlite3NameFromToken(db, pName);
2062 if( zCol==0 ){
2063 assert( db->mallocFailed );
2064 goto exit_drop_column;
2065 }
2066 iCol = sqlite3ColumnIndex(pTab, zCol);
2067 if( iCol<0 ){
2068 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2069 goto exit_drop_column;
2070 }
2071
2072 /* Do not allow the user to drop a PRIMARY KEY column or a column
2073 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002074 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2075 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2076 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2077 zCol
2078 );
dan6e6d9832021-02-16 20:43:36 +00002079 goto exit_drop_column;
2080 }
dan6e6d9832021-02-16 20:43:36 +00002081
drh239c84f2021-02-19 09:09:07 +00002082 /* Do not allow the number of columns to go to zero */
2083 if( pTab->nCol<=1 ){
2084 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2085 goto exit_drop_column;
2086 }
2087
dan6a5a13d2021-02-17 20:08:22 +00002088 /* Edit the sqlite_schema table */
2089 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2090 assert( iDb>=0 );
2091 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002092 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2093 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002094 sqlite3NestedParse(pParse,
2095 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002096 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002097 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002098 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002099 );
2100
2101 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002102 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002103 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002104
2105 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002106 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002107 int i;
2108 int addr;
2109 int reg;
2110 int regRec;
2111 Index *pPk = 0;
2112 int nField = 0; /* Number of non-virtual columns after drop */
2113 int iCur;
2114 Vdbe *v = sqlite3GetVdbe(pParse);
2115 iCur = pParse->nTab++;
2116 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002117 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002118 reg = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002119 if( HasRowid(pTab) ){
2120 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
dancc263012021-04-06 21:20:39 +00002121 pParse->nMem += pTab->nCol;
dan6a5a13d2021-02-17 20:08:22 +00002122 }else{
2123 pPk = sqlite3PrimaryKeyIndex(pTab);
dancc263012021-04-06 21:20:39 +00002124 pParse->nMem += pPk->nColumn;
2125 for(i=0; i<pPk->nKeyCol; i++){
2126 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1);
2127 }
2128 nField = pPk->nKeyCol;
dan6e6d9832021-02-16 20:43:36 +00002129 }
dancc263012021-04-06 21:20:39 +00002130 regRec = ++pParse->nMem;
dan6a5a13d2021-02-17 20:08:22 +00002131 for(i=0; i<pTab->nCol; i++){
2132 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2133 int regOut;
2134 if( pPk ){
2135 int iPos = sqlite3TableColumnToIndex(pPk, i);
2136 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
dancc263012021-04-06 21:20:39 +00002137 if( iPos<pPk->nKeyCol ) continue;
dan6a5a13d2021-02-17 20:08:22 +00002138 regOut = reg+1+iPos-(iPos>iColPos);
2139 }else{
2140 regOut = reg+1+nField;
2141 }
dan0a746cc2021-04-18 05:30:39 +00002142 if( i==pTab->iPKey ){
2143 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut);
2144 }else{
2145 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2146 }
dan6a5a13d2021-02-17 20:08:22 +00002147 nField++;
2148 }
2149 }
dan6a5a13d2021-02-17 20:08:22 +00002150 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2151 if( pPk ){
2152 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2153 }else{
2154 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2155 }
dan0a746cc2021-04-18 05:30:39 +00002156 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION);
dan6e6d9832021-02-16 20:43:36 +00002157
drh03361402021-02-18 23:53:47 +00002158 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002159 sqlite3VdbeJumpHere(v, addr);
2160 }
dan6e6d9832021-02-16 20:43:36 +00002161
2162exit_drop_column:
2163 sqlite3DbFree(db, zCol);
2164 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002165}
2166
2167/*
dancf8f2892018-08-09 20:47:01 +00002168** Register built-in functions used to help implement ALTER TABLE
2169*/
2170void sqlite3AlterFunctions(void){
2171 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002172 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2173 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002174 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002175 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002176 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002177 };
2178 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2179}
drhd0e4a6c2005-02-15 20:47:57 +00002180#endif /* SQLITE_ALTER_TABLE */