blob: 0a82327d632593a08e893cd710c23cfadee49a04 [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
34 || ( (pTab->tabFlags & TF_Shadow)
35 && (pParse->db->flags & SQLITE_Defensive)
36 && pParse->db->nVdbeExec==0
37 )
38#endif
39 ){
40 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danbe535002011-04-01 15:15:58 +000041 return 1;
42 }
43 return 0;
44}
45
dan09236502018-09-01 16:05:50 +000046/*
47** Generate code to verify that the schemas of database zDb and, if
48** bTemp is not true, database "temp", can still be parsed. This is
49** called at the end of the generation of an ALTER TABLE ... RENAME ...
50** statement to ensure that the operation has not rendered any schema
51** objects unusable.
52*/
drh16b870d2018-09-12 15:51:56 +000053static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
dan9d324822018-08-30 20:03:44 +000054 sqlite3NestedParse(pParse,
55 "SELECT 1 "
56 "FROM \"%w\".%s "
dan65455fc2019-04-19 16:34:22 +000057 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000058 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000059 " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
dan9d324822018-08-30 20:03:44 +000060 zDb, MASTER_NAME,
61 zDb, bTemp
62 );
63
64 if( bTemp==0 ){
65 sqlite3NestedParse(pParse,
66 "SELECT 1 "
67 "FROM temp.%s "
dan65455fc2019-04-19 16:34:22 +000068 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000069 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000070 " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
dan9d324822018-08-30 20:03:44 +000071 MASTER_NAME, zDb
72 );
73 }
74}
75
danbe535002011-04-01 15:15:58 +000076/*
dan09236502018-09-01 16:05:50 +000077** Generate code to reload the schema for database iDb. And, if iDb!=1, for
78** the temp database as well.
79*/
drh16b870d2018-09-12 15:51:56 +000080static void renameReloadSchema(Parse *pParse, int iDb){
dan09236502018-09-01 16:05:50 +000081 Vdbe *v = pParse->pVdbe;
82 if( v ){
83 sqlite3ChangeCookie(pParse, iDb);
84 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
85 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
86 }
87}
88
89/*
drhd0e4a6c2005-02-15 20:47:57 +000090** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
91** command.
92*/
93void sqlite3AlterRenameTable(
94 Parse *pParse, /* Parser context. */
95 SrcList *pSrc, /* The table to rename. */
96 Token *pName /* The new table name. */
97){
98 int iDb; /* Database that contains the table */
99 char *zDb; /* Name of database iDb */
100 Table *pTab; /* Table being renamed */
101 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000102 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000103 int nTabName; /* Number of UTF-8 characters in zTabName */
104 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000105 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000106 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000107 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000108
drh8257aa82017-07-26 19:59:13 +0000109 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000110 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000111 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000112 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000113
dan41fb5cd2012-10-04 19:33:00 +0000114 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000115 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000116 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000117 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000118 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000119
120 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000121 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000122 if( !zName ) goto exit_rename_table;
123
124 /* Check that a table or index named 'zName' does not already exist
125 ** in database iDb. If so, this is an error.
126 */
127 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
128 sqlite3ErrorMsg(pParse,
129 "there is already another table or index with this name: %s", zName);
130 goto exit_rename_table;
131 }
132
133 /* Make sure it is not a system table being altered, or a reserved name
134 ** that the table is being renamed to.
135 */
dan397a78d2018-12-18 20:31:14 +0000136 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000137 goto exit_rename_table;
138 }
drhc5a93d42019-08-12 00:08:07 +0000139 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
140 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000141 }
142
danielk197761116ae2007-12-13 08:15:30 +0000143#ifndef SQLITE_OMIT_VIEW
144 if( pTab->pSelect ){
145 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
146 goto exit_rename_table;
147 }
148#endif
149
drhd0e4a6c2005-02-15 20:47:57 +0000150#ifndef SQLITE_OMIT_AUTHORIZATION
151 /* Invoke the authorization callback. */
152 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
153 goto exit_rename_table;
154 }
155#endif
156
danielk1977182c4ba2007-06-27 15:53:34 +0000157#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000158 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
159 goto exit_rename_table;
160 }
danielk1977595a5232009-07-24 17:58:53 +0000161 if( IsVirtual(pTab) ){
162 pVTab = sqlite3GetVTable(db, pTab);
163 if( pVTab->pVtab->pModule->xRename==0 ){
164 pVTab = 0;
165 }
danielk1977182c4ba2007-06-27 15:53:34 +0000166 }
167#endif
168
dan1f3b2842019-03-15 16:17:32 +0000169 /* Begin a transaction for database iDb. Then modify the schema cookie
170 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
171 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
172 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000173 v = sqlite3GetVdbe(pParse);
174 if( v==0 ){
175 goto exit_rename_table;
176 }
dan1f3b2842019-03-15 16:17:32 +0000177 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000178
drh4e5dd852007-05-15 03:56:49 +0000179 /* figure out how many UTF-8 characters are in zName */
180 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000181 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000182
danc9461ec2018-08-29 21:00:16 +0000183 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
184 ** the schema to use the new table name. */
185 sqlite3NestedParse(pParse,
186 "UPDATE \"%w\".%s SET "
dan65372fa2018-09-03 20:05:15 +0000187 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000188 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000189 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan0ccda962018-08-30 16:26:48 +0000190 , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000191 );
dan432cc5b2009-09-26 17:51:48 +0000192
danc9461ec2018-08-29 21:00:16 +0000193 /* Update the tbl_name and name columns of the sqlite_master table
194 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000195 sqlite3NestedParse(pParse,
196 "UPDATE %Q.%s SET "
drhd0e4a6c2005-02-15 20:47:57 +0000197 "tbl_name = %Q, "
198 "name = CASE "
199 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000200 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
201 " AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000202 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000203 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000204 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000205 "(type='table' OR type='index' OR type='trigger');",
danc9461ec2018-08-29 21:00:16 +0000206 zDb, MASTER_NAME,
207 zName, zName, zName,
208 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000209 );
210
211#ifndef SQLITE_OMIT_AUTOINCREMENT
212 /* If the sqlite_sequence table exists in this database, then update
213 ** it with the new table name.
214 */
215 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
216 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000217 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000218 zDb, zName, pTab->zName);
219 }
220#endif
221
danc9461ec2018-08-29 21:00:16 +0000222 /* If the table being renamed is not itself part of the temp database,
223 ** edit view and trigger definitions within the temp database
224 ** as required. */
225 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000226 sqlite3NestedParse(pParse,
227 "UPDATE sqlite_temp_master SET "
dan65372fa2018-09-03 20:05:15 +0000228 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000229 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000230 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
231 " sqlite_rename_test(%Q, sql, type, name, 1) "
232 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000233 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000234 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000235 }
drhd0e4a6c2005-02-15 20:47:57 +0000236
dan34566c42018-09-20 17:21:21 +0000237 /* If this is a virtual table, invoke the xRename() function if
238 ** one is defined. The xRename() callback will modify the names
239 ** of any resources used by the v-table implementation (including other
240 ** SQLite tables) that are identified by the name of the virtual table.
241 */
242#ifndef SQLITE_OMIT_VIRTUALTABLE
243 if( pVTab ){
244 int i = ++pParse->nMem;
245 sqlite3VdbeLoadString(v, i, zName);
246 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000247 }
248#endif
249
dan09236502018-09-01 16:05:50 +0000250 renameReloadSchema(pParse, iDb);
dan9d324822018-08-30 20:03:44 +0000251 renameTestSchema(pParse, zDb, iDb==1);
252
drhd0e4a6c2005-02-15 20:47:57 +0000253exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000254 sqlite3SrcListDelete(db, pSrc);
255 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000256 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000257}
danielk197719a8e7e2005-03-17 05:03:38 +0000258
drhd3001712009-05-12 17:46:53 +0000259/*
danielk197719a8e7e2005-03-17 05:03:38 +0000260** This function is called after an "ALTER TABLE ... ADD" statement
261** has been parsed. Argument pColDef contains the text of the new
262** column definition.
263**
264** The Table structure pParse->pNewTable was extended to include
265** the new column during parsing.
266*/
267void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
268 Table *pNew; /* Copy of pParse->pNewTable */
269 Table *pTab; /* Table being altered */
270 int iDb; /* Database number */
271 const char *zDb; /* Database name */
272 const char *zTab; /* Table name */
273 char *zCol; /* Null-terminated column definition */
274 Column *pCol; /* The new column */
275 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000276 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000277 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000278 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000279
danielk1977f150c9d2008-10-30 17:21:12 +0000280 db = pParse->db;
281 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000282 pNew = pParse->pNewTable;
283 assert( pNew );
284
drh1fee73e2007-08-29 04:00:57 +0000285 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000286 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000287 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000288 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000289 pCol = &pNew->aCol[pNew->nCol-1];
290 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000291 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000292 assert( pTab );
293
drh81f2ccd2006-01-31 14:28:44 +0000294#ifndef SQLITE_OMIT_AUTHORIZATION
295 /* Invoke the authorization callback. */
296 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
297 return;
298 }
299#endif
300
danielk197719a8e7e2005-03-17 05:03:38 +0000301
302 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
303 ** If there is a NOT NULL constraint, then the default value for the
304 ** column must not be NULL.
305 */
drha371ace2012-09-13 14:22:47 +0000306 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000307 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
308 return;
309 }
310 if( pNew->pIndex ){
311 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
312 return;
313 }
drhc27ea2a2019-10-16 20:05:56 +0000314 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
315 /* If the default value for the new column was specified with a
316 ** literal NULL, then set pDflt to 0. This simplifies checking
317 ** for an SQL NULL default below.
318 */
319 assert( pDflt==0 || pDflt->op==TK_SPAN );
320 if( pDflt && pDflt->pLeft->op==TK_NULL ){
321 pDflt = 0;
322 }
323 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
324 sqlite3ErrorMsg(pParse,
325 "Cannot add a REFERENCES column with non-NULL default value");
326 return;
327 }
328 if( pCol->notNull && !pDflt ){
329 sqlite3ErrorMsg(pParse,
330 "Cannot add a NOT NULL column with default value NULL");
331 return;
332 }
333
334 /* Ensure the default expression is something that sqlite3ValueFromExpr()
335 ** can handle (i.e. not CURRENT_TIME etc.)
336 */
337 if( pDflt ){
338 sqlite3_value *pVal = 0;
339 int rc;
340 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
341 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
342 if( rc!=SQLITE_OK ){
343 assert( db->mallocFailed == 1 );
344 return;
345 }
346 if( !pVal ){
347 sqlite3ErrorMsg(pParse,"Cannot add a column with non-constant default");
348 return;
349 }
350 sqlite3ValueFree(pVal);
351 }
drh035f6d92019-10-24 01:04:10 +0000352 }else if( pCol->colFlags & COLFLAG_STORED ){
353 sqlite3ErrorMsg(pParse, "cannot add a STORED column");
354 return;
danielk197719a8e7e2005-03-17 05:03:38 +0000355 }
356
danielk197719a8e7e2005-03-17 05:03:38 +0000357
358 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000359 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000360 if( zCol ){
361 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000362 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000363 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000364 *zEnd-- = '\0';
365 }
drh8257aa82017-07-26 19:59:13 +0000366 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000367 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000368 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000369 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000370 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000371 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000372 zTab
373 );
drh633e6d52008-07-28 19:34:53 +0000374 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000375 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000376 }
377
drh86396212016-07-14 19:13:11 +0000378 /* Make sure the schema version is at least 3. But do not upgrade
379 ** from less than 3 to 4, as that will corrupt any preexisting DESC
380 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000381 */
dan09236502018-09-01 16:05:50 +0000382 v = sqlite3GetVdbe(pParse);
383 if( v ){
384 r1 = sqlite3GetTempReg(pParse);
385 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
386 sqlite3VdbeUsesBtree(v, iDb);
387 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
388 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
389 VdbeCoverage(v);
390 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
391 sqlite3ReleaseTempReg(pParse, r1);
392 }
danielk197719a8e7e2005-03-17 05:03:38 +0000393
dan09236502018-09-01 16:05:50 +0000394 /* Reload the table definition */
395 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000396}
397
drhfdd6e852005-12-16 01:06:16 +0000398/*
danielk197719a8e7e2005-03-17 05:03:38 +0000399** This function is called by the parser after the table-name in
400** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
401** pSrc is the full-name of the table being altered.
402**
403** This routine makes a (partial) copy of the Table structure
404** for the table being altered and sets Parse.pNewTable to point
405** to it. Routines called by the parser as the column definition
406** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
407** the copy. The copy of the Table structure is deleted by tokenize.c
408** after parsing is finished.
409**
410** Routine sqlite3AlterFinishAddColumn() will be called to complete
411** coding the "ALTER TABLE ... ADD" statement.
412*/
413void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
414 Table *pNew;
415 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000416 int iDb;
417 int i;
418 int nAlloc;
drh17435752007-08-16 04:30:38 +0000419 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000420
421 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000422 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000423 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000424 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000425 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000426 if( !pTab ) goto exit_begin_add_column;
427
danielk19775ee9d692006-06-21 12:36:25 +0000428#ifndef SQLITE_OMIT_VIRTUALTABLE
429 if( IsVirtual(pTab) ){
430 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
431 goto exit_begin_add_column;
432 }
433#endif
434
danielk197719a8e7e2005-03-17 05:03:38 +0000435 /* Make sure this is not an attempt to ALTER a view. */
436 if( pTab->pSelect ){
437 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
438 goto exit_begin_add_column;
439 }
dan397a78d2018-12-18 20:31:14 +0000440 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000441 goto exit_begin_add_column;
442 }
danielk197719a8e7e2005-03-17 05:03:38 +0000443
dan03e025e2019-10-07 18:43:21 +0000444 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000445 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000446 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000447
448 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000449 ** sqlite3AddColumn() function and friends to modify. But modify
450 ** the name by adding an "sqlite_altertab_" prefix. By adding this
451 ** prefix, we insure that the name will not collide with an existing
452 ** table because user table are not allowed to have the "sqlite_"
453 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000454 */
drh17435752007-08-16 04:30:38 +0000455 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000456 if( !pNew ) goto exit_begin_add_column;
457 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000458 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000459 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000460 assert( pNew->nCol>0 );
461 nAlloc = (((pNew->nCol-1)/8)*8)+8;
462 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000463 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000464 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000465 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000466 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000467 goto exit_begin_add_column;
468 }
469 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
470 for(i=0; i<pNew->nCol; i++){
471 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000472 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000473 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000474 pCol->pDflt = 0;
475 }
drh17435752007-08-16 04:30:38 +0000476 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000477 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000478 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000479
danielk197719a8e7e2005-03-17 05:03:38 +0000480exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000481 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000482 return;
483}
dancf8f2892018-08-09 20:47:01 +0000484
drh4a2c7472018-08-13 15:09:48 +0000485/*
dan9d705572018-08-20 16:16:05 +0000486** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
487** command. This function checks if the table is a view or virtual
488** table (columns of views or virtual tables may not be renamed). If so,
489** it loads an error message into pParse and returns non-zero.
490**
491** Or, if pTab is not a view or virtual table, zero is returned.
492*/
493#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
494static int isRealTable(Parse *pParse, Table *pTab){
495 const char *zType = 0;
496#ifndef SQLITE_OMIT_VIEW
497 if( pTab->pSelect ){
498 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000499 }
dan9d705572018-08-20 16:16:05 +0000500#endif
501#ifndef SQLITE_OMIT_VIRTUALTABLE
502 if( IsVirtual(pTab) ){
503 zType = "virtual table";
504 }
505#endif
506 if( zType ){
507 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000508 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000509 );
510 return 1;
511 }
512 return 0;
513}
514#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
515# define isRealTable(x,y) (0)
516#endif
517
518/*
drh4a2c7472018-08-13 15:09:48 +0000519** Handles the following parser reduction:
520**
521** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
522*/
dancf8f2892018-08-09 20:47:01 +0000523void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000524 Parse *pParse, /* Parsing context */
525 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
526 Token *pOld, /* Name of column being changed */
527 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000528){
drh4a2c7472018-08-13 15:09:48 +0000529 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000530 Table *pTab; /* Table being updated */
531 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000532 char *zOld = 0; /* Old column name */
533 char *zNew = 0; /* New column name */
534 const char *zDb; /* Name of schema containing the table */
535 int iSchema; /* Index of the schema */
536 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000537
drh4a2c7472018-08-13 15:09:48 +0000538 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000539 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
540 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000541
542 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000543 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000544 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000545
546 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000547 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
548 assert( iSchema>=0 );
549 zDb = db->aDb[iSchema].zDbSName;
550
drh0d019b92018-08-25 16:14:46 +0000551#ifndef SQLITE_OMIT_AUTHORIZATION
552 /* Invoke the authorization callback. */
553 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
554 goto exit_rename_column;
555 }
556#endif
557
drh4a2c7472018-08-13 15:09:48 +0000558 /* Make sure the old name really is a column name in the table to be
559 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000560 zOld = sqlite3NameFromToken(db, pOld);
561 if( !zOld ) goto exit_rename_column;
562 for(iCol=0; iCol<pTab->nCol; iCol++){
563 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
564 }
565 if( iCol==pTab->nCol ){
566 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
567 goto exit_rename_column;
568 }
569
drh4a2c7472018-08-13 15:09:48 +0000570 /* Do the rename operation using a recursive UPDATE statement that
571 ** uses the sqlite_rename_column() SQL function to compute the new
572 ** CREATE statement text for the sqlite_master table.
573 */
dan1f3b2842019-03-15 16:17:32 +0000574 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000575 zNew = sqlite3NameFromToken(db, pNew);
576 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000577 assert( pNew->n>0 );
578 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000579 sqlite3NestedParse(pParse,
580 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000581 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000582 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
583 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000584 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000585 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000586 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000587 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000588 );
589
dan9d324822018-08-30 20:03:44 +0000590 sqlite3NestedParse(pParse,
591 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000592 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000593 "WHERE type IN ('trigger', 'view')",
594 MASTER_NAME,
595 zDb, pTab->zName, iCol, zNew, bQuote
596 );
597
dane325ffe2018-08-11 13:40:20 +0000598 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000599 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000600 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000601
dancf8f2892018-08-09 20:47:01 +0000602 exit_rename_column:
603 sqlite3SrcListDelete(db, pSrc);
604 sqlite3DbFree(db, zOld);
605 sqlite3DbFree(db, zNew);
606 return;
607}
608
drh4a2c7472018-08-13 15:09:48 +0000609/*
610** Each RenameToken object maps an element of the parse tree into
611** the token that generated that element. The parse tree element
612** might be one of:
613**
614** * A pointer to an Expr that represents an ID
615** * The name of a table column in Column.zName
616**
617** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000618** Each new object is created by sqlite3RenameTokenMap().
619** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000620** routine is used to keep the mapping current.
621**
622** After the parse finishes, renameTokenFind() routine can be used
623** to look up the actual token value that created some element in
624** the parse tree.
625*/
dancf8f2892018-08-09 20:47:01 +0000626struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000627 void *p; /* Parse tree element created by token t */
628 Token t; /* The token that created parse tree element p */
629 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000630};
631
drh4a2c7472018-08-13 15:09:48 +0000632/*
633** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
634** down into the Walker.
635*/
dan5496d6a2018-08-13 17:14:26 +0000636typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000637struct RenameCtx {
638 RenameToken *pList; /* List of tokens to overwrite */
639 int nList; /* Number of tokens in pList */
640 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000641 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000642 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000643};
644
dan8900a482018-09-05 14:36:05 +0000645#ifdef SQLITE_DEBUG
646/*
647** This function is only for debugging. It performs two tasks:
648**
649** 1. Checks that pointer pPtr does not already appear in the
650** rename-token list.
651**
652** 2. Dereferences each pointer in the rename-token list.
653**
654** The second is most effective when debugging under valgrind or
655** address-sanitizer or similar. If any of these pointers no longer
656** point to valid objects, an exception is raised by the memory-checking
657** tool.
658**
659** The point of this is to prevent comparisons of invalid pointer values.
660** Even though this always seems to work, it is undefined according to the
661** C standard. Example of undefined comparison:
662**
663** sqlite3_free(x);
664** if( x==y ) ...
665**
666** Technically, as x no longer points into a valid object or to the byte
667** following a valid object, it may not be used in comparison operations.
668*/
drh16b870d2018-09-12 15:51:56 +0000669static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000670 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
671 RenameToken *p;
672 u8 i = 0;
673 for(p=pParse->pRename; p; p=p->pNext){
674 if( p->p ){
675 assert( p->p!=pPtr );
676 i += *(u8*)(p->p);
677 }
danc9461ec2018-08-29 21:00:16 +0000678 }
679 }
680}
dan8900a482018-09-05 14:36:05 +0000681#else
682# define renameTokenCheckAll(x,y)
683#endif
danc9461ec2018-08-29 21:00:16 +0000684
drh4a2c7472018-08-13 15:09:48 +0000685/*
drh49b269e2018-11-26 15:00:25 +0000686** Remember that the parser tree element pPtr was created using
687** the token pToken.
dan07e95232018-08-21 16:32:53 +0000688**
drh49b269e2018-11-26 15:00:25 +0000689** In other words, construct a new RenameToken object and add it
690** to the list of RenameToken objects currently being built up
691** in pParse->pRename.
692**
693** The pPtr argument is returned so that this routine can be used
694** with tail recursion in tokenExpr() routine, for a small performance
695** improvement.
drh4a2c7472018-08-13 15:09:48 +0000696*/
dan07e95232018-08-21 16:32:53 +0000697void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000698 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000699 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000700 renameTokenCheckAll(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000701 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
702 if( pNew ){
703 pNew->p = pPtr;
704 pNew->t = *pToken;
705 pNew->pNext = pParse->pRename;
706 pParse->pRename = pNew;
707 }
danc9461ec2018-08-29 21:00:16 +0000708
dand145e5f2018-08-21 08:29:48 +0000709 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000710}
711
drh4a2c7472018-08-13 15:09:48 +0000712/*
dan07e95232018-08-21 16:32:53 +0000713** It is assumed that there is already a RenameToken object associated
714** with parse tree element pFrom. This function remaps the associated token
715** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000716*/
dan07e95232018-08-21 16:32:53 +0000717void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000718 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000719 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000720 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000721 if( p->p==pFrom ){
722 p->p = pTo;
723 break;
724 }
725 }
dancf8f2892018-08-09 20:47:01 +0000726}
727
drh4a2c7472018-08-13 15:09:48 +0000728/*
dan8900a482018-09-05 14:36:05 +0000729** Walker callback used by sqlite3RenameExprUnmap().
730*/
731static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
732 Parse *pParse = pWalker->pParse;
733 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
734 return WRC_Continue;
735}
736
737/*
dan0b277a92019-06-11 12:03:10 +0000738** Walker callback used by sqlite3RenameExprUnmap().
739*/
740static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000741 Parse *pParse = pWalker->pParse;
742 int i;
743 if( ALWAYS(p->pEList) ){
744 ExprList *pList = p->pEList;
745 for(i=0; i<pList->nExpr; i++){
746 if( pList->a[i].zName ){
747 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
748 }
749 }
750 }
drh2c3f4652019-06-11 16:43:58 +0000751 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000752 SrcList *pSrc = p->pSrc;
753 for(i=0; i<pSrc->nSrc; i++){
754 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan0b277a92019-06-11 12:03:10 +0000755 }
756 }
757 return WRC_Continue;
758}
759
760/*
dan8900a482018-09-05 14:36:05 +0000761** Remove all nodes that are part of expression pExpr from the rename list.
762*/
763void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
764 Walker sWalker;
765 memset(&sWalker, 0, sizeof(Walker));
766 sWalker.pParse = pParse;
767 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000768 sWalker.xSelectCallback = renameUnmapSelectCb;
dan8900a482018-09-05 14:36:05 +0000769 sqlite3WalkExpr(&sWalker, pExpr);
770}
771
772/*
dane8ab40d2018-09-12 08:51:48 +0000773** Remove all nodes that are part of expression-list pEList from the
774** rename list.
775*/
776void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
777 if( pEList ){
778 int i;
779 Walker sWalker;
780 memset(&sWalker, 0, sizeof(Walker));
781 sWalker.pParse = pParse;
782 sWalker.xExprCallback = renameUnmapExprCb;
783 sqlite3WalkExprList(&sWalker, pEList);
784 for(i=0; i<pEList->nExpr; i++){
785 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
786 }
787 }
788}
789
790/*
drh4a2c7472018-08-13 15:09:48 +0000791** Free the list of RenameToken objects given in the second argument
792*/
dancf8f2892018-08-09 20:47:01 +0000793static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
794 RenameToken *pNext;
795 RenameToken *p;
796 for(p=pToken; p; p=pNext){
797 pNext = p->pNext;
798 sqlite3DbFree(db, p);
799 }
800}
801
dan987db762018-08-14 20:18:50 +0000802/*
803** Search the Parse object passed as the first argument for a RenameToken
804** object associated with parse tree element pPtr. If found, remove it
805** from the Parse object and add it to the list maintained by the
806** RenameCtx object passed as the second argument.
807*/
808static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000809 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000810 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000811 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
812 if( (*pp)->p==pPtr ){
813 RenameToken *pToken = *pp;
814 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000815 pToken->pNext = pCtx->pList;
816 pCtx->pList = pToken;
817 pCtx->nList++;
818 break;
dancf8f2892018-08-09 20:47:01 +0000819 }
820 }
dancf8f2892018-08-09 20:47:01 +0000821}
822
dan24fedb92018-08-18 17:35:38 +0000823/*
danea412512018-12-05 13:49:04 +0000824** Iterate through the Select objects that are part of WITH clauses attached
825** to select statement pSelect.
826*/
827static void renameWalkWith(Walker *pWalker, Select *pSelect){
828 if( pSelect->pWith ){
829 int i;
830 for(i=0; i<pSelect->pWith->nCte; i++){
831 Select *p = pSelect->pWith->a[i].pSelect;
832 NameContext sNC;
833 memset(&sNC, 0, sizeof(sNC));
834 sNC.pParse = pWalker->pParse;
835 sqlite3SelectPrep(sNC.pParse, p, &sNC);
836 sqlite3WalkSelect(pWalker, p);
837 }
838 }
839}
840
841/*
dan24fedb92018-08-18 17:35:38 +0000842** This is a Walker select callback. It does nothing. It is only required
843** because without a dummy callback, sqlite3WalkExpr() and similar do not
844** descend into sub-select statements.
845*/
dan987db762018-08-14 20:18:50 +0000846static int renameColumnSelectCb(Walker *pWalker, Select *p){
danea412512018-12-05 13:49:04 +0000847 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000848 return WRC_Continue;
849}
850
dan987db762018-08-14 20:18:50 +0000851/*
852** This is a Walker expression callback.
853**
854** For every TK_COLUMN node in the expression tree, search to see
855** if the column being references is the column being renamed by an
856** ALTER TABLE statement. If it is, then attach its associated
857** RenameToken object to the list of RenameToken objects being
858** constructed in RenameCtx object at pWalker->u.pRename.
859*/
dancf8f2892018-08-09 20:47:01 +0000860static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000861 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000862 if( pExpr->op==TK_TRIGGER
863 && pExpr->iColumn==p->iCol
864 && pWalker->pParse->pTriggerTab==p->pTab
865 ){
dan5be60c52018-08-15 20:28:39 +0000866 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000867 }else if( pExpr->op==TK_COLUMN
868 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000869 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000870 ){
dan5496d6a2018-08-13 17:14:26 +0000871 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000872 }
873 return WRC_Continue;
874}
875
dan987db762018-08-14 20:18:50 +0000876/*
877** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000878** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000879** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000880** RenameContext. "Last" means the last RenameToken encountered when
881** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000882** return all column name tokens in the order that they are encountered
883** in the SQL statement.
884*/
dan5496d6a2018-08-13 17:14:26 +0000885static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000886 RenameToken *pBest = pCtx->pList;
887 RenameToken *pToken;
888 RenameToken **pp;
889
890 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
891 if( pToken->t.z>pBest->t.z ) pBest = pToken;
892 }
893 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
894 *pp = pBest->pNext;
895
896 return pBest;
897}
898
dan6fe7f232018-08-10 19:19:33 +0000899/*
dan24fedb92018-08-18 17:35:38 +0000900** An error occured while parsing or otherwise processing a database
901** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
902** ALTER TABLE RENAME COLUMN program. The error message emitted by the
903** sub-routine is currently stored in pParse->zErrMsg. This function
904** adds context to the error message and then stores it in pCtx.
905*/
danb0137382018-08-20 20:01:01 +0000906static void renameColumnParseError(
907 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000908 int bPost,
danb0137382018-08-20 20:01:01 +0000909 sqlite3_value *pType,
910 sqlite3_value *pObject,
911 Parse *pParse
912){
drh79a5ee92018-08-23 19:32:04 +0000913 const char *zT = (const char*)sqlite3_value_text(pType);
914 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000915 char *zErr;
danb0137382018-08-20 20:01:01 +0000916
dan0d5fa6b2018-08-24 17:55:49 +0000917 zErr = sqlite3_mprintf("error in %s %s%s: %s",
918 zT, zN, (bPost ? " after rename" : ""),
919 pParse->zErrMsg
920 );
dan24fedb92018-08-18 17:35:38 +0000921 sqlite3_result_error(pCtx, zErr, -1);
922 sqlite3_free(zErr);
923}
924
925/*
dan06249392018-08-21 15:06:59 +0000926** For each name in the the expression-list pEList (i.e. each
927** pEList->a[i].zName) that matches the string in zOld, extract the
928** corresponding rename-token from Parse object pParse and add it
929** to the RenameCtx pCtx.
930*/
931static void renameColumnElistNames(
932 Parse *pParse,
933 RenameCtx *pCtx,
934 ExprList *pEList,
935 const char *zOld
936){
937 if( pEList ){
938 int i;
939 for(i=0; i<pEList->nExpr; i++){
940 char *zName = pEList->a[i].zName;
941 if( 0==sqlite3_stricmp(zName, zOld) ){
942 renameTokenFind(pParse, pCtx, (void*)zName);
943 }
944 }
945 }
946}
947
948/*
949** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
950** that matches the string in zOld, extract the corresponding rename-token
951** from Parse object pParse and add it to the RenameCtx pCtx.
952*/
953static void renameColumnIdlistNames(
954 Parse *pParse,
955 RenameCtx *pCtx,
956 IdList *pIdList,
957 const char *zOld
958){
959 if( pIdList ){
960 int i;
961 for(i=0; i<pIdList->nId; i++){
962 char *zName = pIdList->a[i].zName;
963 if( 0==sqlite3_stricmp(zName, zOld) ){
964 renameTokenFind(pParse, pCtx, (void*)zName);
965 }
966 }
967 }
968}
969
dandd1a9c82018-09-05 08:28:30 +0000970/*
971** Parse the SQL statement zSql using Parse object (*p). The Parse object
972** is initialized by this function before it is used.
973*/
danc9461ec2018-08-29 21:00:16 +0000974static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000975 Parse *p, /* Memory to use for Parse object */
976 const char *zDb, /* Name of schema SQL belongs to */
977 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
978 sqlite3 *db, /* Database handle */
979 const char *zSql, /* SQL to parse */
980 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000981){
982 int rc;
983 char *zErr = 0;
984
985 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
986
987 /* Parse the SQL statement passed as the first argument. If no error
988 ** occurs and the parse does not result in a new table, index or
989 ** trigger object, the database must be corrupt. */
990 memset(p, 0, sizeof(Parse));
991 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
992 p->db = db;
993 p->nQueryLoop = 1;
994 rc = sqlite3RunParser(p, zSql, &zErr);
995 assert( p->zErrMsg==0 );
996 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +0000997 p->zErrMsg = zErr;
998 if( db->mallocFailed ) rc = SQLITE_NOMEM;
999 if( rc==SQLITE_OK
1000 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1001 ){
1002 rc = SQLITE_CORRUPT_BKPT;
1003 }
1004
1005#ifdef SQLITE_DEBUG
1006 /* Ensure that all mappings in the Parse.pRename list really do map to
1007 ** a part of the input string. */
1008 if( rc==SQLITE_OK ){
1009 int nSql = sqlite3Strlen30(zSql);
1010 RenameToken *pToken;
1011 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1012 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1013 }
1014 }
1015#endif
1016
1017 db->init.iDb = 0;
1018 return rc;
1019}
1020
dandd1a9c82018-09-05 08:28:30 +00001021/*
1022** This function edits SQL statement zSql, replacing each token identified
1023** by the linked list pRename with the text of zNew. If argument bQuote is
1024** true, then zNew is always quoted first. If no error occurs, the result
1025** is loaded into context object pCtx as the result.
1026**
1027** Or, if an error occurs (i.e. an OOM condition), an error is left in
1028** pCtx and an SQLite error code returned.
1029*/
danc9461ec2018-08-29 21:00:16 +00001030static int renameEditSql(
1031 sqlite3_context *pCtx, /* Return result here */
1032 RenameCtx *pRename, /* Rename context */
1033 const char *zSql, /* SQL statement to edit */
1034 const char *zNew, /* New token text */
1035 int bQuote /* True to always quote token */
1036){
1037 int nNew = sqlite3Strlen30(zNew);
1038 int nSql = sqlite3Strlen30(zSql);
1039 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1040 int rc = SQLITE_OK;
1041 char *zQuot;
1042 char *zOut;
1043 int nQuot;
1044
1045 /* Set zQuot to point to a buffer containing a quoted copy of the
1046 ** identifier zNew. If the corresponding identifier in the original
1047 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1048 ** point to zQuot so that all substitutions are made using the
1049 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001050 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001051 if( zQuot==0 ){
1052 return SQLITE_NOMEM;
1053 }else{
1054 nQuot = sqlite3Strlen30(zQuot);
1055 }
1056 if( bQuote ){
1057 zNew = zQuot;
1058 nNew = nQuot;
1059 }
1060
1061 /* At this point pRename->pList contains a list of RenameToken objects
1062 ** corresponding to all tokens in the input SQL that must be replaced
1063 ** with the new column name. All that remains is to construct and
1064 ** return the edited SQL string. */
1065 assert( nQuot>=nNew );
1066 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1067 if( zOut ){
1068 int nOut = nSql;
1069 memcpy(zOut, zSql, nSql);
1070 while( pRename->pList ){
1071 int iOff; /* Offset of token to replace in zOut */
1072 RenameToken *pBest = renameColumnTokenNext(pRename);
1073
1074 u32 nReplace;
1075 const char *zReplace;
1076 if( sqlite3IsIdChar(*pBest->t.z) ){
1077 nReplace = nNew;
1078 zReplace = zNew;
1079 }else{
1080 nReplace = nQuot;
1081 zReplace = zQuot;
1082 }
1083
1084 iOff = pBest->t.z - zSql;
1085 if( pBest->t.n!=nReplace ){
1086 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1087 nOut - (iOff + pBest->t.n)
1088 );
1089 nOut += nReplace - pBest->t.n;
1090 zOut[nOut] = '\0';
1091 }
1092 memcpy(&zOut[iOff], zReplace, nReplace);
1093 sqlite3DbFree(db, pBest);
1094 }
1095
1096 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1097 sqlite3DbFree(db, zOut);
1098 }else{
1099 rc = SQLITE_NOMEM;
1100 }
1101
1102 sqlite3_free(zQuot);
1103 return rc;
1104}
1105
dandd1a9c82018-09-05 08:28:30 +00001106/*
1107** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1108** it was read from the schema of database zDb. Return SQLITE_OK if
1109** successful. Otherwise, return an SQLite error code and leave an error
1110** message in the Parse object.
1111*/
1112static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001113 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001114 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001115 TriggerStep *pStep;
1116 NameContext sNC;
1117 int rc = SQLITE_OK;
1118
1119 memset(&sNC, 0, sizeof(sNC));
1120 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001121 assert( pNew->pTabSchema );
1122 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1123 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1124 );
1125 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001126 /* ALWAYS() because if the table of the trigger does not exist, the
1127 ** error would have been hit before this point */
1128 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001129 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1130 }
danc9461ec2018-08-29 21:00:16 +00001131
1132 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001133 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001134 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001135 }
1136
dand5e6fef2018-09-07 15:50:31 +00001137 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001138 if( pStep->pSelect ){
1139 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1140 if( pParse->nErr ) rc = pParse->rc;
1141 }
dand5e6fef2018-09-07 15:50:31 +00001142 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001143 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1144 if( pTarget==0 ){
1145 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001146 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
dan0e14e982019-01-18 16:06:18 +00001147 SrcList sSrc;
danc9461ec2018-08-29 21:00:16 +00001148 memset(&sSrc, 0, sizeof(sSrc));
1149 sSrc.nSrc = 1;
1150 sSrc.a[0].zName = pStep->zTarget;
1151 sSrc.a[0].pTab = pTarget;
1152 sNC.pSrcList = &sSrc;
1153 if( pStep->pWhere ){
1154 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1155 }
1156 if( rc==SQLITE_OK ){
1157 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1158 }
1159 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1160 if( pStep->pUpsert ){
1161 Upsert *pUpsert = pStep->pUpsert;
1162 assert( rc==SQLITE_OK );
1163 pUpsert->pUpsertSrc = &sSrc;
1164 sNC.uNC.pUpsert = pUpsert;
1165 sNC.ncFlags = NC_UUpsert;
1166 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1167 if( rc==SQLITE_OK ){
1168 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1169 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1170 }
1171 if( rc==SQLITE_OK ){
1172 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1173 }
1174 if( rc==SQLITE_OK ){
1175 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1176 }
1177 sNC.ncFlags = 0;
1178 }
dan0e14e982019-01-18 16:06:18 +00001179 sNC.pSrcList = 0;
danc9461ec2018-08-29 21:00:16 +00001180 }
1181 }
1182 }
1183 return rc;
1184}
1185
dandd1a9c82018-09-05 08:28:30 +00001186/*
1187** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1188** objects that are part of the trigger passed as the second argument.
1189*/
danc9461ec2018-08-29 21:00:16 +00001190static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1191 TriggerStep *pStep;
1192
1193 /* Find tokens to edit in WHEN clause */
1194 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1195
1196 /* Find tokens to edit in trigger steps */
1197 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1198 sqlite3WalkSelect(pWalker, pStep->pSelect);
1199 sqlite3WalkExpr(pWalker, pStep->pWhere);
1200 sqlite3WalkExprList(pWalker, pStep->pExprList);
1201 if( pStep->pUpsert ){
1202 Upsert *pUpsert = pStep->pUpsert;
1203 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1204 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1205 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1206 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1207 }
1208 }
1209}
1210
dandd1a9c82018-09-05 08:28:30 +00001211/*
1212** Free the contents of Parse object (*pParse). Do not free the memory
1213** occupied by the Parse object itself.
1214*/
dan141e1192018-08-31 18:23:53 +00001215static void renameParseCleanup(Parse *pParse){
1216 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001217 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001218 if( pParse->pVdbe ){
1219 sqlite3VdbeFinalize(pParse->pVdbe);
1220 }
1221 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001222 while( (pIdx = pParse->pNewIndex)!=0 ){
1223 pParse->pNewIndex = pIdx->pNext;
1224 sqlite3FreeIndex(db, pIdx);
1225 }
dan141e1192018-08-31 18:23:53 +00001226 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1227 sqlite3DbFree(db, pParse->zErrMsg);
1228 renameTokenFree(db, pParse->pRename);
1229 sqlite3ParserReset(pParse);
1230}
1231
dan06249392018-08-21 15:06:59 +00001232/*
dan987db762018-08-14 20:18:50 +00001233** SQL function:
1234**
1235** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1236**
1237** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001238** 1. type: Type of object ("table", "view" etc.)
1239** 2. object: Name of object
1240** 3. Database: Database name (e.g. "main")
1241** 4. Table: Table name
1242** 5. iCol: Index of column to rename
1243** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001244** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001245** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001246**
1247** Do a column rename operation on the CREATE statement given in zSql.
1248** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1249** into zNew. The name should be quoted if bQuote is true.
1250**
1251** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001252** It is only accessible to SQL created using sqlite3NestedParse(). It is
1253** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001254*/
dancf8f2892018-08-09 20:47:01 +00001255static void renameColumnFunc(
1256 sqlite3_context *context,
1257 int NotUsed,
1258 sqlite3_value **argv
1259){
1260 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001261 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001262 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001263 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1264 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1265 int iCol = sqlite3_value_int(argv[5]);
1266 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001267 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001268 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001269 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001270 int rc;
dancf8f2892018-08-09 20:47:01 +00001271 Parse sParse;
1272 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001273 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001274 int i;
dan987db762018-08-14 20:18:50 +00001275 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001276#ifndef SQLITE_OMIT_AUTHORIZATION
1277 sqlite3_xauth xAuth = db->xAuth;
1278#endif
dancf8f2892018-08-09 20:47:01 +00001279
drh38d99642018-08-18 18:27:18 +00001280 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001281 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001282 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001283 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001284 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001285 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001286 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001287 if( pTab==0 || iCol>=pTab->nCol ){
1288 sqlite3BtreeLeaveAll(db);
1289 return;
1290 }
dan987db762018-08-14 20:18:50 +00001291 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001292 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001293 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001294
dan141e1192018-08-31 18:23:53 +00001295#ifndef SQLITE_OMIT_AUTHORIZATION
1296 db->xAuth = 0;
1297#endif
danc9461ec2018-08-29 21:00:16 +00001298 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001299
dancf8f2892018-08-09 20:47:01 +00001300 /* Find tokens that need to be replaced. */
1301 memset(&sWalker, 0, sizeof(Walker));
1302 sWalker.pParse = &sParse;
1303 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001304 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001305 sWalker.u.pRename = &sCtx;
1306
dan0cbb0b12018-08-16 19:49:16 +00001307 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001308 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001309 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001310 Select *pSelect = sParse.pNewTable->pSelect;
1311 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001312 sParse.rc = SQLITE_OK;
1313 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1314 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1315 if( rc==SQLITE_OK ){
1316 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001317 }
dan987db762018-08-14 20:18:50 +00001318 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1319 }else{
1320 /* A regular table */
1321 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1322 FKey *pFKey;
1323 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001324 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001325 if( bFKOnly==0 ){
1326 renameTokenFind(
1327 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1328 );
1329 if( sCtx.iCol<0 ){
1330 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001331 }
dan987db762018-08-14 20:18:50 +00001332 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1333 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1334 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1335 }
drh885eeb62019-01-09 02:02:24 +00001336 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1337 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1338 }
dan987db762018-08-14 20:18:50 +00001339 }
drhb9bcf7c2019-10-19 13:29:10 +00001340#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1341 for(i=0; i<sParse.pNewTable->nCol; i++){
1342 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1343 }
1344#endif
dan987db762018-08-14 20:18:50 +00001345
1346 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1347 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001348 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001349 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1350 }
1351 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1352 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1353 ){
1354 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1355 }
dan6fe7f232018-08-10 19:19:33 +00001356 }
dancf8f2892018-08-09 20:47:01 +00001357 }
1358 }
dan5496d6a2018-08-13 17:14:26 +00001359 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001360 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1361 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001362 }else{
dan5be60c52018-08-15 20:28:39 +00001363 /* A trigger */
1364 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001365 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001366 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001367
danc9461ec2018-08-29 21:00:16 +00001368 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1369 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001370 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001371 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001372 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001373 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1374 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001375 }
danc9461ec2018-08-29 21:00:16 +00001376 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1377 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001378 }
1379 }
1380 }
1381
dan5be60c52018-08-15 20:28:39 +00001382
1383 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001384 if( sParse.pTriggerTab==pTab ){
1385 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001386 }
dan5be60c52018-08-15 20:28:39 +00001387
danc9461ec2018-08-29 21:00:16 +00001388 /* Find tokens to edit in various expressions and selects */
1389 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001390 }
1391
dan987db762018-08-14 20:18:50 +00001392 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001393 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001394
drh5fc22cd2018-08-13 13:43:11 +00001395renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001396 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001397 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001398 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001399 }else{
1400 sqlite3_result_error_code(context, rc);
1401 }
1402 }
1403
dan141e1192018-08-31 18:23:53 +00001404 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001405 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001406#ifndef SQLITE_OMIT_AUTHORIZATION
1407 db->xAuth = xAuth;
1408#endif
drhda76adc2018-08-25 02:04:05 +00001409 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001410}
1411
dandd1a9c82018-09-05 08:28:30 +00001412/*
1413** Walker expression callback used by "RENAME TABLE".
1414*/
danc9461ec2018-08-29 21:00:16 +00001415static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1416 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001417 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1418 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001419 }
1420 return WRC_Continue;
1421}
1422
1423/*
dandd1a9c82018-09-05 08:28:30 +00001424** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001425*/
1426static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1427 int i;
1428 RenameCtx *p = pWalker->u.pRename;
1429 SrcList *pSrc = pSelect->pSrc;
drh92a28242019-10-09 15:37:58 +00001430 if( pSrc==0 ){
1431 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001432 return WRC_Abort;
1433 }
danc9461ec2018-08-29 21:00:16 +00001434 for(i=0; i<pSrc->nSrc; i++){
1435 struct SrcList_item *pItem = &pSrc->a[i];
1436 if( pItem->pTab==p->pTab ){
1437 renameTokenFind(pWalker->pParse, p, pItem->zName);
1438 }
1439 }
danea412512018-12-05 13:49:04 +00001440 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001441
1442 return WRC_Continue;
1443}
1444
1445
1446/*
1447** This C function implements an SQL user function that is used by SQL code
1448** generated by the ALTER TABLE ... RENAME command to modify the definition
1449** of any foreign key constraints that use the table being renamed as the
1450** parent table. It is passed three arguments:
1451**
dan141e1192018-08-31 18:23:53 +00001452** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001453** 1. type: Type of object ("table", "view" etc.)
1454** 2. object: Name of object
1455** 3: The complete text of the schema statement being modified,
1456** 4: The old name of the table being renamed, and
1457** 5: The new name of the table being renamed.
1458** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001459**
dan141e1192018-08-31 18:23:53 +00001460** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001461**
dan141e1192018-08-31 18:23:53 +00001462** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001463** -> 'CREATE TABLE t1(a REFERENCES t3)'
1464*/
1465static void renameTableFunc(
1466 sqlite3_context *context,
1467 int NotUsed,
1468 sqlite3_value **argv
1469){
1470 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001471 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001472 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1473 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1474 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1475 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001476 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001477
dan141e1192018-08-31 18:23:53 +00001478 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001479 Parse sParse;
1480 int rc;
1481 int bQuote = 1;
1482 RenameCtx sCtx;
1483 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001484
dan141e1192018-08-31 18:23:53 +00001485#ifndef SQLITE_OMIT_AUTHORIZATION
1486 sqlite3_xauth xAuth = db->xAuth;
1487 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001488#endif
1489
dan141e1192018-08-31 18:23:53 +00001490 sqlite3BtreeEnterAll(db);
1491
1492 memset(&sCtx, 0, sizeof(RenameCtx));
1493 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1494 memset(&sWalker, 0, sizeof(Walker));
1495 sWalker.pParse = &sParse;
1496 sWalker.xExprCallback = renameTableExprCb;
1497 sWalker.xSelectCallback = renameTableSelectCb;
1498 sWalker.u.pRename = &sCtx;
1499
1500 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1501
1502 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001503 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001504 if( sParse.pNewTable ){
1505 Table *pTab = sParse.pNewTable;
1506
1507 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001508 if( isLegacy==0 ){
1509 NameContext sNC;
1510 memset(&sNC, 0, sizeof(sNC));
1511 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001512
dan674b8942018-09-20 08:28:01 +00001513 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1514 if( sParse.nErr ) rc = sParse.rc;
1515 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1516 }
dan141e1192018-08-31 18:23:53 +00001517 }else{
1518 /* Modify any FK definitions to point to the new table. */
1519#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001520 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001521 FKey *pFKey;
1522 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1523 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1524 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1525 }
dan141e1192018-08-31 18:23:53 +00001526 }
1527 }
1528#endif
1529
1530 /* If this is the table being altered, fix any table refs in CHECK
1531 ** expressions. Also update the name that appears right after the
1532 ** "CREATE [VIRTUAL] TABLE" bit. */
1533 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1534 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001535 if( isLegacy==0 ){
1536 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1537 }
dan141e1192018-08-31 18:23:53 +00001538 renameTokenFind(&sParse, &sCtx, pTab->zName);
1539 }
danc9461ec2018-08-29 21:00:16 +00001540 }
1541 }
danc9461ec2018-08-29 21:00:16 +00001542
dan141e1192018-08-31 18:23:53 +00001543 else if( sParse.pNewIndex ){
1544 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001545 if( isLegacy==0 ){
1546 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1547 }
dan141e1192018-08-31 18:23:53 +00001548 }
danc9461ec2018-08-29 21:00:16 +00001549
1550#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001551 else{
dan141e1192018-08-31 18:23:53 +00001552 Trigger *pTrigger = sParse.pNewTrigger;
1553 TriggerStep *pStep;
1554 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1555 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1556 ){
1557 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1558 }
danc9461ec2018-08-29 21:00:16 +00001559
dan674b8942018-09-20 08:28:01 +00001560 if( isLegacy==0 ){
1561 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1562 if( rc==SQLITE_OK ){
1563 renameWalkTrigger(&sWalker, pTrigger);
1564 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1565 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1566 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1567 }
dan141e1192018-08-31 18:23:53 +00001568 }
dan0ccda962018-08-30 16:26:48 +00001569 }
danc9461ec2018-08-29 21:00:16 +00001570 }
1571 }
dan141e1192018-08-31 18:23:53 +00001572#endif
danc9461ec2018-08-29 21:00:16 +00001573 }
dan141e1192018-08-31 18:23:53 +00001574
1575 if( rc==SQLITE_OK ){
1576 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1577 }
1578 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001579 if( sParse.zErrMsg ){
1580 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1581 }else{
1582 sqlite3_result_error_code(context, rc);
1583 }
dan141e1192018-08-31 18:23:53 +00001584 }
1585
1586 renameParseCleanup(&sParse);
1587 renameTokenFree(db, sCtx.pList);
1588 sqlite3BtreeLeaveAll(db);
1589#ifndef SQLITE_OMIT_AUTHORIZATION
1590 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001591#endif
1592 }
1593
danc9461ec2018-08-29 21:00:16 +00001594 return;
1595}
1596
dandd1a9c82018-09-05 08:28:30 +00001597/*
1598** An SQL user function that checks that there are no parse or symbol
1599** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1600** After an ALTER TABLE .. RENAME operation is performed and the schema
1601** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001602** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001603**
1604** 0: Database name ("main", "temp" etc.).
1605** 1: SQL statement.
1606** 2: Object type ("view", "table", "trigger" or "index").
1607** 3: Object name.
1608** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001609**
1610** Unless it finds an error, this function normally returns NULL. However, it
1611** returns integer value 1 if:
1612**
1613** * the SQL argument creates a trigger, and
1614** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001615*/
dan9d324822018-08-30 20:03:44 +00001616static void renameTableTest(
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 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1623 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001624 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001625 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001626
dan141e1192018-08-31 18:23:53 +00001627#ifndef SQLITE_OMIT_AUTHORIZATION
1628 sqlite3_xauth xAuth = db->xAuth;
1629 db->xAuth = 0;
1630#endif
1631
drh5b1da302018-09-01 20:02:07 +00001632 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001633 if( zDb && zInput ){
1634 int rc;
1635 Parse sParse;
1636 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1637 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001638 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001639 NameContext sNC;
1640 memset(&sNC, 0, sizeof(sNC));
1641 sNC.pParse = &sParse;
1642 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1643 if( sParse.nErr ) rc = sParse.rc;
1644 }
1645
1646 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001647 if( isLegacy==0 ){
1648 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1649 }
drh3b700452018-09-07 19:12:08 +00001650 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001651 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1652 int i2 = sqlite3FindDbName(db, zDb);
1653 if( i1==i2 ) sqlite3_result_int(context, 1);
1654 }
dan09236502018-09-01 16:05:50 +00001655 }
dan9d324822018-08-30 20:03:44 +00001656 }
1657
dan09236502018-09-01 16:05:50 +00001658 if( rc!=SQLITE_OK ){
1659 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001660 }
dan09236502018-09-01 16:05:50 +00001661 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001662 }
1663
dan141e1192018-08-31 18:23:53 +00001664#ifndef SQLITE_OMIT_AUTHORIZATION
1665 db->xAuth = xAuth;
1666#endif
dan9d324822018-08-30 20:03:44 +00001667}
1668
dancf8f2892018-08-09 20:47:01 +00001669/*
1670** Register built-in functions used to help implement ALTER TABLE
1671*/
1672void sqlite3AlterFunctions(void){
1673 static FuncDef aAlterTableFuncs[] = {
drheea8eb62018-11-26 18:09:15 +00001674 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1675 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1676 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001677 };
1678 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1679}
drhd0e4a6c2005-02-15 20:47:57 +00001680#endif /* SQLITE_ALTER_TABLE */