blob: 6a0818f651748b800e0e3f946dc30515e713fcb8 [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){
32 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
33#ifndef SQLITE_OMIT_VIRTUALTABLE
drh070ae3b2019-11-16 13:51:31 +000034 || ( (pTab->tabFlags & TF_Shadow)!=0
35 && sqlite3ReadOnlyShadowTables(pParse->db)
dan397a78d2018-12-18 20:31:14 +000036 )
37#endif
38 ){
39 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danbe535002011-04-01 15:15:58 +000040 return 1;
41 }
42 return 0;
43}
44
dan09236502018-09-01 16:05:50 +000045/*
46** Generate code to verify that the schemas of database zDb and, if
47** bTemp is not true, database "temp", can still be parsed. This is
48** called at the end of the generation of an ALTER TABLE ... RENAME ...
49** statement to ensure that the operation has not rendered any schema
50** objects unusable.
51*/
dan16953462021-02-18 19:25:44 +000052static void renameTestSchema(
53 Parse *pParse, /* Parse context */
54 const char *zDb, /* Name of db to verify schema of */
55 int bTemp, /* True if this is the temp db */
dan2ad080a2021-03-16 16:14:48 +000056 const char *zWhen, /* "when" part of error message */
57 int bNoDQS /* Do not allow DQS in the schema */
dan16953462021-02-18 19:25:44 +000058){
drh351ae772021-02-15 13:17:19 +000059 pParse->colNamesSet = 1;
dan9d324822018-08-30 20:03:44 +000060 sqlite3NestedParse(pParse,
61 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000062 "FROM \"%w\"." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000063 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000064 " AND sql NOT LIKE 'create virtual%%'"
dan2ad080a2021-03-16 16:14:48 +000065 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ",
drh346a70c2020-06-15 20:27:35 +000066 zDb,
dan2ad080a2021-03-16 16:14:48 +000067 zDb, bTemp, zWhen, bNoDQS
dan9d324822018-08-30 20:03:44 +000068 );
69
70 if( bTemp==0 ){
71 sqlite3NestedParse(pParse,
72 "SELECT 1 "
drh346a70c2020-06-15 20:27:35 +000073 "FROM temp." DFLT_SCHEMA_TABLE " "
dan65455fc2019-04-19 16:34:22 +000074 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000075 " AND sql NOT LIKE 'create virtual%%'"
dan2ad080a2021-03-16 16:14:48 +000076 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ",
77 zDb, zWhen, bNoDQS
78 );
79 }
80}
81
82/*
83** Generate VM code to replace any double-quoted strings (but not double-quoted
84** identifiers) within the "sql" column of the sqlite_schema table in
85** database zDb with their single-quoted equivalents. If argument bTemp is
86** not true, similarly update all SQL statements in the sqlite_schema table
87** of the temp db.
88*/
89static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){
90 sqlite3NestedParse(pParse,
91 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE
92 " SET sql = sqlite_rename_quotefix(%Q, sql)"
93 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
94 " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb
95 );
96 if( bTemp==0 ){
97 sqlite3NestedParse(pParse,
98 "UPDATE temp." DFLT_SCHEMA_TABLE
99 " SET sql = sqlite_rename_quotefix('temp', sql)"
100 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
101 " AND sql NOT LIKE 'create virtual%%'"
dan9d324822018-08-30 20:03:44 +0000102 );
103 }
104}
105
danbe535002011-04-01 15:15:58 +0000106/*
dan09236502018-09-01 16:05:50 +0000107** Generate code to reload the schema for database iDb. And, if iDb!=1, for
108** the temp database as well.
109*/
dan6a5a13d2021-02-17 20:08:22 +0000110static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){
dan09236502018-09-01 16:05:50 +0000111 Vdbe *v = pParse->pVdbe;
112 if( v ){
113 sqlite3ChangeCookie(pParse, iDb);
dan6a5a13d2021-02-17 20:08:22 +0000114 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
115 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
dan09236502018-09-01 16:05:50 +0000116 }
117}
118
119/*
drhd0e4a6c2005-02-15 20:47:57 +0000120** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
121** command.
122*/
123void sqlite3AlterRenameTable(
124 Parse *pParse, /* Parser context. */
125 SrcList *pSrc, /* The table to rename. */
126 Token *pName /* The new table name. */
127){
128 int iDb; /* Database that contains the table */
129 char *zDb; /* Name of database iDb */
130 Table *pTab; /* Table being renamed */
131 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000132 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000133 int nTabName; /* Number of UTF-8 characters in zTabName */
134 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000135 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000136 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000137 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000138
drh8257aa82017-07-26 19:59:13 +0000139 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000140 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000141 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000142 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000143
dan41fb5cd2012-10-04 19:33:00 +0000144 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000145 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000146 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000147 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000148 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000149
150 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000151 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000152 if( !zName ) goto exit_rename_table;
153
154 /* Check that a table or index named 'zName' does not already exist
155 ** in database iDb. If so, this is an error.
156 */
drh3d863b52020-05-14 21:16:52 +0000157 if( sqlite3FindTable(db, zName, zDb)
158 || sqlite3FindIndex(db, zName, zDb)
159 || sqlite3IsShadowTableOf(db, pTab, zName)
160 ){
drhd0e4a6c2005-02-15 20:47:57 +0000161 sqlite3ErrorMsg(pParse,
162 "there is already another table or index with this name: %s", zName);
163 goto exit_rename_table;
164 }
165
166 /* Make sure it is not a system table being altered, or a reserved name
167 ** that the table is being renamed to.
168 */
dan397a78d2018-12-18 20:31:14 +0000169 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000170 goto exit_rename_table;
171 }
drhc5a93d42019-08-12 00:08:07 +0000172 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
173 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000174 }
175
danielk197761116ae2007-12-13 08:15:30 +0000176#ifndef SQLITE_OMIT_VIEW
177 if( pTab->pSelect ){
178 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
179 goto exit_rename_table;
180 }
181#endif
182
drhd0e4a6c2005-02-15 20:47:57 +0000183#ifndef SQLITE_OMIT_AUTHORIZATION
184 /* Invoke the authorization callback. */
185 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
186 goto exit_rename_table;
187 }
188#endif
189
danielk1977182c4ba2007-06-27 15:53:34 +0000190#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000191 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
192 goto exit_rename_table;
193 }
danielk1977595a5232009-07-24 17:58:53 +0000194 if( IsVirtual(pTab) ){
195 pVTab = sqlite3GetVTable(db, pTab);
196 if( pVTab->pVtab->pModule->xRename==0 ){
197 pVTab = 0;
198 }
danielk1977182c4ba2007-06-27 15:53:34 +0000199 }
200#endif
201
dan1f3b2842019-03-15 16:17:32 +0000202 /* Begin a transaction for database iDb. Then modify the schema cookie
203 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
204 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
205 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000206 v = sqlite3GetVdbe(pParse);
207 if( v==0 ){
208 goto exit_rename_table;
209 }
dan1f3b2842019-03-15 16:17:32 +0000210 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000211
drh4e5dd852007-05-15 03:56:49 +0000212 /* figure out how many UTF-8 characters are in zName */
213 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000214 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000215
danc9461ec2018-08-29 21:00:16 +0000216 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
217 ** the schema to use the new table name. */
218 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000219 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan65372fa2018-09-03 20:05:15 +0000220 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000221 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000222 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
drh346a70c2020-06-15 20:27:35 +0000223 , zDb, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000224 );
dan432cc5b2009-09-26 17:51:48 +0000225
drh1e32bed2020-06-19 13:33:53 +0000226 /* Update the tbl_name and name columns of the sqlite_schema table
danc9461ec2018-08-29 21:00:16 +0000227 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000228 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000229 "UPDATE %Q." DFLT_SCHEMA_TABLE " SET "
drhd0e4a6c2005-02-15 20:47:57 +0000230 "tbl_name = %Q, "
231 "name = CASE "
232 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000233 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
234 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000235 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000236 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000237 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000238 "(type='table' OR type='index' OR type='trigger');",
drh346a70c2020-06-15 20:27:35 +0000239 zDb,
danc9461ec2018-08-29 21:00:16 +0000240 zName, zName, zName,
241 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000242 );
243
244#ifndef SQLITE_OMIT_AUTOINCREMENT
245 /* If the sqlite_sequence table exists in this database, then update
246 ** it with the new table name.
247 */
248 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
249 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000250 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000251 zDb, zName, pTab->zName);
252 }
253#endif
254
danc9461ec2018-08-29 21:00:16 +0000255 /* If the table being renamed is not itself part of the temp database,
256 ** edit view and trigger definitions within the temp database
257 ** as required. */
258 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000259 sqlite3NestedParse(pParse,
drh1e32bed2020-06-19 13:33:53 +0000260 "UPDATE sqlite_temp_schema SET "
dan65372fa2018-09-03 20:05:15 +0000261 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000262 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000263 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
dan2ad080a2021-03-16 16:14:48 +0000264 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) "
dan1d85c6b2018-09-06 16:01:37 +0000265 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000266 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000267 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000268 }
drhd0e4a6c2005-02-15 20:47:57 +0000269
dan34566c42018-09-20 17:21:21 +0000270 /* If this is a virtual table, invoke the xRename() function if
271 ** one is defined. The xRename() callback will modify the names
272 ** of any resources used by the v-table implementation (including other
273 ** SQLite tables) that are identified by the name of the virtual table.
274 */
275#ifndef SQLITE_OMIT_VIRTUALTABLE
276 if( pVTab ){
277 int i = ++pParse->nMem;
278 sqlite3VdbeLoadString(v, i, zName);
279 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000280 }
281#endif
282
dan6a5a13d2021-02-17 20:08:22 +0000283 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000284 renameTestSchema(pParse, zDb, iDb==1, "after rename", 0);
dan9d324822018-08-30 20:03:44 +0000285
drhd0e4a6c2005-02-15 20:47:57 +0000286exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000287 sqlite3SrcListDelete(db, pSrc);
288 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000289 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000290}
danielk197719a8e7e2005-03-17 05:03:38 +0000291
drhd3001712009-05-12 17:46:53 +0000292/*
drh9e5fdc42020-05-08 19:02:21 +0000293** Write code that will raise an error if the table described by
294** zDb and zTab is not empty.
295*/
296static void sqlite3ErrorIfNotEmpty(
297 Parse *pParse, /* Parsing context */
298 const char *zDb, /* Schema holding the table */
299 const char *zTab, /* Table to check for empty */
300 const char *zErr /* Error message text */
301){
302 sqlite3NestedParse(pParse,
303 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"",
304 zErr, zDb, zTab
305 );
306}
307
308/*
danielk197719a8e7e2005-03-17 05:03:38 +0000309** This function is called after an "ALTER TABLE ... ADD" statement
310** has been parsed. Argument pColDef contains the text of the new
311** column definition.
312**
313** The Table structure pParse->pNewTable was extended to include
314** the new column during parsing.
315*/
316void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
317 Table *pNew; /* Copy of pParse->pNewTable */
318 Table *pTab; /* Table being altered */
319 int iDb; /* Database number */
320 const char *zDb; /* Database name */
321 const char *zTab; /* Table name */
322 char *zCol; /* Null-terminated column definition */
323 Column *pCol; /* The new column */
324 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000325 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000326 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000327 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000328
danielk1977f150c9d2008-10-30 17:21:12 +0000329 db = pParse->db;
330 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000331 pNew = pParse->pNewTable;
332 assert( pNew );
333
drh1fee73e2007-08-29 04:00:57 +0000334 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000335 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000336 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000337 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000338 pCol = &pNew->aCol[pNew->nCol-1];
339 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000340 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000341 assert( pTab );
342
drh81f2ccd2006-01-31 14:28:44 +0000343#ifndef SQLITE_OMIT_AUTHORIZATION
344 /* Invoke the authorization callback. */
345 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
346 return;
347 }
348#endif
349
danielk197719a8e7e2005-03-17 05:03:38 +0000350
351 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
352 ** If there is a NOT NULL constraint, then the default value for the
353 ** column must not be NULL.
354 */
drha371ace2012-09-13 14:22:47 +0000355 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000356 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
357 return;
358 }
359 if( pNew->pIndex ){
drh9e5fdc42020-05-08 19:02:21 +0000360 sqlite3ErrorMsg(pParse,
361 "Cannot add a UNIQUE column");
danielk197719a8e7e2005-03-17 05:03:38 +0000362 return;
363 }
drhc27ea2a2019-10-16 20:05:56 +0000364 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
365 /* If the default value for the new column was specified with a
366 ** literal NULL, then set pDflt to 0. This simplifies checking
367 ** for an SQL NULL default below.
368 */
369 assert( pDflt==0 || pDflt->op==TK_SPAN );
370 if( pDflt && pDflt->pLeft->op==TK_NULL ){
371 pDflt = 0;
372 }
373 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000374 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000375 "Cannot add a REFERENCES column with non-NULL default value");
drhc27ea2a2019-10-16 20:05:56 +0000376 }
377 if( pCol->notNull && !pDflt ){
drh9e5fdc42020-05-08 19:02:21 +0000378 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
drhc27ea2a2019-10-16 20:05:56 +0000379 "Cannot add a NOT NULL column with default value NULL");
drhc27ea2a2019-10-16 20:05:56 +0000380 }
381
drh9e5fdc42020-05-08 19:02:21 +0000382
drhc27ea2a2019-10-16 20:05:56 +0000383 /* Ensure the default expression is something that sqlite3ValueFromExpr()
384 ** can handle (i.e. not CURRENT_TIME etc.)
385 */
386 if( pDflt ){
387 sqlite3_value *pVal = 0;
388 int rc;
389 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
390 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
391 if( rc!=SQLITE_OK ){
392 assert( db->mallocFailed == 1 );
393 return;
394 }
395 if( !pVal ){
drh9e5fdc42020-05-08 19:02:21 +0000396 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab,
397 "Cannot add a column with non-constant default");
drhc27ea2a2019-10-16 20:05:56 +0000398 }
399 sqlite3ValueFree(pVal);
400 }
drh035f6d92019-10-24 01:04:10 +0000401 }else if( pCol->colFlags & COLFLAG_STORED ){
drh9e5fdc42020-05-08 19:02:21 +0000402 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column");
danielk197719a8e7e2005-03-17 05:03:38 +0000403 }
404
danielk197719a8e7e2005-03-17 05:03:38 +0000405
406 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000407 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000408 if( zCol ){
409 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000410 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000411 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000412 *zEnd-- = '\0';
413 }
drh8257aa82017-07-26 19:59:13 +0000414 db->mDbFlags |= DBFLAG_PreferBuiltin;
drh37114fb2021-01-01 20:04:34 +0000415 /* substr() operations on characters, but addColOffset is in bytes. So we
416 ** have to use printf() to translate between these units: */
danielk197719a8e7e2005-03-17 05:03:38 +0000417 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000418 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
drh37114fb2021-01-01 20:04:34 +0000419 "sql = printf('%%.%ds, ',sql) || %Q"
420 " || substr(sql,1+length(printf('%%.%ds',sql))) "
danielk197719a8e7e2005-03-17 05:03:38 +0000421 "WHERE type = 'table' AND name = %Q",
drh37114fb2021-01-01 20:04:34 +0000422 zDb, pNew->addColOffset, zCol, pNew->addColOffset,
danielk197719a8e7e2005-03-17 05:03:38 +0000423 zTab
424 );
drh633e6d52008-07-28 19:34:53 +0000425 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000426 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000427 }
428
drh86396212016-07-14 19:13:11 +0000429 /* Make sure the schema version is at least 3. But do not upgrade
430 ** from less than 3 to 4, as that will corrupt any preexisting DESC
431 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000432 */
dan09236502018-09-01 16:05:50 +0000433 v = sqlite3GetVdbe(pParse);
434 if( v ){
435 r1 = sqlite3GetTempReg(pParse);
436 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
437 sqlite3VdbeUsesBtree(v, iDb);
438 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
439 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
440 VdbeCoverage(v);
441 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
442 sqlite3ReleaseTempReg(pParse, r1);
443 }
danielk197719a8e7e2005-03-17 05:03:38 +0000444
dan09236502018-09-01 16:05:50 +0000445 /* Reload the table definition */
dan6a5a13d2021-02-17 20:08:22 +0000446 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename);
danielk197719a8e7e2005-03-17 05:03:38 +0000447}
448
drhfdd6e852005-12-16 01:06:16 +0000449/*
danielk197719a8e7e2005-03-17 05:03:38 +0000450** This function is called by the parser after the table-name in
451** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
452** pSrc is the full-name of the table being altered.
453**
454** This routine makes a (partial) copy of the Table structure
455** for the table being altered and sets Parse.pNewTable to point
456** to it. Routines called by the parser as the column definition
457** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
458** the copy. The copy of the Table structure is deleted by tokenize.c
459** after parsing is finished.
460**
461** Routine sqlite3AlterFinishAddColumn() will be called to complete
462** coding the "ALTER TABLE ... ADD" statement.
463*/
464void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
465 Table *pNew;
466 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000467 int iDb;
468 int i;
469 int nAlloc;
drh17435752007-08-16 04:30:38 +0000470 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000471
472 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000473 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000474 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000475 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000476 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000477 if( !pTab ) goto exit_begin_add_column;
478
danielk19775ee9d692006-06-21 12:36:25 +0000479#ifndef SQLITE_OMIT_VIRTUALTABLE
480 if( IsVirtual(pTab) ){
481 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
482 goto exit_begin_add_column;
483 }
484#endif
485
danielk197719a8e7e2005-03-17 05:03:38 +0000486 /* Make sure this is not an attempt to ALTER a view. */
487 if( pTab->pSelect ){
488 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
489 goto exit_begin_add_column;
490 }
dan397a78d2018-12-18 20:31:14 +0000491 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000492 goto exit_begin_add_column;
493 }
danielk197719a8e7e2005-03-17 05:03:38 +0000494
dan03e025e2019-10-07 18:43:21 +0000495 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000496 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000497 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000498
499 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000500 ** sqlite3AddColumn() function and friends to modify. But modify
501 ** the name by adding an "sqlite_altertab_" prefix. By adding this
502 ** prefix, we insure that the name will not collide with an existing
503 ** table because user table are not allowed to have the "sqlite_"
504 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000505 */
drh17435752007-08-16 04:30:38 +0000506 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000507 if( !pNew ) goto exit_begin_add_column;
508 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000509 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000510 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000511 assert( pNew->nCol>0 );
512 nAlloc = (((pNew->nCol-1)/8)*8)+8;
513 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000514 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000515 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000516 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000517 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000518 goto exit_begin_add_column;
519 }
520 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
521 for(i=0; i<pNew->nCol; i++){
522 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000523 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhd44390c2020-04-06 18:16:31 +0000524 pCol->hName = sqlite3StrIHash(pCol->zName);
drhff22e182006-02-09 02:56:02 +0000525 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000526 pCol->pDflt = 0;
527 }
drh17435752007-08-16 04:30:38 +0000528 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000529 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000530 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000531
danielk197719a8e7e2005-03-17 05:03:38 +0000532exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000533 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000534 return;
535}
dancf8f2892018-08-09 20:47:01 +0000536
drh4a2c7472018-08-13 15:09:48 +0000537/*
dan9d705572018-08-20 16:16:05 +0000538** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
539** command. This function checks if the table is a view or virtual
540** table (columns of views or virtual tables may not be renamed). If so,
541** it loads an error message into pParse and returns non-zero.
542**
543** Or, if pTab is not a view or virtual table, zero is returned.
544*/
545#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
dan6a5a13d2021-02-17 20:08:22 +0000546static int isRealTable(Parse *pParse, Table *pTab, int bDrop){
dan9d705572018-08-20 16:16:05 +0000547 const char *zType = 0;
548#ifndef SQLITE_OMIT_VIEW
549 if( pTab->pSelect ){
550 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000551 }
dan9d705572018-08-20 16:16:05 +0000552#endif
553#ifndef SQLITE_OMIT_VIRTUALTABLE
554 if( IsVirtual(pTab) ){
555 zType = "virtual table";
556 }
557#endif
558 if( zType ){
dan6a5a13d2021-02-17 20:08:22 +0000559 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"",
560 (bDrop ? "drop column from" : "rename columns of"),
561 zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000562 );
563 return 1;
564 }
565 return 0;
566}
567#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
dan6a5a13d2021-02-17 20:08:22 +0000568# define isRealTable(x,y,z) (0)
dan9d705572018-08-20 16:16:05 +0000569#endif
570
571/*
drh4a2c7472018-08-13 15:09:48 +0000572** Handles the following parser reduction:
573**
574** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
575*/
dancf8f2892018-08-09 20:47:01 +0000576void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000577 Parse *pParse, /* Parsing context */
578 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
579 Token *pOld, /* Name of column being changed */
580 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000581){
drh4a2c7472018-08-13 15:09:48 +0000582 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000583 Table *pTab; /* Table being updated */
584 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000585 char *zOld = 0; /* Old column name */
586 char *zNew = 0; /* New column name */
587 const char *zDb; /* Name of schema containing the table */
588 int iSchema; /* Index of the schema */
589 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000590
drh4a2c7472018-08-13 15:09:48 +0000591 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000592 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
593 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000594
595 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000596 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan6a5a13d2021-02-17 20:08:22 +0000597 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000598
599 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000600 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
601 assert( iSchema>=0 );
602 zDb = db->aDb[iSchema].zDbSName;
603
drh0d019b92018-08-25 16:14:46 +0000604#ifndef SQLITE_OMIT_AUTHORIZATION
605 /* Invoke the authorization callback. */
606 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
607 goto exit_rename_column;
608 }
609#endif
610
drh4a2c7472018-08-13 15:09:48 +0000611 /* Make sure the old name really is a column name in the table to be
612 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000613 zOld = sqlite3NameFromToken(db, pOld);
614 if( !zOld ) goto exit_rename_column;
615 for(iCol=0; iCol<pTab->nCol; iCol++){
616 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
617 }
618 if( iCol==pTab->nCol ){
619 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
620 goto exit_rename_column;
621 }
622
dan2ad080a2021-03-16 16:14:48 +0000623 /* Ensure the schema contains no double-quoted strings */
624 renameTestSchema(pParse, zDb, iSchema==1, "", 0);
625 renameFixQuotes(pParse, zDb, iSchema==1);
626
drh4a2c7472018-08-13 15:09:48 +0000627 /* Do the rename operation using a recursive UPDATE statement that
628 ** uses the sqlite_rename_column() SQL function to compute the new
drh1e32bed2020-06-19 13:33:53 +0000629 ** CREATE statement text for the sqlite_schema table.
drh4a2c7472018-08-13 15:09:48 +0000630 */
dan1f3b2842019-03-15 16:17:32 +0000631 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000632 zNew = sqlite3NameFromToken(db, pNew);
633 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000634 assert( pNew->n>0 );
635 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000636 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000637 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000638 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000639 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
640 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000641 " AND sql NOT LIKE 'create virtual%%'",
drh346a70c2020-06-15 20:27:35 +0000642 zDb,
danb87a9a82018-09-01 20:23:28 +0000643 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000644 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000645 );
646
dan9d324822018-08-30 20:03:44 +0000647 sqlite3NestedParse(pParse,
drh346a70c2020-06-15 20:27:35 +0000648 "UPDATE temp." DFLT_SCHEMA_TABLE " SET "
danb87a9a82018-09-01 20:23:28 +0000649 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000650 "WHERE type IN ('trigger', 'view')",
dan9d324822018-08-30 20:03:44 +0000651 zDb, pTab->zName, iCol, zNew, bQuote
652 );
653
dane325ffe2018-08-11 13:40:20 +0000654 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +0000655 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename);
dan2ad080a2021-03-16 16:14:48 +0000656 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1);
dan0d5fa6b2018-08-24 17:55:49 +0000657
dancf8f2892018-08-09 20:47:01 +0000658 exit_rename_column:
659 sqlite3SrcListDelete(db, pSrc);
660 sqlite3DbFree(db, zOld);
661 sqlite3DbFree(db, zNew);
662 return;
663}
664
drh4a2c7472018-08-13 15:09:48 +0000665/*
666** Each RenameToken object maps an element of the parse tree into
667** the token that generated that element. The parse tree element
668** might be one of:
669**
670** * A pointer to an Expr that represents an ID
671** * The name of a table column in Column.zName
672**
673** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000674** Each new object is created by sqlite3RenameTokenMap().
675** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000676** routine is used to keep the mapping current.
677**
678** After the parse finishes, renameTokenFind() routine can be used
679** to look up the actual token value that created some element in
680** the parse tree.
681*/
dancf8f2892018-08-09 20:47:01 +0000682struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000683 void *p; /* Parse tree element created by token t */
684 Token t; /* The token that created parse tree element p */
685 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000686};
687
drh4a2c7472018-08-13 15:09:48 +0000688/*
689** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
690** down into the Walker.
691*/
dan5496d6a2018-08-13 17:14:26 +0000692typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000693struct RenameCtx {
694 RenameToken *pList; /* List of tokens to overwrite */
695 int nList; /* Number of tokens in pList */
696 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000697 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000698 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000699};
700
dan8900a482018-09-05 14:36:05 +0000701#ifdef SQLITE_DEBUG
702/*
703** This function is only for debugging. It performs two tasks:
704**
705** 1. Checks that pointer pPtr does not already appear in the
706** rename-token list.
707**
708** 2. Dereferences each pointer in the rename-token list.
709**
710** The second is most effective when debugging under valgrind or
711** address-sanitizer or similar. If any of these pointers no longer
712** point to valid objects, an exception is raised by the memory-checking
713** tool.
714**
715** The point of this is to prevent comparisons of invalid pointer values.
716** Even though this always seems to work, it is undefined according to the
717** C standard. Example of undefined comparison:
718**
719** sqlite3_free(x);
720** if( x==y ) ...
721**
722** Technically, as x no longer points into a valid object or to the byte
723** following a valid object, it may not be used in comparison operations.
724*/
drh16b870d2018-09-12 15:51:56 +0000725static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000726 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
727 RenameToken *p;
728 u8 i = 0;
729 for(p=pParse->pRename; p; p=p->pNext){
730 if( p->p ){
731 assert( p->p!=pPtr );
732 i += *(u8*)(p->p);
733 }
danc9461ec2018-08-29 21:00:16 +0000734 }
735 }
736}
dan8900a482018-09-05 14:36:05 +0000737#else
738# define renameTokenCheckAll(x,y)
739#endif
danc9461ec2018-08-29 21:00:16 +0000740
drh4a2c7472018-08-13 15:09:48 +0000741/*
drh49b269e2018-11-26 15:00:25 +0000742** Remember that the parser tree element pPtr was created using
743** the token pToken.
dan07e95232018-08-21 16:32:53 +0000744**
drh49b269e2018-11-26 15:00:25 +0000745** In other words, construct a new RenameToken object and add it
746** to the list of RenameToken objects currently being built up
747** in pParse->pRename.
748**
749** The pPtr argument is returned so that this routine can be used
750** with tail recursion in tokenExpr() routine, for a small performance
751** improvement.
drh4a2c7472018-08-13 15:09:48 +0000752*/
dan07e95232018-08-21 16:32:53 +0000753void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000754 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000755 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000756 renameTokenCheckAll(pParse, pPtr);
drh2d99f952020-04-07 01:18:23 +0000757 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
dane6dc1e52019-12-05 14:31:43 +0000758 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
759 if( pNew ){
760 pNew->p = pPtr;
761 pNew->t = *pToken;
762 pNew->pNext = pParse->pRename;
763 pParse->pRename = pNew;
764 }
dancf8f2892018-08-09 20:47:01 +0000765 }
danc9461ec2018-08-29 21:00:16 +0000766
dand145e5f2018-08-21 08:29:48 +0000767 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000768}
769
drh4a2c7472018-08-13 15:09:48 +0000770/*
dan07e95232018-08-21 16:32:53 +0000771** It is assumed that there is already a RenameToken object associated
772** with parse tree element pFrom. This function remaps the associated token
773** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000774*/
dan07e95232018-08-21 16:32:53 +0000775void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000776 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000777 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000778 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000779 if( p->p==pFrom ){
780 p->p = pTo;
781 break;
782 }
783 }
dancf8f2892018-08-09 20:47:01 +0000784}
785
drh4a2c7472018-08-13 15:09:48 +0000786/*
dan8900a482018-09-05 14:36:05 +0000787** Walker callback used by sqlite3RenameExprUnmap().
788*/
789static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
790 Parse *pParse = pWalker->pParse;
791 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
792 return WRC_Continue;
793}
794
795/*
dan8f407622019-12-04 14:26:38 +0000796** Iterate through the Select objects that are part of WITH clauses attached
797** to select statement pSelect.
798*/
799static void renameWalkWith(Walker *pWalker, Select *pSelect){
drh646975c2019-12-17 12:03:30 +0000800 With *pWith = pSelect->pWith;
801 if( pWith ){
dan8f407622019-12-04 14:26:38 +0000802 int i;
drh646975c2019-12-17 12:03:30 +0000803 for(i=0; i<pWith->nCte; i++){
804 Select *p = pWith->a[i].pSelect;
dan8f407622019-12-04 14:26:38 +0000805 NameContext sNC;
806 memset(&sNC, 0, sizeof(sNC));
807 sNC.pParse = pWalker->pParse;
808 sqlite3SelectPrep(sNC.pParse, p, &sNC);
809 sqlite3WalkSelect(pWalker, p);
drh646975c2019-12-17 12:03:30 +0000810 sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols);
dan8f407622019-12-04 14:26:38 +0000811 }
812 }
813}
814
815/*
danfb99e382020-04-03 11:20:40 +0000816** Unmap all tokens in the IdList object passed as the second argument.
817*/
818static void unmapColumnIdlistNames(
819 Parse *pParse,
820 IdList *pIdList
821){
822 if( pIdList ){
823 int ii;
824 for(ii=0; ii<pIdList->nId; ii++){
825 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName);
826 }
827 }
828}
829
830/*
dan0b277a92019-06-11 12:03:10 +0000831** Walker callback used by sqlite3RenameExprUnmap().
832*/
833static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000834 Parse *pParse = pWalker->pParse;
835 int i;
drhd63b69b2019-12-04 15:08:58 +0000836 if( pParse->nErr ) return WRC_Abort;
drh2bc5cf92019-12-09 19:29:10 +0000837 if( NEVER(p->selFlags & SF_View) ) return WRC_Prune;
drhbdf4cf02019-06-15 15:21:49 +0000838 if( ALWAYS(p->pEList) ){
839 ExprList *pList = p->pEList;
840 for(i=0; i<pList->nExpr; i++){
drhc4938ea2019-12-13 00:49:42 +0000841 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){
drh41cee662019-12-12 20:22:34 +0000842 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
drhbdf4cf02019-06-15 15:21:49 +0000843 }
844 }
845 }
drh2c3f4652019-06-11 16:43:58 +0000846 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000847 SrcList *pSrc = p->pSrc;
848 for(i=0; i<pSrc->nSrc; i++){
849 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan394aa712019-12-20 14:18:29 +0000850 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort;
danfb99e382020-04-03 11:20:40 +0000851 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing);
dan0b277a92019-06-11 12:03:10 +0000852 }
853 }
dan8f407622019-12-04 14:26:38 +0000854
855 renameWalkWith(pWalker, p);
dan0b277a92019-06-11 12:03:10 +0000856 return WRC_Continue;
857}
858
859/*
dan8900a482018-09-05 14:36:05 +0000860** Remove all nodes that are part of expression pExpr from the rename list.
861*/
862void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
dane6dc1e52019-12-05 14:31:43 +0000863 u8 eMode = pParse->eParseMode;
dan8900a482018-09-05 14:36:05 +0000864 Walker sWalker;
865 memset(&sWalker, 0, sizeof(Walker));
866 sWalker.pParse = pParse;
867 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000868 sWalker.xSelectCallback = renameUnmapSelectCb;
dane6dc1e52019-12-05 14:31:43 +0000869 pParse->eParseMode = PARSE_MODE_UNMAP;
dan8900a482018-09-05 14:36:05 +0000870 sqlite3WalkExpr(&sWalker, pExpr);
dane6dc1e52019-12-05 14:31:43 +0000871 pParse->eParseMode = eMode;
dan8900a482018-09-05 14:36:05 +0000872}
873
874/*
dane8ab40d2018-09-12 08:51:48 +0000875** Remove all nodes that are part of expression-list pEList from the
876** rename list.
877*/
878void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
879 if( pEList ){
880 int i;
881 Walker sWalker;
882 memset(&sWalker, 0, sizeof(Walker));
883 sWalker.pParse = pParse;
884 sWalker.xExprCallback = renameUnmapExprCb;
885 sqlite3WalkExprList(&sWalker, pEList);
886 for(i=0; i<pEList->nExpr; i++){
drh9fc1b9a2020-01-02 22:23:01 +0000887 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){
drhc4938ea2019-12-13 00:49:42 +0000888 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
889 }
dane8ab40d2018-09-12 08:51:48 +0000890 }
891 }
892}
893
894/*
drh4a2c7472018-08-13 15:09:48 +0000895** Free the list of RenameToken objects given in the second argument
896*/
dancf8f2892018-08-09 20:47:01 +0000897static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
898 RenameToken *pNext;
899 RenameToken *p;
900 for(p=pToken; p; p=pNext){
901 pNext = p->pNext;
902 sqlite3DbFree(db, p);
903 }
904}
905
dan987db762018-08-14 20:18:50 +0000906/*
907** Search the Parse object passed as the first argument for a RenameToken
dan6e6d9832021-02-16 20:43:36 +0000908** object associated with parse tree element pPtr. If found, return a pointer
909** to it. Otherwise, return NULL.
910**
911** If the second argument passed to this function is not NULL and a matching
912** RenameToken object is found, remove it from the Parse object and add it to
913** the list maintained by the RenameCtx object.
dan987db762018-08-14 20:18:50 +0000914*/
dan6e6d9832021-02-16 20:43:36 +0000915static RenameToken *renameTokenFind(
916 Parse *pParse,
917 struct RenameCtx *pCtx,
918 void *pPtr
919){
dancf8f2892018-08-09 20:47:01 +0000920 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000921 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000922 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
923 if( (*pp)->p==pPtr ){
924 RenameToken *pToken = *pp;
dan6e6d9832021-02-16 20:43:36 +0000925 if( pCtx ){
926 *pp = pToken->pNext;
927 pToken->pNext = pCtx->pList;
928 pCtx->pList = pToken;
929 pCtx->nList++;
930 }
931 return pToken;
dancf8f2892018-08-09 20:47:01 +0000932 }
933 }
dan6e6d9832021-02-16 20:43:36 +0000934 return 0;
dancf8f2892018-08-09 20:47:01 +0000935}
936
dan24fedb92018-08-18 17:35:38 +0000937/*
938** This is a Walker select callback. It does nothing. It is only required
939** because without a dummy callback, sqlite3WalkExpr() and similar do not
940** descend into sub-select statements.
941*/
dan987db762018-08-14 20:18:50 +0000942static int renameColumnSelectCb(Walker *pWalker, Select *p){
dan38096962019-12-09 08:13:43 +0000943 if( p->selFlags & SF_View ) return WRC_Prune;
danea412512018-12-05 13:49:04 +0000944 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000945 return WRC_Continue;
946}
947
dan987db762018-08-14 20:18:50 +0000948/*
949** This is a Walker expression callback.
950**
951** For every TK_COLUMN node in the expression tree, search to see
952** if the column being references is the column being renamed by an
953** ALTER TABLE statement. If it is, then attach its associated
954** RenameToken object to the list of RenameToken objects being
955** constructed in RenameCtx object at pWalker->u.pRename.
956*/
dancf8f2892018-08-09 20:47:01 +0000957static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000958 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000959 if( pExpr->op==TK_TRIGGER
960 && pExpr->iColumn==p->iCol
961 && pWalker->pParse->pTriggerTab==p->pTab
962 ){
dan5be60c52018-08-15 20:28:39 +0000963 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000964 }else if( pExpr->op==TK_COLUMN
965 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000966 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000967 ){
dan5496d6a2018-08-13 17:14:26 +0000968 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000969 }
970 return WRC_Continue;
971}
972
dan987db762018-08-14 20:18:50 +0000973/*
974** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000975** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000976** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000977** RenameContext. "Last" means the last RenameToken encountered when
978** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000979** return all column name tokens in the order that they are encountered
980** in the SQL statement.
981*/
dan5496d6a2018-08-13 17:14:26 +0000982static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000983 RenameToken *pBest = pCtx->pList;
984 RenameToken *pToken;
985 RenameToken **pp;
986
987 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
988 if( pToken->t.z>pBest->t.z ) pBest = pToken;
989 }
990 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
991 *pp = pBest->pNext;
992
993 return pBest;
994}
995
dan6fe7f232018-08-10 19:19:33 +0000996/*
dan24fedb92018-08-18 17:35:38 +0000997** An error occured while parsing or otherwise processing a database
998** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
999** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1000** sub-routine is currently stored in pParse->zErrMsg. This function
1001** adds context to the error message and then stores it in pCtx.
1002*/
danb0137382018-08-20 20:01:01 +00001003static void renameColumnParseError(
1004 sqlite3_context *pCtx,
dan16953462021-02-18 19:25:44 +00001005 const char *zWhen,
danb0137382018-08-20 20:01:01 +00001006 sqlite3_value *pType,
1007 sqlite3_value *pObject,
1008 Parse *pParse
1009){
drh79a5ee92018-08-23 19:32:04 +00001010 const char *zT = (const char*)sqlite3_value_text(pType);
1011 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +00001012 char *zErr;
danb0137382018-08-20 20:01:01 +00001013
dan16953462021-02-18 19:25:44 +00001014 zErr = sqlite3_mprintf("error in %s %s%s%s: %s",
1015 zT, zN, (zWhen[0] ? " " : ""), zWhen,
dan0d5fa6b2018-08-24 17:55:49 +00001016 pParse->zErrMsg
1017 );
dan24fedb92018-08-18 17:35:38 +00001018 sqlite3_result_error(pCtx, zErr, -1);
1019 sqlite3_free(zErr);
1020}
1021
1022/*
dan06249392018-08-21 15:06:59 +00001023** For each name in the the expression-list pEList (i.e. each
1024** pEList->a[i].zName) that matches the string in zOld, extract the
1025** corresponding rename-token from Parse object pParse and add it
1026** to the RenameCtx pCtx.
1027*/
1028static void renameColumnElistNames(
1029 Parse *pParse,
1030 RenameCtx *pCtx,
1031 ExprList *pEList,
1032 const char *zOld
1033){
1034 if( pEList ){
1035 int i;
1036 for(i=0; i<pEList->nExpr; i++){
drh41cee662019-12-12 20:22:34 +00001037 char *zName = pEList->a[i].zEName;
drh9fc1b9a2020-01-02 22:23:01 +00001038 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME)
1039 && ALWAYS(zName!=0)
drhc4938ea2019-12-13 00:49:42 +00001040 && 0==sqlite3_stricmp(zName, zOld)
1041 ){
dan06249392018-08-21 15:06:59 +00001042 renameTokenFind(pParse, pCtx, (void*)zName);
1043 }
1044 }
1045 }
1046}
1047
1048/*
1049** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
1050** that matches the string in zOld, extract the corresponding rename-token
1051** from Parse object pParse and add it to the RenameCtx pCtx.
1052*/
1053static void renameColumnIdlistNames(
1054 Parse *pParse,
1055 RenameCtx *pCtx,
1056 IdList *pIdList,
1057 const char *zOld
1058){
1059 if( pIdList ){
1060 int i;
1061 for(i=0; i<pIdList->nId; i++){
1062 char *zName = pIdList->a[i].zName;
1063 if( 0==sqlite3_stricmp(zName, zOld) ){
1064 renameTokenFind(pParse, pCtx, (void*)zName);
1065 }
1066 }
1067 }
1068}
1069
danfb99e382020-04-03 11:20:40 +00001070
dandd1a9c82018-09-05 08:28:30 +00001071/*
1072** Parse the SQL statement zSql using Parse object (*p). The Parse object
1073** is initialized by this function before it is used.
1074*/
danc9461ec2018-08-29 21:00:16 +00001075static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +00001076 Parse *p, /* Memory to use for Parse object */
1077 const char *zDb, /* Name of schema SQL belongs to */
dandd1a9c82018-09-05 08:28:30 +00001078 sqlite3 *db, /* Database handle */
1079 const char *zSql, /* SQL to parse */
1080 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +00001081){
1082 int rc;
1083 char *zErr = 0;
1084
1085 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
1086
1087 /* Parse the SQL statement passed as the first argument. If no error
1088 ** occurs and the parse does not result in a new table, index or
1089 ** trigger object, the database must be corrupt. */
1090 memset(p, 0, sizeof(Parse));
dane6dc1e52019-12-05 14:31:43 +00001091 p->eParseMode = PARSE_MODE_RENAME;
danc9461ec2018-08-29 21:00:16 +00001092 p->db = db;
1093 p->nQueryLoop = 1;
drhdcc29e02021-02-18 23:03:50 +00001094 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001095 assert( p->zErrMsg==0 );
1096 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +00001097 p->zErrMsg = zErr;
1098 if( db->mallocFailed ) rc = SQLITE_NOMEM;
1099 if( rc==SQLITE_OK
1100 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1101 ){
1102 rc = SQLITE_CORRUPT_BKPT;
1103 }
1104
1105#ifdef SQLITE_DEBUG
1106 /* Ensure that all mappings in the Parse.pRename list really do map to
1107 ** a part of the input string. */
1108 if( rc==SQLITE_OK ){
1109 int nSql = sqlite3Strlen30(zSql);
1110 RenameToken *pToken;
1111 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1112 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1113 }
1114 }
1115#endif
1116
1117 db->init.iDb = 0;
1118 return rc;
1119}
1120
dandd1a9c82018-09-05 08:28:30 +00001121/*
1122** This function edits SQL statement zSql, replacing each token identified
1123** by the linked list pRename with the text of zNew. If argument bQuote is
1124** true, then zNew is always quoted first. If no error occurs, the result
1125** is loaded into context object pCtx as the result.
1126**
1127** Or, if an error occurs (i.e. an OOM condition), an error is left in
1128** pCtx and an SQLite error code returned.
1129*/
danc9461ec2018-08-29 21:00:16 +00001130static int renameEditSql(
1131 sqlite3_context *pCtx, /* Return result here */
1132 RenameCtx *pRename, /* Rename context */
1133 const char *zSql, /* SQL statement to edit */
1134 const char *zNew, /* New token text */
1135 int bQuote /* True to always quote token */
1136){
1137 int nNew = sqlite3Strlen30(zNew);
1138 int nSql = sqlite3Strlen30(zSql);
1139 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1140 int rc = SQLITE_OK;
dan1e240722021-03-15 20:22:34 +00001141 char *zQuot = 0;
danc9461ec2018-08-29 21:00:16 +00001142 char *zOut;
1143 int nQuot;
dan1e240722021-03-15 20:22:34 +00001144 char *zBuf1 = 0;
1145 char *zBuf2 = 0;
danc9461ec2018-08-29 21:00:16 +00001146
dan1e240722021-03-15 20:22:34 +00001147 if( zNew ){
1148 /* Set zQuot to point to a buffer containing a quoted copy of the
1149 ** identifier zNew. If the corresponding identifier in the original
1150 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1151 ** point to zQuot so that all substitutions are made using the
1152 ** quoted version of the new column name. */
1153 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
1154 if( zQuot==0 ){
1155 return SQLITE_NOMEM;
1156 }else{
1157 nQuot = sqlite3Strlen30(zQuot);
1158 }
1159 if( bQuote ){
1160 zNew = zQuot;
1161 nNew = nQuot;
1162 }
1163
1164 assert( nQuot>=nNew );
1165 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
danc9461ec2018-08-29 21:00:16 +00001166 }else{
dan1e240722021-03-15 20:22:34 +00001167 zOut = (char*)sqlite3DbMallocZero(db, (nSql*2+1) * 3);
1168 if( zOut ){
1169 zBuf1 = &zOut[nSql*2+1];
1170 zBuf2 = &zOut[nSql*4+2];
1171 }
danc9461ec2018-08-29 21:00:16 +00001172 }
1173
1174 /* At this point pRename->pList contains a list of RenameToken objects
1175 ** corresponding to all tokens in the input SQL that must be replaced
dan1e240722021-03-15 20:22:34 +00001176 ** with the new column name, or with single-quoted versions of themselves.
1177 ** All that remains is to construct and return the edited SQL string. */
danc9461ec2018-08-29 21:00:16 +00001178 if( zOut ){
1179 int nOut = nSql;
1180 memcpy(zOut, zSql, nSql);
1181 while( pRename->pList ){
1182 int iOff; /* Offset of token to replace in zOut */
danc9461ec2018-08-29 21:00:16 +00001183 u32 nReplace;
1184 const char *zReplace;
dan1e240722021-03-15 20:22:34 +00001185 RenameToken *pBest = renameColumnTokenNext(pRename);
1186
1187 if( zNew ){
1188 if( sqlite3IsIdChar(*pBest->t.z) ){
1189 nReplace = nNew;
1190 zReplace = zNew;
1191 }else{
1192 nReplace = nQuot;
1193 zReplace = zQuot;
1194 }
danc9461ec2018-08-29 21:00:16 +00001195 }else{
dan1e240722021-03-15 20:22:34 +00001196 /* Dequote the double-quoted token. Then requote it again, this time
1197 ** using single quotes. If the character immediately following the
1198 ** original token within the input SQL was a single quote ('), then
1199 ** add another space after the new, single-quoted version of the
1200 ** token. This is so that (SELECT "string"'alias') maps to
1201 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */
1202 memcpy(zBuf1, pBest->t.z, pBest->t.n);
1203 zBuf1[pBest->t.n] = 0;
1204 sqlite3Dequote(zBuf1);
1205 sqlite3_snprintf(nSql*2, zBuf2, "%Q%s", zBuf1,
1206 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
1207 );
1208 zReplace = zBuf2;
1209 nReplace = sqlite3Strlen30(zReplace);
danc9461ec2018-08-29 21:00:16 +00001210 }
1211
1212 iOff = pBest->t.z - zSql;
1213 if( pBest->t.n!=nReplace ){
1214 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1215 nOut - (iOff + pBest->t.n)
1216 );
1217 nOut += nReplace - pBest->t.n;
1218 zOut[nOut] = '\0';
1219 }
1220 memcpy(&zOut[iOff], zReplace, nReplace);
1221 sqlite3DbFree(db, pBest);
1222 }
1223
1224 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1225 sqlite3DbFree(db, zOut);
1226 }else{
1227 rc = SQLITE_NOMEM;
1228 }
1229
1230 sqlite3_free(zQuot);
1231 return rc;
1232}
1233
dandd1a9c82018-09-05 08:28:30 +00001234/*
1235** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1236** it was read from the schema of database zDb. Return SQLITE_OK if
1237** successful. Otherwise, return an SQLite error code and leave an error
1238** message in the Parse object.
1239*/
drha7c74002020-07-18 18:44:59 +00001240static int renameResolveTrigger(Parse *pParse){
danc9461ec2018-08-29 21:00:16 +00001241 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001242 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001243 TriggerStep *pStep;
1244 NameContext sNC;
1245 int rc = SQLITE_OK;
1246
1247 memset(&sNC, 0, sizeof(sNC));
1248 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001249 assert( pNew->pTabSchema );
1250 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1251 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1252 );
1253 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001254 /* ALWAYS() because if the table of the trigger does not exist, the
1255 ** error would have been hit before this point */
1256 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001257 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1258 }
danc9461ec2018-08-29 21:00:16 +00001259
1260 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001261 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001262 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001263 }
1264
dand5e6fef2018-09-07 15:50:31 +00001265 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001266 if( pStep->pSelect ){
1267 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1268 if( pParse->nErr ) rc = pParse->rc;
1269 }
dand5e6fef2018-09-07 15:50:31 +00001270 if( rc==SQLITE_OK && pStep->zTarget ){
dane7877b22020-07-14 19:51:01 +00001271 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep);
1272 if( pSrc ){
1273 int i;
drha3e64952020-08-12 16:19:12 +00001274 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){
drh76012942021-02-21 21:04:54 +00001275 SrcItem *p = &pSrc->a[i];
dane7877b22020-07-14 19:51:01 +00001276 p->iCursor = pParse->nTab++;
dan7a39fae2020-10-31 16:33:01 +00001277 if( p->pSelect ){
1278 sqlite3SelectPrep(pParse, p->pSelect, 0);
1279 sqlite3ExpandSubquery(pParse, p);
1280 assert( i>0 );
1281 assert( pStep->pFrom->a[i-1].pSelect );
1282 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0);
dane7877b22020-07-14 19:51:01 +00001283 }else{
dan7a39fae2020-10-31 16:33:01 +00001284 p->pTab = sqlite3LocateTableItem(pParse, 0, p);
1285 if( p->pTab==0 ){
1286 rc = SQLITE_ERROR;
1287 }else{
1288 p->pTab->nTabRef++;
1289 rc = sqlite3ViewGetColumnNames(pParse, p->pTab);
1290 }
dane7877b22020-07-14 19:51:01 +00001291 }
1292 }
1293 sNC.pSrcList = pSrc;
1294 if( rc==SQLITE_OK && pStep->pWhere ){
danc9461ec2018-08-29 21:00:16 +00001295 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1296 }
1297 if( rc==SQLITE_OK ){
1298 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1299 }
1300 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
drhe58b2b42021-03-08 17:17:38 +00001301 if( pStep->pUpsert && rc==SQLITE_OK ){
danc9461ec2018-08-29 21:00:16 +00001302 Upsert *pUpsert = pStep->pUpsert;
dane7877b22020-07-14 19:51:01 +00001303 pUpsert->pUpsertSrc = pSrc;
danc9461ec2018-08-29 21:00:16 +00001304 sNC.uNC.pUpsert = pUpsert;
1305 sNC.ncFlags = NC_UUpsert;
1306 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1307 if( rc==SQLITE_OK ){
1308 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1309 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1310 }
1311 if( rc==SQLITE_OK ){
1312 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1313 }
1314 if( rc==SQLITE_OK ){
1315 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1316 }
1317 sNC.ncFlags = 0;
1318 }
dan0e14e982019-01-18 16:06:18 +00001319 sNC.pSrcList = 0;
dane7877b22020-07-14 19:51:01 +00001320 sqlite3SrcListDelete(db, pSrc);
1321 }else{
1322 rc = SQLITE_NOMEM;
danc9461ec2018-08-29 21:00:16 +00001323 }
1324 }
1325 }
1326 return rc;
1327}
1328
dandd1a9c82018-09-05 08:28:30 +00001329/*
1330** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1331** objects that are part of the trigger passed as the second argument.
1332*/
danc9461ec2018-08-29 21:00:16 +00001333static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1334 TriggerStep *pStep;
1335
1336 /* Find tokens to edit in WHEN clause */
1337 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1338
1339 /* Find tokens to edit in trigger steps */
1340 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1341 sqlite3WalkSelect(pWalker, pStep->pSelect);
1342 sqlite3WalkExpr(pWalker, pStep->pWhere);
1343 sqlite3WalkExprList(pWalker, pStep->pExprList);
1344 if( pStep->pUpsert ){
1345 Upsert *pUpsert = pStep->pUpsert;
1346 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1347 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1348 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1349 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1350 }
dan7a39fae2020-10-31 16:33:01 +00001351 if( pStep->pFrom ){
1352 int i;
1353 for(i=0; i<pStep->pFrom->nSrc; i++){
1354 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
1355 }
1356 }
danc9461ec2018-08-29 21:00:16 +00001357 }
1358}
1359
dandd1a9c82018-09-05 08:28:30 +00001360/*
1361** Free the contents of Parse object (*pParse). Do not free the memory
1362** occupied by the Parse object itself.
1363*/
dan141e1192018-08-31 18:23:53 +00001364static void renameParseCleanup(Parse *pParse){
1365 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001366 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001367 if( pParse->pVdbe ){
1368 sqlite3VdbeFinalize(pParse->pVdbe);
1369 }
1370 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001371 while( (pIdx = pParse->pNewIndex)!=0 ){
1372 pParse->pNewIndex = pIdx->pNext;
1373 sqlite3FreeIndex(db, pIdx);
1374 }
dan141e1192018-08-31 18:23:53 +00001375 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1376 sqlite3DbFree(db, pParse->zErrMsg);
1377 renameTokenFree(db, pParse->pRename);
1378 sqlite3ParserReset(pParse);
1379}
1380
dan06249392018-08-21 15:06:59 +00001381/*
dan987db762018-08-14 20:18:50 +00001382** SQL function:
1383**
1384** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1385**
1386** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001387** 1. type: Type of object ("table", "view" etc.)
1388** 2. object: Name of object
1389** 3. Database: Database name (e.g. "main")
1390** 4. Table: Table name
1391** 5. iCol: Index of column to rename
1392** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001393** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001394** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001395**
1396** Do a column rename operation on the CREATE statement given in zSql.
1397** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1398** into zNew. The name should be quoted if bQuote is true.
1399**
1400** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001401** It is only accessible to SQL created using sqlite3NestedParse(). It is
1402** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001403*/
dancf8f2892018-08-09 20:47:01 +00001404static void renameColumnFunc(
1405 sqlite3_context *context,
1406 int NotUsed,
1407 sqlite3_value **argv
1408){
1409 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001410 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001411 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001412 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1413 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1414 int iCol = sqlite3_value_int(argv[5]);
1415 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001416 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001417 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001418 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001419 int rc;
dancf8f2892018-08-09 20:47:01 +00001420 Parse sParse;
1421 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001422 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001423 int i;
dan987db762018-08-14 20:18:50 +00001424 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001425#ifndef SQLITE_OMIT_AUTHORIZATION
1426 sqlite3_xauth xAuth = db->xAuth;
1427#endif
dancf8f2892018-08-09 20:47:01 +00001428
drh38d99642018-08-18 18:27:18 +00001429 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001430 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001431 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001432 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001433 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001434 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001435 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001436 if( pTab==0 || iCol>=pTab->nCol ){
1437 sqlite3BtreeLeaveAll(db);
1438 return;
1439 }
dan987db762018-08-14 20:18:50 +00001440 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001441 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001442 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001443
dan141e1192018-08-31 18:23:53 +00001444#ifndef SQLITE_OMIT_AUTHORIZATION
1445 db->xAuth = 0;
1446#endif
drhb2ab3dc2019-12-20 14:08:34 +00001447 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001448
dancf8f2892018-08-09 20:47:01 +00001449 /* Find tokens that need to be replaced. */
1450 memset(&sWalker, 0, sizeof(Walker));
1451 sWalker.pParse = &sParse;
1452 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001453 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001454 sWalker.u.pRename = &sCtx;
1455
dan0cbb0b12018-08-16 19:49:16 +00001456 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001457 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001458 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001459 Select *pSelect = sParse.pNewTable->pSelect;
1460 if( pSelect ){
dan38096962019-12-09 08:13:43 +00001461 pSelect->selFlags &= ~SF_View;
dan987db762018-08-14 20:18:50 +00001462 sParse.rc = SQLITE_OK;
dan38096962019-12-09 08:13:43 +00001463 sqlite3SelectPrep(&sParse, pSelect, 0);
dan987db762018-08-14 20:18:50 +00001464 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1465 if( rc==SQLITE_OK ){
1466 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001467 }
dan987db762018-08-14 20:18:50 +00001468 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1469 }else{
1470 /* A regular table */
1471 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1472 FKey *pFKey;
1473 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001474 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001475 if( bFKOnly==0 ){
1476 renameTokenFind(
1477 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1478 );
1479 if( sCtx.iCol<0 ){
1480 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001481 }
dan987db762018-08-14 20:18:50 +00001482 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1483 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1484 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1485 }
drh885eeb62019-01-09 02:02:24 +00001486 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1487 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1488 }
drhb9bcf7c2019-10-19 13:29:10 +00001489#ifndef SQLITE_OMIT_GENERATED_COLUMNS
dan776a5782021-03-16 11:11:07 +00001490 for(i=0; i<sParse.pNewTable->nCol; i++){
1491 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1492 }
drhb9bcf7c2019-10-19 13:29:10 +00001493#endif
dan776a5782021-03-16 11:11:07 +00001494 }
dan987db762018-08-14 20:18:50 +00001495
1496 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1497 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001498 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001499 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1500 }
1501 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1502 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1503 ){
1504 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1505 }
dan6fe7f232018-08-10 19:19:33 +00001506 }
dancf8f2892018-08-09 20:47:01 +00001507 }
1508 }
dan5496d6a2018-08-13 17:14:26 +00001509 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001510 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1511 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001512 }else{
dan5be60c52018-08-15 20:28:39 +00001513 /* A trigger */
1514 TriggerStep *pStep;
drha7c74002020-07-18 18:44:59 +00001515 rc = renameResolveTrigger(&sParse);
danc9461ec2018-08-29 21:00:16 +00001516 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001517
danc9461ec2018-08-29 21:00:16 +00001518 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1519 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001520 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001521 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001522 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001523 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1524 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001525 }
danc9461ec2018-08-29 21:00:16 +00001526 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1527 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001528 }
1529 }
1530 }
1531
dan5be60c52018-08-15 20:28:39 +00001532
1533 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001534 if( sParse.pTriggerTab==pTab ){
1535 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001536 }
dan5be60c52018-08-15 20:28:39 +00001537
danc9461ec2018-08-29 21:00:16 +00001538 /* Find tokens to edit in various expressions and selects */
1539 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001540 }
1541
dan987db762018-08-14 20:18:50 +00001542 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001543 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001544
drh5fc22cd2018-08-13 13:43:11 +00001545renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001546 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001547 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001548 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001549 }else{
1550 sqlite3_result_error_code(context, rc);
1551 }
1552 }
1553
dan141e1192018-08-31 18:23:53 +00001554 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001555 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001556#ifndef SQLITE_OMIT_AUTHORIZATION
1557 db->xAuth = xAuth;
1558#endif
drhda76adc2018-08-25 02:04:05 +00001559 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001560}
1561
dandd1a9c82018-09-05 08:28:30 +00001562/*
1563** Walker expression callback used by "RENAME TABLE".
1564*/
danc9461ec2018-08-29 21:00:16 +00001565static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1566 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001567 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1568 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001569 }
1570 return WRC_Continue;
1571}
1572
1573/*
dandd1a9c82018-09-05 08:28:30 +00001574** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001575*/
1576static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1577 int i;
1578 RenameCtx *p = pWalker->u.pRename;
1579 SrcList *pSrc = pSelect->pSrc;
dan38096962019-12-09 08:13:43 +00001580 if( pSelect->selFlags & SF_View ) return WRC_Prune;
drh92a28242019-10-09 15:37:58 +00001581 if( pSrc==0 ){
1582 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001583 return WRC_Abort;
1584 }
danc9461ec2018-08-29 21:00:16 +00001585 for(i=0; i<pSrc->nSrc; i++){
drh76012942021-02-21 21:04:54 +00001586 SrcItem *pItem = &pSrc->a[i];
danc9461ec2018-08-29 21:00:16 +00001587 if( pItem->pTab==p->pTab ){
1588 renameTokenFind(pWalker->pParse, p, pItem->zName);
1589 }
1590 }
danea412512018-12-05 13:49:04 +00001591 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001592
1593 return WRC_Continue;
1594}
1595
1596
1597/*
1598** This C function implements an SQL user function that is used by SQL code
1599** generated by the ALTER TABLE ... RENAME command to modify the definition
1600** of any foreign key constraints that use the table being renamed as the
1601** parent table. It is passed three arguments:
1602**
dan141e1192018-08-31 18:23:53 +00001603** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001604** 1. type: Type of object ("table", "view" etc.)
1605** 2. object: Name of object
1606** 3: The complete text of the schema statement being modified,
1607** 4: The old name of the table being renamed, and
1608** 5: The new name of the table being renamed.
1609** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001610**
dan141e1192018-08-31 18:23:53 +00001611** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001612**
dan141e1192018-08-31 18:23:53 +00001613** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001614** -> 'CREATE TABLE t1(a REFERENCES t3)'
1615*/
1616static void renameTableFunc(
1617 sqlite3_context *context,
1618 int NotUsed,
1619 sqlite3_value **argv
1620){
1621 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001622 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001623 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1624 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1625 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1626 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001627 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001628
dan141e1192018-08-31 18:23:53 +00001629 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001630 Parse sParse;
1631 int rc;
1632 int bQuote = 1;
1633 RenameCtx sCtx;
1634 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001635
dan141e1192018-08-31 18:23:53 +00001636#ifndef SQLITE_OMIT_AUTHORIZATION
1637 sqlite3_xauth xAuth = db->xAuth;
1638 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001639#endif
1640
dan141e1192018-08-31 18:23:53 +00001641 sqlite3BtreeEnterAll(db);
1642
1643 memset(&sCtx, 0, sizeof(RenameCtx));
1644 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1645 memset(&sWalker, 0, sizeof(Walker));
1646 sWalker.pParse = &sParse;
1647 sWalker.xExprCallback = renameTableExprCb;
1648 sWalker.xSelectCallback = renameTableSelectCb;
1649 sWalker.u.pRename = &sCtx;
1650
drhb2ab3dc2019-12-20 14:08:34 +00001651 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan141e1192018-08-31 18:23:53 +00001652
1653 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001654 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001655 if( sParse.pNewTable ){
1656 Table *pTab = sParse.pNewTable;
1657
1658 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001659 if( isLegacy==0 ){
dan38096962019-12-09 08:13:43 +00001660 Select *pSelect = pTab->pSelect;
dan674b8942018-09-20 08:28:01 +00001661 NameContext sNC;
1662 memset(&sNC, 0, sizeof(sNC));
1663 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001664
dan38096962019-12-09 08:13:43 +00001665 assert( pSelect->selFlags & SF_View );
1666 pSelect->selFlags &= ~SF_View;
dan674b8942018-09-20 08:28:01 +00001667 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
drh1548d522019-12-20 12:55:21 +00001668 if( sParse.nErr ){
1669 rc = sParse.rc;
1670 }else{
1671 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1672 }
dan674b8942018-09-20 08:28:01 +00001673 }
dan141e1192018-08-31 18:23:53 +00001674 }else{
1675 /* Modify any FK definitions to point to the new table. */
1676#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001677 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001678 FKey *pFKey;
1679 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1680 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1681 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1682 }
dan141e1192018-08-31 18:23:53 +00001683 }
1684 }
1685#endif
1686
1687 /* If this is the table being altered, fix any table refs in CHECK
1688 ** expressions. Also update the name that appears right after the
1689 ** "CREATE [VIRTUAL] TABLE" bit. */
1690 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1691 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001692 if( isLegacy==0 ){
1693 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1694 }
dan141e1192018-08-31 18:23:53 +00001695 renameTokenFind(&sParse, &sCtx, pTab->zName);
1696 }
danc9461ec2018-08-29 21:00:16 +00001697 }
1698 }
danc9461ec2018-08-29 21:00:16 +00001699
dan141e1192018-08-31 18:23:53 +00001700 else if( sParse.pNewIndex ){
1701 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001702 if( isLegacy==0 ){
1703 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1704 }
dan141e1192018-08-31 18:23:53 +00001705 }
danc9461ec2018-08-29 21:00:16 +00001706
1707#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001708 else{
dan141e1192018-08-31 18:23:53 +00001709 Trigger *pTrigger = sParse.pNewTrigger;
1710 TriggerStep *pStep;
1711 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1712 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1713 ){
1714 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1715 }
danc9461ec2018-08-29 21:00:16 +00001716
dan674b8942018-09-20 08:28:01 +00001717 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001718 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001719 if( rc==SQLITE_OK ){
1720 renameWalkTrigger(&sWalker, pTrigger);
1721 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1722 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1723 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1724 }
dan141e1192018-08-31 18:23:53 +00001725 }
dan0ccda962018-08-30 16:26:48 +00001726 }
danc9461ec2018-08-29 21:00:16 +00001727 }
1728 }
dan141e1192018-08-31 18:23:53 +00001729#endif
danc9461ec2018-08-29 21:00:16 +00001730 }
dan141e1192018-08-31 18:23:53 +00001731
1732 if( rc==SQLITE_OK ){
1733 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1734 }
1735 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001736 if( sParse.zErrMsg ){
dan16953462021-02-18 19:25:44 +00001737 renameColumnParseError(context, "", argv[1], argv[2], &sParse);
dan65372fa2018-09-03 20:05:15 +00001738 }else{
1739 sqlite3_result_error_code(context, rc);
1740 }
dan141e1192018-08-31 18:23:53 +00001741 }
1742
1743 renameParseCleanup(&sParse);
1744 renameTokenFree(db, sCtx.pList);
1745 sqlite3BtreeLeaveAll(db);
1746#ifndef SQLITE_OMIT_AUTHORIZATION
1747 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001748#endif
1749 }
1750
danc9461ec2018-08-29 21:00:16 +00001751 return;
1752}
1753
dan1e240722021-03-15 20:22:34 +00001754static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){
1755 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
1756 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (void*)pExpr);
1757 }
1758 return WRC_Continue;
1759}
1760
1761/*
1762** The implementation of an SQL scalar function that rewrites DDL statements
1763** so that any string literals that use double-quotes are modified so that
1764** they use single quotes.
1765**
1766** Two arguments must be passed:
1767**
1768** 0: Database name ("main", "temp" etc.).
1769** 1: SQL statement to edit.
1770**
1771** The returned value is the modified SQL statement. For example, given
1772** the database schema:
1773**
1774** CREATE TABLE t1(a, b, c);
1775**
1776** SELECT sqlite_rename_quotefix('main',
1777** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1'
1778** );
1779**
1780** returns the string:
1781**
1782** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1
1783*/
1784static void renameQuotefixFunc(
1785 sqlite3_context *context,
1786 int NotUsed,
1787 sqlite3_value **argv
1788){
1789 sqlite3 *db = sqlite3_context_db_handle(context);
1790 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1791 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
1792
1793#ifndef SQLITE_OMIT_AUTHORIZATION
1794 sqlite3_xauth xAuth = db->xAuth;
1795 db->xAuth = 0;
1796#endif
1797
1798 sqlite3BtreeEnterAll(db);
1799
1800 UNUSED_PARAMETER(NotUsed);
1801 if( zDb && zInput ){
1802 int rc;
1803 Parse sParse;
1804 rc = renameParseSql(&sParse, zDb, db, zInput, 0);
1805
1806 if( rc==SQLITE_OK ){
1807 RenameCtx sCtx;
1808 Walker sWalker;
1809
1810 /* Walker to find tokens that need to be replaced. */
1811 memset(&sCtx, 0, sizeof(RenameCtx));
1812 memset(&sWalker, 0, sizeof(Walker));
1813 sWalker.pParse = &sParse;
1814 sWalker.xExprCallback = renameQuotefixExprCb;
1815 sWalker.xSelectCallback = renameColumnSelectCb;
1816 sWalker.u.pRename = &sCtx;
1817
1818 if( sParse.pNewTable ){
1819 Select *pSelect = sParse.pNewTable->pSelect;
1820 if( pSelect ){
1821 pSelect->selFlags &= ~SF_View;
1822 sParse.rc = SQLITE_OK;
1823 sqlite3SelectPrep(&sParse, pSelect, 0);
1824 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1825 if( rc==SQLITE_OK ){
1826 sqlite3WalkSelect(&sWalker, pSelect);
1827 }
1828 }else{
1829 int i;
1830 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1831#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1832 for(i=0; i<sParse.pNewTable->nCol; i++){
1833 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1834 }
1835#endif /* SQLITE_OMIT_GENERATED_COLUMNS */
1836 }
1837 }else if( sParse.pNewIndex ){
1838 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1839 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1840 }else{
1841#ifndef SQLITE_OMIT_TRIGGER
1842 rc = renameResolveTrigger(&sParse);
1843 if( rc==SQLITE_OK ){
1844 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
1845 }
1846#endif /* SQLITE_OMIT_TRIGGER */
1847 }
1848
1849 if( rc==SQLITE_OK ){
1850 rc = renameEditSql(context, &sCtx, zInput, 0, 0);
1851 }
dan1fffa732021-03-16 18:24:49 +00001852 renameTokenFree(db, sCtx.pList);
dan1e240722021-03-15 20:22:34 +00001853 }
1854 if( rc!=SQLITE_OK ){
1855 sqlite3_result_error_code(context, rc);
1856 }
1857 renameParseCleanup(&sParse);
1858 }
1859
1860#ifndef SQLITE_OMIT_AUTHORIZATION
1861 db->xAuth = xAuth;
1862#endif
1863
1864 sqlite3BtreeLeaveAll(db);
1865}
1866
dandd1a9c82018-09-05 08:28:30 +00001867/*
1868** An SQL user function that checks that there are no parse or symbol
1869** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1870** After an ALTER TABLE .. RENAME operation is performed and the schema
1871** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001872** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001873**
1874** 0: Database name ("main", "temp" etc.).
1875** 1: SQL statement.
1876** 2: Object type ("view", "table", "trigger" or "index").
1877** 3: Object name.
1878** 4: True if object is from temp schema.
dan16953462021-02-18 19:25:44 +00001879** 5: "when" part of error message.
dan2ad080a2021-03-16 16:14:48 +00001880** 6: True to disable the DQS quirk when parsing SQL.
dan1d85c6b2018-09-06 16:01:37 +00001881**
1882** Unless it finds an error, this function normally returns NULL. However, it
1883** returns integer value 1 if:
1884**
1885** * the SQL argument creates a trigger, and
1886** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001887*/
dan9d324822018-08-30 20:03:44 +00001888static void renameTableTest(
1889 sqlite3_context *context,
1890 int NotUsed,
1891 sqlite3_value **argv
1892){
1893 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001894 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1895 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001896 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001897 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan16953462021-02-18 19:25:44 +00001898 char const *zWhen = (const char*)sqlite3_value_text(argv[5]);
dan2ad080a2021-03-16 16:14:48 +00001899 int bNoDQS = sqlite3_value_int(argv[6]);
dan9d324822018-08-30 20:03:44 +00001900
dan141e1192018-08-31 18:23:53 +00001901#ifndef SQLITE_OMIT_AUTHORIZATION
1902 sqlite3_xauth xAuth = db->xAuth;
1903 db->xAuth = 0;
1904#endif
1905
drh5b1da302018-09-01 20:02:07 +00001906 UNUSED_PARAMETER(NotUsed);
dan2ad080a2021-03-16 16:14:48 +00001907
dan09236502018-09-01 16:05:50 +00001908 if( zDb && zInput ){
1909 int rc;
1910 Parse sParse;
dan2ad080a2021-03-16 16:14:48 +00001911 int flags = db->flags;
1912 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
drhb2ab3dc2019-12-20 14:08:34 +00001913 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp);
dan2ad080a2021-03-16 16:14:48 +00001914 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
dan09236502018-09-01 16:05:50 +00001915 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001916 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001917 NameContext sNC;
1918 memset(&sNC, 0, sizeof(sNC));
1919 sNC.pParse = &sParse;
1920 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1921 if( sParse.nErr ) rc = sParse.rc;
1922 }
1923
1924 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001925 if( isLegacy==0 ){
drha7c74002020-07-18 18:44:59 +00001926 rc = renameResolveTrigger(&sParse);
dan674b8942018-09-20 08:28:01 +00001927 }
drh3b700452018-09-07 19:12:08 +00001928 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001929 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1930 int i2 = sqlite3FindDbName(db, zDb);
1931 if( i1==i2 ) sqlite3_result_int(context, 1);
1932 }
dan09236502018-09-01 16:05:50 +00001933 }
dan9d324822018-08-30 20:03:44 +00001934 }
1935
dan16953462021-02-18 19:25:44 +00001936 if( rc!=SQLITE_OK && zWhen ){
1937 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse);
dan9d324822018-08-30 20:03:44 +00001938 }
dan09236502018-09-01 16:05:50 +00001939 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001940 }
1941
dan141e1192018-08-31 18:23:53 +00001942#ifndef SQLITE_OMIT_AUTHORIZATION
1943 db->xAuth = xAuth;
1944#endif
dan9d324822018-08-30 20:03:44 +00001945}
1946
dancf8f2892018-08-09 20:47:01 +00001947/*
dan6a5a13d2021-02-17 20:08:22 +00001948** The implementation of internal UDF sqlite_drop_column().
1949**
dan6e6d9832021-02-16 20:43:36 +00001950** Arguments:
1951**
1952** argv[0]: An integer - the index of the schema containing the table
1953** argv[1]: CREATE TABLE statement to modify.
1954** argv[2]: An integer - the index of the column to remove.
dan6a5a13d2021-02-17 20:08:22 +00001955**
1956** The value returned is a string containing the CREATE TABLE statement
1957** with column argv[2] removed.
dan6e6d9832021-02-16 20:43:36 +00001958*/
1959static void dropColumnFunc(
1960 sqlite3_context *context,
1961 int NotUsed,
1962 sqlite3_value **argv
1963){
1964 sqlite3 *db = sqlite3_context_db_handle(context);
1965 int iSchema = sqlite3_value_int(argv[0]);
1966 const char *zSql = (const char*)sqlite3_value_text(argv[1]);
1967 int iCol = sqlite3_value_int(argv[2]);
dan6e6d9832021-02-16 20:43:36 +00001968 const char *zDb = db->aDb[iSchema].zDbSName;
1969 int rc;
1970 Parse sParse;
1971 RenameToken *pCol;
1972 Table *pTab;
1973 const char *zEnd;
1974 char *zNew = 0;
1975
dan678f3b32021-02-18 20:27:46 +00001976#ifndef SQLITE_OMIT_AUTHORIZATION
1977 sqlite3_xauth xAuth = db->xAuth;
1978 db->xAuth = 0;
1979#endif
1980
drh05edf722021-03-04 19:44:01 +00001981 UNUSED_PARAMETER(NotUsed);
dan6e6d9832021-02-16 20:43:36 +00001982 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1);
1983 if( rc!=SQLITE_OK ) goto drop_column_done;
1984 pTab = sParse.pNewTable;
drh747cc942021-03-06 13:02:12 +00001985 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
danf4a72782021-02-19 14:13:40 +00001986 /* This can happen if the sqlite_schema table is corrupt */
1987 rc = SQLITE_CORRUPT_BKPT;
1988 goto drop_column_done;
1989 }
dan6e6d9832021-02-16 20:43:36 +00001990
1991 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName);
1992 if( iCol<pTab->nCol-1 ){
1993 RenameToken *pEnd;
1994 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName);
1995 zEnd = (const char*)pEnd->t.z;
1996 }else{
dan578277c2021-02-19 18:39:32 +00001997 zEnd = (const char*)&zSql[pTab->addColOffset];
drh60fe2352021-02-19 09:46:52 +00001998 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
dan6e6d9832021-02-16 20:43:36 +00001999 }
2000
danc2a878e2021-02-17 20:46:44 +00002001 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
dan6e6d9832021-02-16 20:43:36 +00002002 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
2003 sqlite3_free(zNew);
2004
2005drop_column_done:
2006 renameParseCleanup(&sParse);
dan678f3b32021-02-18 20:27:46 +00002007#ifndef SQLITE_OMIT_AUTHORIZATION
2008 db->xAuth = xAuth;
2009#endif
danf4a72782021-02-19 14:13:40 +00002010 if( rc!=SQLITE_OK ){
2011 sqlite3_result_error_code(context, rc);
2012 }
dan6e6d9832021-02-16 20:43:36 +00002013}
2014
dan6a5a13d2021-02-17 20:08:22 +00002015/*
2016** This function is called by the parser upon parsing an
2017**
2018** ALTER TABLE pSrc DROP COLUMN pName
2019**
2020** statement. Argument pSrc contains the possibly qualified name of the
2021** table being edited, and token pName the name of the column to drop.
2022*/
dan6e6d9832021-02-16 20:43:36 +00002023void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){
dan6a5a13d2021-02-17 20:08:22 +00002024 sqlite3 *db = pParse->db; /* Database handle */
2025 Table *pTab; /* Table to modify */
2026 int iDb; /* Index of db containing pTab in aDb[] */
2027 const char *zDb; /* Database containing pTab ("main" etc.) */
2028 char *zCol = 0; /* Name of column to drop */
2029 int iCol; /* Index of column zCol in pTab->aCol[] */
dan6e6d9832021-02-16 20:43:36 +00002030
2031 /* Look up the table being altered. */
2032 assert( pParse->pNewTable==0 );
2033 assert( sqlite3BtreeHoldsAllMutexes(db) );
drhc90fa012021-02-19 02:30:02 +00002034 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002035 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
2036 if( !pTab ) goto exit_drop_column;
2037
dan6a5a13d2021-02-17 20:08:22 +00002038 /* Make sure this is not an attempt to ALTER a view, virtual table or
2039 ** system table. */
2040 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column;
2041 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column;
dan6e6d9832021-02-16 20:43:36 +00002042
2043 /* Find the index of the column being dropped. */
2044 zCol = sqlite3NameFromToken(db, pName);
2045 if( zCol==0 ){
2046 assert( db->mallocFailed );
2047 goto exit_drop_column;
2048 }
2049 iCol = sqlite3ColumnIndex(pTab, zCol);
2050 if( iCol<0 ){
2051 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol);
2052 goto exit_drop_column;
2053 }
2054
2055 /* Do not allow the user to drop a PRIMARY KEY column or a column
2056 ** constrained by a UNIQUE constraint. */
dan6a5a13d2021-02-17 20:08:22 +00002057 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
2058 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"",
2059 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
2060 zCol
2061 );
dan6e6d9832021-02-16 20:43:36 +00002062 goto exit_drop_column;
2063 }
dan6e6d9832021-02-16 20:43:36 +00002064
drh239c84f2021-02-19 09:09:07 +00002065 /* Do not allow the number of columns to go to zero */
2066 if( pTab->nCol<=1 ){
2067 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol);
2068 goto exit_drop_column;
2069 }
2070
dan6a5a13d2021-02-17 20:08:22 +00002071 /* Edit the sqlite_schema table */
2072 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2073 assert( iDb>=0 );
2074 zDb = db->aDb[iDb].zDbSName;
dan2ad080a2021-03-16 16:14:48 +00002075 renameTestSchema(pParse, zDb, iDb==1, "", 0);
2076 renameFixQuotes(pParse, zDb, iDb==1);
dan6e6d9832021-02-16 20:43:36 +00002077 sqlite3NestedParse(pParse,
2078 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET "
dan578277c2021-02-19 18:39:32 +00002079 "sql = sqlite_drop_column(%d, sql, %d) "
dan6e6d9832021-02-16 20:43:36 +00002080 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)"
dan578277c2021-02-19 18:39:32 +00002081 , zDb, iDb, iCol, pTab->zName
dan6e6d9832021-02-16 20:43:36 +00002082 );
2083
2084 /* Drop and reload the database schema. */
dan6a5a13d2021-02-17 20:08:22 +00002085 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop);
dan2ad080a2021-03-16 16:14:48 +00002086 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1);
dan6e6d9832021-02-16 20:43:36 +00002087
2088 /* Edit rows of table on disk */
danc2a878e2021-02-17 20:46:44 +00002089 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
dan6a5a13d2021-02-17 20:08:22 +00002090 int i;
2091 int addr;
2092 int reg;
2093 int regRec;
2094 Index *pPk = 0;
2095 int nField = 0; /* Number of non-virtual columns after drop */
2096 int iCur;
2097 Vdbe *v = sqlite3GetVdbe(pParse);
2098 iCur = pParse->nTab++;
2099 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
drh03361402021-02-18 23:53:47 +00002100 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002101 reg = ++pParse->nMem;
2102 pParse->nMem += pTab->nCol;
2103 if( HasRowid(pTab) ){
2104 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg);
2105 }else{
2106 pPk = sqlite3PrimaryKeyIndex(pTab);
dan6e6d9832021-02-16 20:43:36 +00002107 }
dan6a5a13d2021-02-17 20:08:22 +00002108 for(i=0; i<pTab->nCol; i++){
2109 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
2110 int regOut;
2111 if( pPk ){
2112 int iPos = sqlite3TableColumnToIndex(pPk, i);
2113 int iColPos = sqlite3TableColumnToIndex(pPk, iCol);
2114 regOut = reg+1+iPos-(iPos>iColPos);
2115 }else{
2116 regOut = reg+1+nField;
2117 }
2118 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut);
2119 nField++;
2120 }
2121 }
2122 regRec = reg + pTab->nCol;
2123 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec);
2124 if( pPk ){
2125 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
2126 }else{
2127 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg);
2128 }
dan6e6d9832021-02-16 20:43:36 +00002129
drh03361402021-02-18 23:53:47 +00002130 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v);
dan6a5a13d2021-02-17 20:08:22 +00002131 sqlite3VdbeJumpHere(v, addr);
2132 }
dan6e6d9832021-02-16 20:43:36 +00002133
2134exit_drop_column:
2135 sqlite3DbFree(db, zCol);
2136 sqlite3SrcListDelete(db, pSrc);
dan6e6d9832021-02-16 20:43:36 +00002137}
2138
2139/*
dancf8f2892018-08-09 20:47:01 +00002140** Register built-in functions used to help implement ALTER TABLE
2141*/
2142void sqlite3AlterFunctions(void){
2143 static FuncDef aAlterTableFuncs[] = {
dan6e6d9832021-02-16 20:43:36 +00002144 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
2145 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
dan2ad080a2021-03-16 16:14:48 +00002146 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest),
dan578277c2021-02-19 18:39:32 +00002147 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc),
dan1e240722021-03-15 20:22:34 +00002148 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc),
dancf8f2892018-08-09 20:47:01 +00002149 };
2150 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
2151}
drhd0e4a6c2005-02-15 20:47:57 +00002152#endif /* SQLITE_ALTER_TABLE */