blob: b7389bf9cbfa8dedb624ad4557ea57186e6feda4 [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 }
danielk197719a8e7e2005-03-17 05:03:38 +0000352 }
353
danielk197719a8e7e2005-03-17 05:03:38 +0000354
355 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000356 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000357 if( zCol ){
358 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000359 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000360 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000361 *zEnd-- = '\0';
362 }
drh8257aa82017-07-26 19:59:13 +0000363 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000364 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000365 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000366 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000367 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000368 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000369 zTab
370 );
drh633e6d52008-07-28 19:34:53 +0000371 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000372 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000373 }
374
drh86396212016-07-14 19:13:11 +0000375 /* Make sure the schema version is at least 3. But do not upgrade
376 ** from less than 3 to 4, as that will corrupt any preexisting DESC
377 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000378 */
dan09236502018-09-01 16:05:50 +0000379 v = sqlite3GetVdbe(pParse);
380 if( v ){
381 r1 = sqlite3GetTempReg(pParse);
382 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
383 sqlite3VdbeUsesBtree(v, iDb);
384 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
385 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
386 VdbeCoverage(v);
387 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
388 sqlite3ReleaseTempReg(pParse, r1);
389 }
danielk197719a8e7e2005-03-17 05:03:38 +0000390
dan09236502018-09-01 16:05:50 +0000391 /* Reload the table definition */
392 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000393}
394
drhfdd6e852005-12-16 01:06:16 +0000395/*
danielk197719a8e7e2005-03-17 05:03:38 +0000396** This function is called by the parser after the table-name in
397** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
398** pSrc is the full-name of the table being altered.
399**
400** This routine makes a (partial) copy of the Table structure
401** for the table being altered and sets Parse.pNewTable to point
402** to it. Routines called by the parser as the column definition
403** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
404** the copy. The copy of the Table structure is deleted by tokenize.c
405** after parsing is finished.
406**
407** Routine sqlite3AlterFinishAddColumn() will be called to complete
408** coding the "ALTER TABLE ... ADD" statement.
409*/
410void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
411 Table *pNew;
412 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000413 int iDb;
414 int i;
415 int nAlloc;
drh17435752007-08-16 04:30:38 +0000416 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000417
418 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000419 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000420 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000421 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000422 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000423 if( !pTab ) goto exit_begin_add_column;
424
danielk19775ee9d692006-06-21 12:36:25 +0000425#ifndef SQLITE_OMIT_VIRTUALTABLE
426 if( IsVirtual(pTab) ){
427 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
428 goto exit_begin_add_column;
429 }
430#endif
431
danielk197719a8e7e2005-03-17 05:03:38 +0000432 /* Make sure this is not an attempt to ALTER a view. */
433 if( pTab->pSelect ){
434 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
435 goto exit_begin_add_column;
436 }
dan397a78d2018-12-18 20:31:14 +0000437 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000438 goto exit_begin_add_column;
439 }
danielk197719a8e7e2005-03-17 05:03:38 +0000440
dan03e025e2019-10-07 18:43:21 +0000441 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000442 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000443 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000444
445 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000446 ** sqlite3AddColumn() function and friends to modify. But modify
447 ** the name by adding an "sqlite_altertab_" prefix. By adding this
448 ** prefix, we insure that the name will not collide with an existing
449 ** table because user table are not allowed to have the "sqlite_"
450 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000451 */
drh17435752007-08-16 04:30:38 +0000452 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000453 if( !pNew ) goto exit_begin_add_column;
454 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000455 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000456 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000457 assert( pNew->nCol>0 );
458 nAlloc = (((pNew->nCol-1)/8)*8)+8;
459 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000460 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000461 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000462 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000463 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000464 goto exit_begin_add_column;
465 }
466 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
467 for(i=0; i<pNew->nCol; i++){
468 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000469 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000470 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000471 pCol->pDflt = 0;
472 }
drh17435752007-08-16 04:30:38 +0000473 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000474 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000475 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000476
danielk197719a8e7e2005-03-17 05:03:38 +0000477exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000478 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000479 return;
480}
dancf8f2892018-08-09 20:47:01 +0000481
drh4a2c7472018-08-13 15:09:48 +0000482/*
dan9d705572018-08-20 16:16:05 +0000483** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
484** command. This function checks if the table is a view or virtual
485** table (columns of views or virtual tables may not be renamed). If so,
486** it loads an error message into pParse and returns non-zero.
487**
488** Or, if pTab is not a view or virtual table, zero is returned.
489*/
490#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
491static int isRealTable(Parse *pParse, Table *pTab){
492 const char *zType = 0;
493#ifndef SQLITE_OMIT_VIEW
494 if( pTab->pSelect ){
495 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000496 }
dan9d705572018-08-20 16:16:05 +0000497#endif
498#ifndef SQLITE_OMIT_VIRTUALTABLE
499 if( IsVirtual(pTab) ){
500 zType = "virtual table";
501 }
502#endif
503 if( zType ){
504 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000505 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000506 );
507 return 1;
508 }
509 return 0;
510}
511#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
512# define isRealTable(x,y) (0)
513#endif
514
515/*
drh4a2c7472018-08-13 15:09:48 +0000516** Handles the following parser reduction:
517**
518** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
519*/
dancf8f2892018-08-09 20:47:01 +0000520void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000521 Parse *pParse, /* Parsing context */
522 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
523 Token *pOld, /* Name of column being changed */
524 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000525){
drh4a2c7472018-08-13 15:09:48 +0000526 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000527 Table *pTab; /* Table being updated */
528 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000529 char *zOld = 0; /* Old column name */
530 char *zNew = 0; /* New column name */
531 const char *zDb; /* Name of schema containing the table */
532 int iSchema; /* Index of the schema */
533 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000534
drh4a2c7472018-08-13 15:09:48 +0000535 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000536 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
537 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000538
539 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000540 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000541 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000542
543 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000544 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
545 assert( iSchema>=0 );
546 zDb = db->aDb[iSchema].zDbSName;
547
drh0d019b92018-08-25 16:14:46 +0000548#ifndef SQLITE_OMIT_AUTHORIZATION
549 /* Invoke the authorization callback. */
550 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
551 goto exit_rename_column;
552 }
553#endif
554
drh4a2c7472018-08-13 15:09:48 +0000555 /* Make sure the old name really is a column name in the table to be
556 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000557 zOld = sqlite3NameFromToken(db, pOld);
558 if( !zOld ) goto exit_rename_column;
559 for(iCol=0; iCol<pTab->nCol; iCol++){
560 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
561 }
562 if( iCol==pTab->nCol ){
563 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
564 goto exit_rename_column;
565 }
566
drh4a2c7472018-08-13 15:09:48 +0000567 /* Do the rename operation using a recursive UPDATE statement that
568 ** uses the sqlite_rename_column() SQL function to compute the new
569 ** CREATE statement text for the sqlite_master table.
570 */
dan1f3b2842019-03-15 16:17:32 +0000571 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000572 zNew = sqlite3NameFromToken(db, pNew);
573 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000574 assert( pNew->n>0 );
575 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000576 sqlite3NestedParse(pParse,
577 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000578 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000579 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
580 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000581 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000582 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000583 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000584 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000585 );
586
dan9d324822018-08-30 20:03:44 +0000587 sqlite3NestedParse(pParse,
588 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000589 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000590 "WHERE type IN ('trigger', 'view')",
591 MASTER_NAME,
592 zDb, pTab->zName, iCol, zNew, bQuote
593 );
594
dane325ffe2018-08-11 13:40:20 +0000595 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000596 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000597 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000598
dancf8f2892018-08-09 20:47:01 +0000599 exit_rename_column:
600 sqlite3SrcListDelete(db, pSrc);
601 sqlite3DbFree(db, zOld);
602 sqlite3DbFree(db, zNew);
603 return;
604}
605
drh4a2c7472018-08-13 15:09:48 +0000606/*
607** Each RenameToken object maps an element of the parse tree into
608** the token that generated that element. The parse tree element
609** might be one of:
610**
611** * A pointer to an Expr that represents an ID
612** * The name of a table column in Column.zName
613**
614** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000615** Each new object is created by sqlite3RenameTokenMap().
616** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000617** routine is used to keep the mapping current.
618**
619** After the parse finishes, renameTokenFind() routine can be used
620** to look up the actual token value that created some element in
621** the parse tree.
622*/
dancf8f2892018-08-09 20:47:01 +0000623struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000624 void *p; /* Parse tree element created by token t */
625 Token t; /* The token that created parse tree element p */
626 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000627};
628
drh4a2c7472018-08-13 15:09:48 +0000629/*
630** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
631** down into the Walker.
632*/
dan5496d6a2018-08-13 17:14:26 +0000633typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000634struct RenameCtx {
635 RenameToken *pList; /* List of tokens to overwrite */
636 int nList; /* Number of tokens in pList */
637 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000638 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000639 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000640};
641
dan8900a482018-09-05 14:36:05 +0000642#ifdef SQLITE_DEBUG
643/*
644** This function is only for debugging. It performs two tasks:
645**
646** 1. Checks that pointer pPtr does not already appear in the
647** rename-token list.
648**
649** 2. Dereferences each pointer in the rename-token list.
650**
651** The second is most effective when debugging under valgrind or
652** address-sanitizer or similar. If any of these pointers no longer
653** point to valid objects, an exception is raised by the memory-checking
654** tool.
655**
656** The point of this is to prevent comparisons of invalid pointer values.
657** Even though this always seems to work, it is undefined according to the
658** C standard. Example of undefined comparison:
659**
660** sqlite3_free(x);
661** if( x==y ) ...
662**
663** Technically, as x no longer points into a valid object or to the byte
664** following a valid object, it may not be used in comparison operations.
665*/
drh16b870d2018-09-12 15:51:56 +0000666static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000667 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
668 RenameToken *p;
669 u8 i = 0;
670 for(p=pParse->pRename; p; p=p->pNext){
671 if( p->p ){
672 assert( p->p!=pPtr );
673 i += *(u8*)(p->p);
674 }
danc9461ec2018-08-29 21:00:16 +0000675 }
676 }
677}
dan8900a482018-09-05 14:36:05 +0000678#else
679# define renameTokenCheckAll(x,y)
680#endif
danc9461ec2018-08-29 21:00:16 +0000681
drh4a2c7472018-08-13 15:09:48 +0000682/*
drh49b269e2018-11-26 15:00:25 +0000683** Remember that the parser tree element pPtr was created using
684** the token pToken.
dan07e95232018-08-21 16:32:53 +0000685**
drh49b269e2018-11-26 15:00:25 +0000686** In other words, construct a new RenameToken object and add it
687** to the list of RenameToken objects currently being built up
688** in pParse->pRename.
689**
690** The pPtr argument is returned so that this routine can be used
691** with tail recursion in tokenExpr() routine, for a small performance
692** improvement.
drh4a2c7472018-08-13 15:09:48 +0000693*/
dan07e95232018-08-21 16:32:53 +0000694void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000695 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000696 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000697 renameTokenCheckAll(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000698 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
699 if( pNew ){
700 pNew->p = pPtr;
701 pNew->t = *pToken;
702 pNew->pNext = pParse->pRename;
703 pParse->pRename = pNew;
704 }
danc9461ec2018-08-29 21:00:16 +0000705
dand145e5f2018-08-21 08:29:48 +0000706 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000707}
708
drh4a2c7472018-08-13 15:09:48 +0000709/*
dan07e95232018-08-21 16:32:53 +0000710** It is assumed that there is already a RenameToken object associated
711** with parse tree element pFrom. This function remaps the associated token
712** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000713*/
dan07e95232018-08-21 16:32:53 +0000714void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000715 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000716 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000717 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000718 if( p->p==pFrom ){
719 p->p = pTo;
720 break;
721 }
722 }
dancf8f2892018-08-09 20:47:01 +0000723}
724
drh4a2c7472018-08-13 15:09:48 +0000725/*
dan8900a482018-09-05 14:36:05 +0000726** Walker callback used by sqlite3RenameExprUnmap().
727*/
728static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
729 Parse *pParse = pWalker->pParse;
730 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
731 return WRC_Continue;
732}
733
734/*
dan0b277a92019-06-11 12:03:10 +0000735** Walker callback used by sqlite3RenameExprUnmap().
736*/
737static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000738 Parse *pParse = pWalker->pParse;
739 int i;
740 if( ALWAYS(p->pEList) ){
741 ExprList *pList = p->pEList;
742 for(i=0; i<pList->nExpr; i++){
743 if( pList->a[i].zName ){
744 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
745 }
746 }
747 }
drh2c3f4652019-06-11 16:43:58 +0000748 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000749 SrcList *pSrc = p->pSrc;
750 for(i=0; i<pSrc->nSrc; i++){
751 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan0b277a92019-06-11 12:03:10 +0000752 }
753 }
754 return WRC_Continue;
755}
756
757/*
dan8900a482018-09-05 14:36:05 +0000758** Remove all nodes that are part of expression pExpr from the rename list.
759*/
760void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
761 Walker sWalker;
762 memset(&sWalker, 0, sizeof(Walker));
763 sWalker.pParse = pParse;
764 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000765 sWalker.xSelectCallback = renameUnmapSelectCb;
dan8900a482018-09-05 14:36:05 +0000766 sqlite3WalkExpr(&sWalker, pExpr);
767}
768
769/*
dane8ab40d2018-09-12 08:51:48 +0000770** Remove all nodes that are part of expression-list pEList from the
771** rename list.
772*/
773void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
774 if( pEList ){
775 int i;
776 Walker sWalker;
777 memset(&sWalker, 0, sizeof(Walker));
778 sWalker.pParse = pParse;
779 sWalker.xExprCallback = renameUnmapExprCb;
780 sqlite3WalkExprList(&sWalker, pEList);
781 for(i=0; i<pEList->nExpr; i++){
782 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
783 }
784 }
785}
786
787/*
drh4a2c7472018-08-13 15:09:48 +0000788** Free the list of RenameToken objects given in the second argument
789*/
dancf8f2892018-08-09 20:47:01 +0000790static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
791 RenameToken *pNext;
792 RenameToken *p;
793 for(p=pToken; p; p=pNext){
794 pNext = p->pNext;
795 sqlite3DbFree(db, p);
796 }
797}
798
dan987db762018-08-14 20:18:50 +0000799/*
800** Search the Parse object passed as the first argument for a RenameToken
801** object associated with parse tree element pPtr. If found, remove it
802** from the Parse object and add it to the list maintained by the
803** RenameCtx object passed as the second argument.
804*/
805static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000806 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000807 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000808 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
809 if( (*pp)->p==pPtr ){
810 RenameToken *pToken = *pp;
811 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000812 pToken->pNext = pCtx->pList;
813 pCtx->pList = pToken;
814 pCtx->nList++;
815 break;
dancf8f2892018-08-09 20:47:01 +0000816 }
817 }
dancf8f2892018-08-09 20:47:01 +0000818}
819
dan24fedb92018-08-18 17:35:38 +0000820/*
danea412512018-12-05 13:49:04 +0000821** Iterate through the Select objects that are part of WITH clauses attached
822** to select statement pSelect.
823*/
824static void renameWalkWith(Walker *pWalker, Select *pSelect){
825 if( pSelect->pWith ){
826 int i;
827 for(i=0; i<pSelect->pWith->nCte; i++){
828 Select *p = pSelect->pWith->a[i].pSelect;
829 NameContext sNC;
830 memset(&sNC, 0, sizeof(sNC));
831 sNC.pParse = pWalker->pParse;
832 sqlite3SelectPrep(sNC.pParse, p, &sNC);
833 sqlite3WalkSelect(pWalker, p);
834 }
835 }
836}
837
838/*
dan24fedb92018-08-18 17:35:38 +0000839** This is a Walker select callback. It does nothing. It is only required
840** because without a dummy callback, sqlite3WalkExpr() and similar do not
841** descend into sub-select statements.
842*/
dan987db762018-08-14 20:18:50 +0000843static int renameColumnSelectCb(Walker *pWalker, Select *p){
danea412512018-12-05 13:49:04 +0000844 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000845 return WRC_Continue;
846}
847
dan987db762018-08-14 20:18:50 +0000848/*
849** This is a Walker expression callback.
850**
851** For every TK_COLUMN node in the expression tree, search to see
852** if the column being references is the column being renamed by an
853** ALTER TABLE statement. If it is, then attach its associated
854** RenameToken object to the list of RenameToken objects being
855** constructed in RenameCtx object at pWalker->u.pRename.
856*/
dancf8f2892018-08-09 20:47:01 +0000857static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000858 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000859 if( pExpr->op==TK_TRIGGER
860 && pExpr->iColumn==p->iCol
861 && pWalker->pParse->pTriggerTab==p->pTab
862 ){
dan5be60c52018-08-15 20:28:39 +0000863 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000864 }else if( pExpr->op==TK_COLUMN
865 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000866 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000867 ){
dan5496d6a2018-08-13 17:14:26 +0000868 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000869 }
870 return WRC_Continue;
871}
872
dan987db762018-08-14 20:18:50 +0000873/*
874** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000875** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000876** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000877** RenameContext. "Last" means the last RenameToken encountered when
878** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000879** return all column name tokens in the order that they are encountered
880** in the SQL statement.
881*/
dan5496d6a2018-08-13 17:14:26 +0000882static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000883 RenameToken *pBest = pCtx->pList;
884 RenameToken *pToken;
885 RenameToken **pp;
886
887 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
888 if( pToken->t.z>pBest->t.z ) pBest = pToken;
889 }
890 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
891 *pp = pBest->pNext;
892
893 return pBest;
894}
895
dan6fe7f232018-08-10 19:19:33 +0000896/*
dan24fedb92018-08-18 17:35:38 +0000897** An error occured while parsing or otherwise processing a database
898** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
899** ALTER TABLE RENAME COLUMN program. The error message emitted by the
900** sub-routine is currently stored in pParse->zErrMsg. This function
901** adds context to the error message and then stores it in pCtx.
902*/
danb0137382018-08-20 20:01:01 +0000903static void renameColumnParseError(
904 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000905 int bPost,
danb0137382018-08-20 20:01:01 +0000906 sqlite3_value *pType,
907 sqlite3_value *pObject,
908 Parse *pParse
909){
drh79a5ee92018-08-23 19:32:04 +0000910 const char *zT = (const char*)sqlite3_value_text(pType);
911 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000912 char *zErr;
danb0137382018-08-20 20:01:01 +0000913
dan0d5fa6b2018-08-24 17:55:49 +0000914 zErr = sqlite3_mprintf("error in %s %s%s: %s",
915 zT, zN, (bPost ? " after rename" : ""),
916 pParse->zErrMsg
917 );
dan24fedb92018-08-18 17:35:38 +0000918 sqlite3_result_error(pCtx, zErr, -1);
919 sqlite3_free(zErr);
920}
921
922/*
dan06249392018-08-21 15:06:59 +0000923** For each name in the the expression-list pEList (i.e. each
924** pEList->a[i].zName) that matches the string in zOld, extract the
925** corresponding rename-token from Parse object pParse and add it
926** to the RenameCtx pCtx.
927*/
928static void renameColumnElistNames(
929 Parse *pParse,
930 RenameCtx *pCtx,
931 ExprList *pEList,
932 const char *zOld
933){
934 if( pEList ){
935 int i;
936 for(i=0; i<pEList->nExpr; i++){
937 char *zName = pEList->a[i].zName;
938 if( 0==sqlite3_stricmp(zName, zOld) ){
939 renameTokenFind(pParse, pCtx, (void*)zName);
940 }
941 }
942 }
943}
944
945/*
946** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
947** that matches the string in zOld, extract the corresponding rename-token
948** from Parse object pParse and add it to the RenameCtx pCtx.
949*/
950static void renameColumnIdlistNames(
951 Parse *pParse,
952 RenameCtx *pCtx,
953 IdList *pIdList,
954 const char *zOld
955){
956 if( pIdList ){
957 int i;
958 for(i=0; i<pIdList->nId; i++){
959 char *zName = pIdList->a[i].zName;
960 if( 0==sqlite3_stricmp(zName, zOld) ){
961 renameTokenFind(pParse, pCtx, (void*)zName);
962 }
963 }
964 }
965}
966
dandd1a9c82018-09-05 08:28:30 +0000967/*
968** Parse the SQL statement zSql using Parse object (*p). The Parse object
969** is initialized by this function before it is used.
970*/
danc9461ec2018-08-29 21:00:16 +0000971static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000972 Parse *p, /* Memory to use for Parse object */
973 const char *zDb, /* Name of schema SQL belongs to */
974 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
975 sqlite3 *db, /* Database handle */
976 const char *zSql, /* SQL to parse */
977 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000978){
979 int rc;
980 char *zErr = 0;
981
982 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
983
984 /* Parse the SQL statement passed as the first argument. If no error
985 ** occurs and the parse does not result in a new table, index or
986 ** trigger object, the database must be corrupt. */
987 memset(p, 0, sizeof(Parse));
988 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
989 p->db = db;
990 p->nQueryLoop = 1;
991 rc = sqlite3RunParser(p, zSql, &zErr);
992 assert( p->zErrMsg==0 );
993 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +0000994 p->zErrMsg = zErr;
995 if( db->mallocFailed ) rc = SQLITE_NOMEM;
996 if( rc==SQLITE_OK
997 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
998 ){
999 rc = SQLITE_CORRUPT_BKPT;
1000 }
1001
1002#ifdef SQLITE_DEBUG
1003 /* Ensure that all mappings in the Parse.pRename list really do map to
1004 ** a part of the input string. */
1005 if( rc==SQLITE_OK ){
1006 int nSql = sqlite3Strlen30(zSql);
1007 RenameToken *pToken;
1008 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1009 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1010 }
1011 }
1012#endif
1013
1014 db->init.iDb = 0;
1015 return rc;
1016}
1017
dandd1a9c82018-09-05 08:28:30 +00001018/*
1019** This function edits SQL statement zSql, replacing each token identified
1020** by the linked list pRename with the text of zNew. If argument bQuote is
1021** true, then zNew is always quoted first. If no error occurs, the result
1022** is loaded into context object pCtx as the result.
1023**
1024** Or, if an error occurs (i.e. an OOM condition), an error is left in
1025** pCtx and an SQLite error code returned.
1026*/
danc9461ec2018-08-29 21:00:16 +00001027static int renameEditSql(
1028 sqlite3_context *pCtx, /* Return result here */
1029 RenameCtx *pRename, /* Rename context */
1030 const char *zSql, /* SQL statement to edit */
1031 const char *zNew, /* New token text */
1032 int bQuote /* True to always quote token */
1033){
1034 int nNew = sqlite3Strlen30(zNew);
1035 int nSql = sqlite3Strlen30(zSql);
1036 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1037 int rc = SQLITE_OK;
1038 char *zQuot;
1039 char *zOut;
1040 int nQuot;
1041
1042 /* Set zQuot to point to a buffer containing a quoted copy of the
1043 ** identifier zNew. If the corresponding identifier in the original
1044 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1045 ** point to zQuot so that all substitutions are made using the
1046 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001047 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001048 if( zQuot==0 ){
1049 return SQLITE_NOMEM;
1050 }else{
1051 nQuot = sqlite3Strlen30(zQuot);
1052 }
1053 if( bQuote ){
1054 zNew = zQuot;
1055 nNew = nQuot;
1056 }
1057
1058 /* At this point pRename->pList contains a list of RenameToken objects
1059 ** corresponding to all tokens in the input SQL that must be replaced
1060 ** with the new column name. All that remains is to construct and
1061 ** return the edited SQL string. */
1062 assert( nQuot>=nNew );
1063 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1064 if( zOut ){
1065 int nOut = nSql;
1066 memcpy(zOut, zSql, nSql);
1067 while( pRename->pList ){
1068 int iOff; /* Offset of token to replace in zOut */
1069 RenameToken *pBest = renameColumnTokenNext(pRename);
1070
1071 u32 nReplace;
1072 const char *zReplace;
1073 if( sqlite3IsIdChar(*pBest->t.z) ){
1074 nReplace = nNew;
1075 zReplace = zNew;
1076 }else{
1077 nReplace = nQuot;
1078 zReplace = zQuot;
1079 }
1080
1081 iOff = pBest->t.z - zSql;
1082 if( pBest->t.n!=nReplace ){
1083 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1084 nOut - (iOff + pBest->t.n)
1085 );
1086 nOut += nReplace - pBest->t.n;
1087 zOut[nOut] = '\0';
1088 }
1089 memcpy(&zOut[iOff], zReplace, nReplace);
1090 sqlite3DbFree(db, pBest);
1091 }
1092
1093 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1094 sqlite3DbFree(db, zOut);
1095 }else{
1096 rc = SQLITE_NOMEM;
1097 }
1098
1099 sqlite3_free(zQuot);
1100 return rc;
1101}
1102
dandd1a9c82018-09-05 08:28:30 +00001103/*
1104** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1105** it was read from the schema of database zDb. Return SQLITE_OK if
1106** successful. Otherwise, return an SQLite error code and leave an error
1107** message in the Parse object.
1108*/
1109static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001110 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001111 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001112 TriggerStep *pStep;
1113 NameContext sNC;
1114 int rc = SQLITE_OK;
1115
1116 memset(&sNC, 0, sizeof(sNC));
1117 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001118 assert( pNew->pTabSchema );
1119 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1120 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1121 );
1122 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001123 /* ALWAYS() because if the table of the trigger does not exist, the
1124 ** error would have been hit before this point */
1125 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001126 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1127 }
danc9461ec2018-08-29 21:00:16 +00001128
1129 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001130 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001131 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001132 }
1133
dand5e6fef2018-09-07 15:50:31 +00001134 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001135 if( pStep->pSelect ){
1136 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1137 if( pParse->nErr ) rc = pParse->rc;
1138 }
dand5e6fef2018-09-07 15:50:31 +00001139 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001140 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1141 if( pTarget==0 ){
1142 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001143 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
dan0e14e982019-01-18 16:06:18 +00001144 SrcList sSrc;
danc9461ec2018-08-29 21:00:16 +00001145 memset(&sSrc, 0, sizeof(sSrc));
1146 sSrc.nSrc = 1;
1147 sSrc.a[0].zName = pStep->zTarget;
1148 sSrc.a[0].pTab = pTarget;
1149 sNC.pSrcList = &sSrc;
1150 if( pStep->pWhere ){
1151 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1152 }
1153 if( rc==SQLITE_OK ){
1154 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1155 }
1156 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1157 if( pStep->pUpsert ){
1158 Upsert *pUpsert = pStep->pUpsert;
1159 assert( rc==SQLITE_OK );
1160 pUpsert->pUpsertSrc = &sSrc;
1161 sNC.uNC.pUpsert = pUpsert;
1162 sNC.ncFlags = NC_UUpsert;
1163 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1164 if( rc==SQLITE_OK ){
1165 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1166 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1167 }
1168 if( rc==SQLITE_OK ){
1169 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1170 }
1171 if( rc==SQLITE_OK ){
1172 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1173 }
1174 sNC.ncFlags = 0;
1175 }
dan0e14e982019-01-18 16:06:18 +00001176 sNC.pSrcList = 0;
danc9461ec2018-08-29 21:00:16 +00001177 }
1178 }
1179 }
1180 return rc;
1181}
1182
dandd1a9c82018-09-05 08:28:30 +00001183/*
1184** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1185** objects that are part of the trigger passed as the second argument.
1186*/
danc9461ec2018-08-29 21:00:16 +00001187static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1188 TriggerStep *pStep;
1189
1190 /* Find tokens to edit in WHEN clause */
1191 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1192
1193 /* Find tokens to edit in trigger steps */
1194 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1195 sqlite3WalkSelect(pWalker, pStep->pSelect);
1196 sqlite3WalkExpr(pWalker, pStep->pWhere);
1197 sqlite3WalkExprList(pWalker, pStep->pExprList);
1198 if( pStep->pUpsert ){
1199 Upsert *pUpsert = pStep->pUpsert;
1200 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1201 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1202 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1203 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1204 }
1205 }
1206}
1207
dandd1a9c82018-09-05 08:28:30 +00001208/*
1209** Free the contents of Parse object (*pParse). Do not free the memory
1210** occupied by the Parse object itself.
1211*/
dan141e1192018-08-31 18:23:53 +00001212static void renameParseCleanup(Parse *pParse){
1213 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001214 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001215 if( pParse->pVdbe ){
1216 sqlite3VdbeFinalize(pParse->pVdbe);
1217 }
1218 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001219 while( (pIdx = pParse->pNewIndex)!=0 ){
1220 pParse->pNewIndex = pIdx->pNext;
1221 sqlite3FreeIndex(db, pIdx);
1222 }
dan141e1192018-08-31 18:23:53 +00001223 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1224 sqlite3DbFree(db, pParse->zErrMsg);
1225 renameTokenFree(db, pParse->pRename);
1226 sqlite3ParserReset(pParse);
1227}
1228
dan06249392018-08-21 15:06:59 +00001229/*
dan987db762018-08-14 20:18:50 +00001230** SQL function:
1231**
1232** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1233**
1234** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001235** 1. type: Type of object ("table", "view" etc.)
1236** 2. object: Name of object
1237** 3. Database: Database name (e.g. "main")
1238** 4. Table: Table name
1239** 5. iCol: Index of column to rename
1240** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001241** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001242** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001243**
1244** Do a column rename operation on the CREATE statement given in zSql.
1245** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1246** into zNew. The name should be quoted if bQuote is true.
1247**
1248** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001249** It is only accessible to SQL created using sqlite3NestedParse(). It is
1250** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001251*/
dancf8f2892018-08-09 20:47:01 +00001252static void renameColumnFunc(
1253 sqlite3_context *context,
1254 int NotUsed,
1255 sqlite3_value **argv
1256){
1257 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001258 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001259 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001260 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1261 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1262 int iCol = sqlite3_value_int(argv[5]);
1263 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001264 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001265 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001266 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001267 int rc;
dancf8f2892018-08-09 20:47:01 +00001268 Parse sParse;
1269 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001270 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001271 int i;
dan987db762018-08-14 20:18:50 +00001272 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001273#ifndef SQLITE_OMIT_AUTHORIZATION
1274 sqlite3_xauth xAuth = db->xAuth;
1275#endif
dancf8f2892018-08-09 20:47:01 +00001276
drh38d99642018-08-18 18:27:18 +00001277 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001278 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001279 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001280 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001281 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001282 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001283 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001284 if( pTab==0 || iCol>=pTab->nCol ){
1285 sqlite3BtreeLeaveAll(db);
1286 return;
1287 }
dan987db762018-08-14 20:18:50 +00001288 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001289 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001290 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001291
dan141e1192018-08-31 18:23:53 +00001292#ifndef SQLITE_OMIT_AUTHORIZATION
1293 db->xAuth = 0;
1294#endif
danc9461ec2018-08-29 21:00:16 +00001295 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001296
dancf8f2892018-08-09 20:47:01 +00001297 /* Find tokens that need to be replaced. */
1298 memset(&sWalker, 0, sizeof(Walker));
1299 sWalker.pParse = &sParse;
1300 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001301 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001302 sWalker.u.pRename = &sCtx;
1303
dan0cbb0b12018-08-16 19:49:16 +00001304 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001305 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001306 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001307 Select *pSelect = sParse.pNewTable->pSelect;
1308 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001309 sParse.rc = SQLITE_OK;
1310 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1311 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1312 if( rc==SQLITE_OK ){
1313 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001314 }
dan987db762018-08-14 20:18:50 +00001315 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1316 }else{
1317 /* A regular table */
1318 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1319 FKey *pFKey;
1320 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001321 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001322 if( bFKOnly==0 ){
1323 renameTokenFind(
1324 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1325 );
1326 if( sCtx.iCol<0 ){
1327 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001328 }
dan987db762018-08-14 20:18:50 +00001329 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1330 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1331 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1332 }
drh885eeb62019-01-09 02:02:24 +00001333 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1334 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1335 }
dan987db762018-08-14 20:18:50 +00001336 }
drhb9bcf7c2019-10-19 13:29:10 +00001337#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1338 for(i=0; i<sParse.pNewTable->nCol; i++){
1339 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1340 }
1341#endif
dan987db762018-08-14 20:18:50 +00001342
1343 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1344 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001345 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001346 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1347 }
1348 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1349 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1350 ){
1351 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1352 }
dan6fe7f232018-08-10 19:19:33 +00001353 }
dancf8f2892018-08-09 20:47:01 +00001354 }
1355 }
dan5496d6a2018-08-13 17:14:26 +00001356 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001357 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1358 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001359 }else{
dan5be60c52018-08-15 20:28:39 +00001360 /* A trigger */
1361 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001362 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001363 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001364
danc9461ec2018-08-29 21:00:16 +00001365 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1366 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001367 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001368 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001369 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001370 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1371 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001372 }
danc9461ec2018-08-29 21:00:16 +00001373 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1374 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001375 }
1376 }
1377 }
1378
dan5be60c52018-08-15 20:28:39 +00001379
1380 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001381 if( sParse.pTriggerTab==pTab ){
1382 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001383 }
dan5be60c52018-08-15 20:28:39 +00001384
danc9461ec2018-08-29 21:00:16 +00001385 /* Find tokens to edit in various expressions and selects */
1386 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001387 }
1388
dan987db762018-08-14 20:18:50 +00001389 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001390 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001391
drh5fc22cd2018-08-13 13:43:11 +00001392renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001393 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001394 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001395 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001396 }else{
1397 sqlite3_result_error_code(context, rc);
1398 }
1399 }
1400
dan141e1192018-08-31 18:23:53 +00001401 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001402 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001403#ifndef SQLITE_OMIT_AUTHORIZATION
1404 db->xAuth = xAuth;
1405#endif
drhda76adc2018-08-25 02:04:05 +00001406 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001407}
1408
dandd1a9c82018-09-05 08:28:30 +00001409/*
1410** Walker expression callback used by "RENAME TABLE".
1411*/
danc9461ec2018-08-29 21:00:16 +00001412static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1413 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001414 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1415 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001416 }
1417 return WRC_Continue;
1418}
1419
1420/*
dandd1a9c82018-09-05 08:28:30 +00001421** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001422*/
1423static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1424 int i;
1425 RenameCtx *p = pWalker->u.pRename;
1426 SrcList *pSrc = pSelect->pSrc;
drh92a28242019-10-09 15:37:58 +00001427 if( pSrc==0 ){
1428 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001429 return WRC_Abort;
1430 }
danc9461ec2018-08-29 21:00:16 +00001431 for(i=0; i<pSrc->nSrc; i++){
1432 struct SrcList_item *pItem = &pSrc->a[i];
1433 if( pItem->pTab==p->pTab ){
1434 renameTokenFind(pWalker->pParse, p, pItem->zName);
1435 }
1436 }
danea412512018-12-05 13:49:04 +00001437 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001438
1439 return WRC_Continue;
1440}
1441
1442
1443/*
1444** This C function implements an SQL user function that is used by SQL code
1445** generated by the ALTER TABLE ... RENAME command to modify the definition
1446** of any foreign key constraints that use the table being renamed as the
1447** parent table. It is passed three arguments:
1448**
dan141e1192018-08-31 18:23:53 +00001449** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001450** 1. type: Type of object ("table", "view" etc.)
1451** 2. object: Name of object
1452** 3: The complete text of the schema statement being modified,
1453** 4: The old name of the table being renamed, and
1454** 5: The new name of the table being renamed.
1455** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001456**
dan141e1192018-08-31 18:23:53 +00001457** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001458**
dan141e1192018-08-31 18:23:53 +00001459** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001460** -> 'CREATE TABLE t1(a REFERENCES t3)'
1461*/
1462static void renameTableFunc(
1463 sqlite3_context *context,
1464 int NotUsed,
1465 sqlite3_value **argv
1466){
1467 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001468 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001469 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1470 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1471 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1472 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001473 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001474
dan141e1192018-08-31 18:23:53 +00001475 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001476 Parse sParse;
1477 int rc;
1478 int bQuote = 1;
1479 RenameCtx sCtx;
1480 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001481
dan141e1192018-08-31 18:23:53 +00001482#ifndef SQLITE_OMIT_AUTHORIZATION
1483 sqlite3_xauth xAuth = db->xAuth;
1484 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001485#endif
1486
dan141e1192018-08-31 18:23:53 +00001487 sqlite3BtreeEnterAll(db);
1488
1489 memset(&sCtx, 0, sizeof(RenameCtx));
1490 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1491 memset(&sWalker, 0, sizeof(Walker));
1492 sWalker.pParse = &sParse;
1493 sWalker.xExprCallback = renameTableExprCb;
1494 sWalker.xSelectCallback = renameTableSelectCb;
1495 sWalker.u.pRename = &sCtx;
1496
1497 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1498
1499 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001500 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001501 if( sParse.pNewTable ){
1502 Table *pTab = sParse.pNewTable;
1503
1504 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001505 if( isLegacy==0 ){
1506 NameContext sNC;
1507 memset(&sNC, 0, sizeof(sNC));
1508 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001509
dan674b8942018-09-20 08:28:01 +00001510 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1511 if( sParse.nErr ) rc = sParse.rc;
1512 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1513 }
dan141e1192018-08-31 18:23:53 +00001514 }else{
1515 /* Modify any FK definitions to point to the new table. */
1516#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001517 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001518 FKey *pFKey;
1519 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1520 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1521 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1522 }
dan141e1192018-08-31 18:23:53 +00001523 }
1524 }
1525#endif
1526
1527 /* If this is the table being altered, fix any table refs in CHECK
1528 ** expressions. Also update the name that appears right after the
1529 ** "CREATE [VIRTUAL] TABLE" bit. */
1530 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1531 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001532 if( isLegacy==0 ){
1533 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1534 }
dan141e1192018-08-31 18:23:53 +00001535 renameTokenFind(&sParse, &sCtx, pTab->zName);
1536 }
danc9461ec2018-08-29 21:00:16 +00001537 }
1538 }
danc9461ec2018-08-29 21:00:16 +00001539
dan141e1192018-08-31 18:23:53 +00001540 else if( sParse.pNewIndex ){
1541 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001542 if( isLegacy==0 ){
1543 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1544 }
dan141e1192018-08-31 18:23:53 +00001545 }
danc9461ec2018-08-29 21:00:16 +00001546
1547#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001548 else{
dan141e1192018-08-31 18:23:53 +00001549 Trigger *pTrigger = sParse.pNewTrigger;
1550 TriggerStep *pStep;
1551 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1552 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1553 ){
1554 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1555 }
danc9461ec2018-08-29 21:00:16 +00001556
dan674b8942018-09-20 08:28:01 +00001557 if( isLegacy==0 ){
1558 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1559 if( rc==SQLITE_OK ){
1560 renameWalkTrigger(&sWalker, pTrigger);
1561 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1562 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1563 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1564 }
dan141e1192018-08-31 18:23:53 +00001565 }
dan0ccda962018-08-30 16:26:48 +00001566 }
danc9461ec2018-08-29 21:00:16 +00001567 }
1568 }
dan141e1192018-08-31 18:23:53 +00001569#endif
danc9461ec2018-08-29 21:00:16 +00001570 }
dan141e1192018-08-31 18:23:53 +00001571
1572 if( rc==SQLITE_OK ){
1573 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1574 }
1575 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001576 if( sParse.zErrMsg ){
1577 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1578 }else{
1579 sqlite3_result_error_code(context, rc);
1580 }
dan141e1192018-08-31 18:23:53 +00001581 }
1582
1583 renameParseCleanup(&sParse);
1584 renameTokenFree(db, sCtx.pList);
1585 sqlite3BtreeLeaveAll(db);
1586#ifndef SQLITE_OMIT_AUTHORIZATION
1587 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001588#endif
1589 }
1590
danc9461ec2018-08-29 21:00:16 +00001591 return;
1592}
1593
dandd1a9c82018-09-05 08:28:30 +00001594/*
1595** An SQL user function that checks that there are no parse or symbol
1596** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1597** After an ALTER TABLE .. RENAME operation is performed and the schema
1598** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001599** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001600**
1601** 0: Database name ("main", "temp" etc.).
1602** 1: SQL statement.
1603** 2: Object type ("view", "table", "trigger" or "index").
1604** 3: Object name.
1605** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001606**
1607** Unless it finds an error, this function normally returns NULL. However, it
1608** returns integer value 1 if:
1609**
1610** * the SQL argument creates a trigger, and
1611** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001612*/
dan9d324822018-08-30 20:03:44 +00001613static void renameTableTest(
1614 sqlite3_context *context,
1615 int NotUsed,
1616 sqlite3_value **argv
1617){
1618 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001619 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1620 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001621 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001622 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001623
dan141e1192018-08-31 18:23:53 +00001624#ifndef SQLITE_OMIT_AUTHORIZATION
1625 sqlite3_xauth xAuth = db->xAuth;
1626 db->xAuth = 0;
1627#endif
1628
drh5b1da302018-09-01 20:02:07 +00001629 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001630 if( zDb && zInput ){
1631 int rc;
1632 Parse sParse;
1633 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1634 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001635 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001636 NameContext sNC;
1637 memset(&sNC, 0, sizeof(sNC));
1638 sNC.pParse = &sParse;
1639 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1640 if( sParse.nErr ) rc = sParse.rc;
1641 }
1642
1643 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001644 if( isLegacy==0 ){
1645 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1646 }
drh3b700452018-09-07 19:12:08 +00001647 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001648 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1649 int i2 = sqlite3FindDbName(db, zDb);
1650 if( i1==i2 ) sqlite3_result_int(context, 1);
1651 }
dan09236502018-09-01 16:05:50 +00001652 }
dan9d324822018-08-30 20:03:44 +00001653 }
1654
dan09236502018-09-01 16:05:50 +00001655 if( rc!=SQLITE_OK ){
1656 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001657 }
dan09236502018-09-01 16:05:50 +00001658 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001659 }
1660
dan141e1192018-08-31 18:23:53 +00001661#ifndef SQLITE_OMIT_AUTHORIZATION
1662 db->xAuth = xAuth;
1663#endif
dan9d324822018-08-30 20:03:44 +00001664}
1665
dancf8f2892018-08-09 20:47:01 +00001666/*
1667** Register built-in functions used to help implement ALTER TABLE
1668*/
1669void sqlite3AlterFunctions(void){
1670 static FuncDef aAlterTableFuncs[] = {
drheea8eb62018-11-26 18:09:15 +00001671 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1672 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1673 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001674 };
1675 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1676}
drhd0e4a6c2005-02-15 20:47:57 +00001677#endif /* SQLITE_ALTER_TABLE */