blob: d71074795b707576f63de5d3c45f00d1d0c677f7 [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 "
57 "WHERE name NOT LIKE 'sqlite_%%'"
58 " 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 "
68 "WHERE name NOT LIKE 'sqlite_%%'"
69 " 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 }
danbe535002011-04-01 15:15:58 +0000139 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
140 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)"
189 "AND name NOT LIKE 'sqlite_%%'"
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 "
200 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000201 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000202 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000203 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000204 "(type='table' OR type='index' OR type='trigger');",
danc9461ec2018-08-29 21:00:16 +0000205 zDb, MASTER_NAME,
206 zName, zName, zName,
207 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000208 );
209
210#ifndef SQLITE_OMIT_AUTOINCREMENT
211 /* If the sqlite_sequence table exists in this database, then update
212 ** it with the new table name.
213 */
214 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
215 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000216 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000217 zDb, zName, pTab->zName);
218 }
219#endif
220
danc9461ec2018-08-29 21:00:16 +0000221 /* If the table being renamed is not itself part of the temp database,
222 ** edit view and trigger definitions within the temp database
223 ** as required. */
224 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000225 sqlite3NestedParse(pParse,
226 "UPDATE sqlite_temp_master SET "
dan65372fa2018-09-03 20:05:15 +0000227 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000228 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000229 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
230 " sqlite_rename_test(%Q, sql, type, name, 1) "
231 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000232 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000233 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000234 }
drhd0e4a6c2005-02-15 20:47:57 +0000235
dan34566c42018-09-20 17:21:21 +0000236 /* If this is a virtual table, invoke the xRename() function if
237 ** one is defined. The xRename() callback will modify the names
238 ** of any resources used by the v-table implementation (including other
239 ** SQLite tables) that are identified by the name of the virtual table.
240 */
241#ifndef SQLITE_OMIT_VIRTUALTABLE
242 if( pVTab ){
243 int i = ++pParse->nMem;
244 sqlite3VdbeLoadString(v, i, zName);
245 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dan34566c42018-09-20 17:21:21 +0000246 }
247#endif
248
dan09236502018-09-01 16:05:50 +0000249 renameReloadSchema(pParse, iDb);
dan9d324822018-08-30 20:03:44 +0000250 renameTestSchema(pParse, zDb, iDb==1);
251
drhd0e4a6c2005-02-15 20:47:57 +0000252exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000253 sqlite3SrcListDelete(db, pSrc);
254 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000255 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000256}
danielk197719a8e7e2005-03-17 05:03:38 +0000257
drhd3001712009-05-12 17:46:53 +0000258/*
danielk197719a8e7e2005-03-17 05:03:38 +0000259** This function is called after an "ALTER TABLE ... ADD" statement
260** has been parsed. Argument pColDef contains the text of the new
261** column definition.
262**
263** The Table structure pParse->pNewTable was extended to include
264** the new column during parsing.
265*/
266void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
267 Table *pNew; /* Copy of pParse->pNewTable */
268 Table *pTab; /* Table being altered */
269 int iDb; /* Database number */
270 const char *zDb; /* Database name */
271 const char *zTab; /* Table name */
272 char *zCol; /* Null-terminated column definition */
273 Column *pCol; /* The new column */
274 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000275 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000276 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000277 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000278
danielk1977f150c9d2008-10-30 17:21:12 +0000279 db = pParse->db;
280 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000281 pNew = pParse->pNewTable;
282 assert( pNew );
283
drh1fee73e2007-08-29 04:00:57 +0000284 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000285 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000286 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000287 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000288 pCol = &pNew->aCol[pNew->nCol-1];
289 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000290 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000291 assert( pTab );
292
drh81f2ccd2006-01-31 14:28:44 +0000293#ifndef SQLITE_OMIT_AUTHORIZATION
294 /* Invoke the authorization callback. */
295 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
296 return;
297 }
298#endif
299
danielk197719a8e7e2005-03-17 05:03:38 +0000300 /* If the default value for the new column was specified with a
301 ** literal NULL, then set pDflt to 0. This simplifies checking
302 ** for an SQL NULL default below.
303 */
drh94fa9c42016-02-27 21:16:04 +0000304 assert( pDflt==0 || pDflt->op==TK_SPAN );
305 if( pDflt && pDflt->pLeft->op==TK_NULL ){
danielk197719a8e7e2005-03-17 05:03:38 +0000306 pDflt = 0;
307 }
308
309 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
310 ** If there is a NOT NULL constraint, then the default value for the
311 ** column must not be NULL.
312 */
drha371ace2012-09-13 14:22:47 +0000313 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000314 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
315 return;
316 }
317 if( pNew->pIndex ){
318 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
319 return;
320 }
dan53c3fa82009-09-25 11:26:54 +0000321 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
322 sqlite3ErrorMsg(pParse,
323 "Cannot add a REFERENCES column with non-NULL default value");
324 return;
325 }
danielk197719a8e7e2005-03-17 05:03:38 +0000326 if( pCol->notNull && !pDflt ){
327 sqlite3ErrorMsg(pParse,
328 "Cannot add a NOT NULL column with default value NULL");
329 return;
330 }
331
332 /* Ensure the default expression is something that sqlite3ValueFromExpr()
333 ** can handle (i.e. not CURRENT_TIME etc.)
334 */
335 if( pDflt ){
dan7a419232013-08-06 20:01:43 +0000336 sqlite3_value *pVal = 0;
drh96f4ad22015-03-12 21:02:36 +0000337 int rc;
drh05883a32015-06-02 15:32:08 +0000338 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
drh96f4ad22015-03-12 21:02:36 +0000339 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
340 if( rc!=SQLITE_OK ){
pdrbb3da062016-02-06 14:14:43 +0000341 assert( db->mallocFailed == 1 );
danielk197719a8e7e2005-03-17 05:03:38 +0000342 return;
343 }
344 if( !pVal ){
345 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
346 return;
347 }
348 sqlite3ValueFree(pVal);
349 }
350
351 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000352 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000353 if( zCol ){
354 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000355 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000356 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000357 *zEnd-- = '\0';
358 }
drh8257aa82017-07-26 19:59:13 +0000359 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000360 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000361 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000362 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000363 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000364 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000365 zTab
366 );
drh633e6d52008-07-28 19:34:53 +0000367 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000368 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000369 }
370
drh86396212016-07-14 19:13:11 +0000371 /* Make sure the schema version is at least 3. But do not upgrade
372 ** from less than 3 to 4, as that will corrupt any preexisting DESC
373 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000374 */
dan09236502018-09-01 16:05:50 +0000375 v = sqlite3GetVdbe(pParse);
376 if( v ){
377 r1 = sqlite3GetTempReg(pParse);
378 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
379 sqlite3VdbeUsesBtree(v, iDb);
380 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
381 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
382 VdbeCoverage(v);
383 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
384 sqlite3ReleaseTempReg(pParse, r1);
385 }
danielk197719a8e7e2005-03-17 05:03:38 +0000386
dan09236502018-09-01 16:05:50 +0000387 /* Reload the table definition */
388 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000389}
390
drhfdd6e852005-12-16 01:06:16 +0000391/*
danielk197719a8e7e2005-03-17 05:03:38 +0000392** This function is called by the parser after the table-name in
393** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
394** pSrc is the full-name of the table being altered.
395**
396** This routine makes a (partial) copy of the Table structure
397** for the table being altered and sets Parse.pNewTable to point
398** to it. Routines called by the parser as the column definition
399** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
400** the copy. The copy of the Table structure is deleted by tokenize.c
401** after parsing is finished.
402**
403** Routine sqlite3AlterFinishAddColumn() will be called to complete
404** coding the "ALTER TABLE ... ADD" statement.
405*/
406void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
407 Table *pNew;
408 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000409 int iDb;
410 int i;
411 int nAlloc;
drh17435752007-08-16 04:30:38 +0000412 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000413
414 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000415 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000416 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000417 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000418 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000419 if( !pTab ) goto exit_begin_add_column;
420
danielk19775ee9d692006-06-21 12:36:25 +0000421#ifndef SQLITE_OMIT_VIRTUALTABLE
422 if( IsVirtual(pTab) ){
423 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
424 goto exit_begin_add_column;
425 }
426#endif
427
danielk197719a8e7e2005-03-17 05:03:38 +0000428 /* Make sure this is not an attempt to ALTER a view. */
429 if( pTab->pSelect ){
430 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
431 goto exit_begin_add_column;
432 }
dan397a78d2018-12-18 20:31:14 +0000433 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000434 goto exit_begin_add_column;
435 }
danielk197719a8e7e2005-03-17 05:03:38 +0000436
437 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000438 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000439
440 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000441 ** sqlite3AddColumn() function and friends to modify. But modify
442 ** the name by adding an "sqlite_altertab_" prefix. By adding this
443 ** prefix, we insure that the name will not collide with an existing
444 ** table because user table are not allowed to have the "sqlite_"
445 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000446 */
drh17435752007-08-16 04:30:38 +0000447 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000448 if( !pNew ) goto exit_begin_add_column;
449 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000450 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000451 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000452 assert( pNew->nCol>0 );
453 nAlloc = (((pNew->nCol-1)/8)*8)+8;
454 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000455 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000456 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000457 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000458 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000459 goto exit_begin_add_column;
460 }
461 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
462 for(i=0; i<pNew->nCol; i++){
463 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000464 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000465 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000466 pCol->pDflt = 0;
467 }
drh17435752007-08-16 04:30:38 +0000468 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000469 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000470 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000471
danielk197719a8e7e2005-03-17 05:03:38 +0000472exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000473 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000474 return;
475}
dancf8f2892018-08-09 20:47:01 +0000476
drh4a2c7472018-08-13 15:09:48 +0000477/*
dan9d705572018-08-20 16:16:05 +0000478** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
479** command. This function checks if the table is a view or virtual
480** table (columns of views or virtual tables may not be renamed). If so,
481** it loads an error message into pParse and returns non-zero.
482**
483** Or, if pTab is not a view or virtual table, zero is returned.
484*/
485#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
486static int isRealTable(Parse *pParse, Table *pTab){
487 const char *zType = 0;
488#ifndef SQLITE_OMIT_VIEW
489 if( pTab->pSelect ){
490 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000491 }
dan9d705572018-08-20 16:16:05 +0000492#endif
493#ifndef SQLITE_OMIT_VIRTUALTABLE
494 if( IsVirtual(pTab) ){
495 zType = "virtual table";
496 }
497#endif
498 if( zType ){
499 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000500 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000501 );
502 return 1;
503 }
504 return 0;
505}
506#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
507# define isRealTable(x,y) (0)
508#endif
509
510/*
drh4a2c7472018-08-13 15:09:48 +0000511** Handles the following parser reduction:
512**
513** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
514*/
dancf8f2892018-08-09 20:47:01 +0000515void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000516 Parse *pParse, /* Parsing context */
517 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
518 Token *pOld, /* Name of column being changed */
519 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000520){
drh4a2c7472018-08-13 15:09:48 +0000521 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000522 Table *pTab; /* Table being updated */
523 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000524 char *zOld = 0; /* Old column name */
525 char *zNew = 0; /* New column name */
526 const char *zDb; /* Name of schema containing the table */
527 int iSchema; /* Index of the schema */
528 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000529
drh4a2c7472018-08-13 15:09:48 +0000530 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000531 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
532 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000533
534 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000535 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000536 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000537
538 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000539 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
540 assert( iSchema>=0 );
541 zDb = db->aDb[iSchema].zDbSName;
542
drh0d019b92018-08-25 16:14:46 +0000543#ifndef SQLITE_OMIT_AUTHORIZATION
544 /* Invoke the authorization callback. */
545 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
546 goto exit_rename_column;
547 }
548#endif
549
drh4a2c7472018-08-13 15:09:48 +0000550 /* Make sure the old name really is a column name in the table to be
551 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000552 zOld = sqlite3NameFromToken(db, pOld);
553 if( !zOld ) goto exit_rename_column;
554 for(iCol=0; iCol<pTab->nCol; iCol++){
555 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
556 }
557 if( iCol==pTab->nCol ){
558 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
559 goto exit_rename_column;
560 }
561
drh4a2c7472018-08-13 15:09:48 +0000562 /* Do the rename operation using a recursive UPDATE statement that
563 ** uses the sqlite_rename_column() SQL function to compute the new
564 ** CREATE statement text for the sqlite_master table.
565 */
dan1f3b2842019-03-15 16:17:32 +0000566 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000567 zNew = sqlite3NameFromToken(db, pNew);
568 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000569 assert( pNew->n>0 );
570 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000571 sqlite3NestedParse(pParse,
572 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000573 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan499b8252018-08-17 18:08:28 +0000574 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
575 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000576 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000577 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000578 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000579 );
580
dan9d324822018-08-30 20:03:44 +0000581 sqlite3NestedParse(pParse,
582 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000583 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000584 "WHERE type IN ('trigger', 'view')",
585 MASTER_NAME,
586 zDb, pTab->zName, iCol, zNew, bQuote
587 );
588
dane325ffe2018-08-11 13:40:20 +0000589 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000590 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000591 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000592
dancf8f2892018-08-09 20:47:01 +0000593 exit_rename_column:
594 sqlite3SrcListDelete(db, pSrc);
595 sqlite3DbFree(db, zOld);
596 sqlite3DbFree(db, zNew);
597 return;
598}
599
drh4a2c7472018-08-13 15:09:48 +0000600/*
601** Each RenameToken object maps an element of the parse tree into
602** the token that generated that element. The parse tree element
603** might be one of:
604**
605** * A pointer to an Expr that represents an ID
606** * The name of a table column in Column.zName
607**
608** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000609** Each new object is created by sqlite3RenameTokenMap().
610** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000611** routine is used to keep the mapping current.
612**
613** After the parse finishes, renameTokenFind() routine can be used
614** to look up the actual token value that created some element in
615** the parse tree.
616*/
dancf8f2892018-08-09 20:47:01 +0000617struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000618 void *p; /* Parse tree element created by token t */
619 Token t; /* The token that created parse tree element p */
620 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000621};
622
drh4a2c7472018-08-13 15:09:48 +0000623/*
624** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
625** down into the Walker.
626*/
dan5496d6a2018-08-13 17:14:26 +0000627typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000628struct RenameCtx {
629 RenameToken *pList; /* List of tokens to overwrite */
630 int nList; /* Number of tokens in pList */
631 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000632 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000633 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000634};
635
dan8900a482018-09-05 14:36:05 +0000636#ifdef SQLITE_DEBUG
637/*
638** This function is only for debugging. It performs two tasks:
639**
640** 1. Checks that pointer pPtr does not already appear in the
641** rename-token list.
642**
643** 2. Dereferences each pointer in the rename-token list.
644**
645** The second is most effective when debugging under valgrind or
646** address-sanitizer or similar. If any of these pointers no longer
647** point to valid objects, an exception is raised by the memory-checking
648** tool.
649**
650** The point of this is to prevent comparisons of invalid pointer values.
651** Even though this always seems to work, it is undefined according to the
652** C standard. Example of undefined comparison:
653**
654** sqlite3_free(x);
655** if( x==y ) ...
656**
657** Technically, as x no longer points into a valid object or to the byte
658** following a valid object, it may not be used in comparison operations.
659*/
drh16b870d2018-09-12 15:51:56 +0000660static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000661 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
662 RenameToken *p;
663 u8 i = 0;
664 for(p=pParse->pRename; p; p=p->pNext){
665 if( p->p ){
666 assert( p->p!=pPtr );
667 i += *(u8*)(p->p);
668 }
danc9461ec2018-08-29 21:00:16 +0000669 }
670 }
671}
dan8900a482018-09-05 14:36:05 +0000672#else
673# define renameTokenCheckAll(x,y)
674#endif
danc9461ec2018-08-29 21:00:16 +0000675
drh4a2c7472018-08-13 15:09:48 +0000676/*
drh49b269e2018-11-26 15:00:25 +0000677** Remember that the parser tree element pPtr was created using
678** the token pToken.
dan07e95232018-08-21 16:32:53 +0000679**
drh49b269e2018-11-26 15:00:25 +0000680** In other words, construct a new RenameToken object and add it
681** to the list of RenameToken objects currently being built up
682** in pParse->pRename.
683**
684** The pPtr argument is returned so that this routine can be used
685** with tail recursion in tokenExpr() routine, for a small performance
686** improvement.
drh4a2c7472018-08-13 15:09:48 +0000687*/
dan07e95232018-08-21 16:32:53 +0000688void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000689 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000690 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000691 renameTokenCheckAll(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000692 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
693 if( pNew ){
694 pNew->p = pPtr;
695 pNew->t = *pToken;
696 pNew->pNext = pParse->pRename;
697 pParse->pRename = pNew;
698 }
danc9461ec2018-08-29 21:00:16 +0000699
dand145e5f2018-08-21 08:29:48 +0000700 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000701}
702
drh4a2c7472018-08-13 15:09:48 +0000703/*
dan07e95232018-08-21 16:32:53 +0000704** It is assumed that there is already a RenameToken object associated
705** with parse tree element pFrom. This function remaps the associated token
706** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000707*/
dan07e95232018-08-21 16:32:53 +0000708void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000709 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000710 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000711 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000712 if( p->p==pFrom ){
713 p->p = pTo;
714 break;
715 }
716 }
dancf8f2892018-08-09 20:47:01 +0000717}
718
drh4a2c7472018-08-13 15:09:48 +0000719/*
dan8900a482018-09-05 14:36:05 +0000720** Walker callback used by sqlite3RenameExprUnmap().
721*/
722static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
723 Parse *pParse = pWalker->pParse;
724 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
725 return WRC_Continue;
726}
727
728/*
729** Remove all nodes that are part of expression pExpr from the rename list.
730*/
731void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
732 Walker sWalker;
733 memset(&sWalker, 0, sizeof(Walker));
734 sWalker.pParse = pParse;
735 sWalker.xExprCallback = renameUnmapExprCb;
736 sqlite3WalkExpr(&sWalker, pExpr);
737}
738
739/*
dane8ab40d2018-09-12 08:51:48 +0000740** Remove all nodes that are part of expression-list pEList from the
741** rename list.
742*/
743void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
744 if( pEList ){
745 int i;
746 Walker sWalker;
747 memset(&sWalker, 0, sizeof(Walker));
748 sWalker.pParse = pParse;
749 sWalker.xExprCallback = renameUnmapExprCb;
750 sqlite3WalkExprList(&sWalker, pEList);
751 for(i=0; i<pEList->nExpr; i++){
752 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
753 }
754 }
755}
756
757/*
drh4a2c7472018-08-13 15:09:48 +0000758** Free the list of RenameToken objects given in the second argument
759*/
dancf8f2892018-08-09 20:47:01 +0000760static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
761 RenameToken *pNext;
762 RenameToken *p;
763 for(p=pToken; p; p=pNext){
764 pNext = p->pNext;
765 sqlite3DbFree(db, p);
766 }
767}
768
dan987db762018-08-14 20:18:50 +0000769/*
770** Search the Parse object passed as the first argument for a RenameToken
771** object associated with parse tree element pPtr. If found, remove it
772** from the Parse object and add it to the list maintained by the
773** RenameCtx object passed as the second argument.
774*/
775static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000776 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000777 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000778 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
779 if( (*pp)->p==pPtr ){
780 RenameToken *pToken = *pp;
781 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000782 pToken->pNext = pCtx->pList;
783 pCtx->pList = pToken;
784 pCtx->nList++;
785 break;
dancf8f2892018-08-09 20:47:01 +0000786 }
787 }
dancf8f2892018-08-09 20:47:01 +0000788}
789
dan24fedb92018-08-18 17:35:38 +0000790/*
danea412512018-12-05 13:49:04 +0000791** Iterate through the Select objects that are part of WITH clauses attached
792** to select statement pSelect.
793*/
794static void renameWalkWith(Walker *pWalker, Select *pSelect){
795 if( pSelect->pWith ){
796 int i;
797 for(i=0; i<pSelect->pWith->nCte; i++){
798 Select *p = pSelect->pWith->a[i].pSelect;
799 NameContext sNC;
800 memset(&sNC, 0, sizeof(sNC));
801 sNC.pParse = pWalker->pParse;
802 sqlite3SelectPrep(sNC.pParse, p, &sNC);
803 sqlite3WalkSelect(pWalker, p);
804 }
805 }
806}
807
808/*
dan24fedb92018-08-18 17:35:38 +0000809** This is a Walker select callback. It does nothing. It is only required
810** because without a dummy callback, sqlite3WalkExpr() and similar do not
811** descend into sub-select statements.
812*/
dan987db762018-08-14 20:18:50 +0000813static int renameColumnSelectCb(Walker *pWalker, Select *p){
danea412512018-12-05 13:49:04 +0000814 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000815 return WRC_Continue;
816}
817
dan987db762018-08-14 20:18:50 +0000818/*
819** This is a Walker expression callback.
820**
821** For every TK_COLUMN node in the expression tree, search to see
822** if the column being references is the column being renamed by an
823** ALTER TABLE statement. If it is, then attach its associated
824** RenameToken object to the list of RenameToken objects being
825** constructed in RenameCtx object at pWalker->u.pRename.
826*/
dancf8f2892018-08-09 20:47:01 +0000827static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000828 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000829 if( pExpr->op==TK_TRIGGER
830 && pExpr->iColumn==p->iCol
831 && pWalker->pParse->pTriggerTab==p->pTab
832 ){
dan5be60c52018-08-15 20:28:39 +0000833 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000834 }else if( pExpr->op==TK_COLUMN
835 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000836 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000837 ){
dan5496d6a2018-08-13 17:14:26 +0000838 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000839 }
840 return WRC_Continue;
841}
842
dan987db762018-08-14 20:18:50 +0000843/*
844** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000845** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000846** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000847** RenameContext. "Last" means the last RenameToken encountered when
848** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000849** return all column name tokens in the order that they are encountered
850** in the SQL statement.
851*/
dan5496d6a2018-08-13 17:14:26 +0000852static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000853 RenameToken *pBest = pCtx->pList;
854 RenameToken *pToken;
855 RenameToken **pp;
856
857 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
858 if( pToken->t.z>pBest->t.z ) pBest = pToken;
859 }
860 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
861 *pp = pBest->pNext;
862
863 return pBest;
864}
865
dan6fe7f232018-08-10 19:19:33 +0000866/*
dan24fedb92018-08-18 17:35:38 +0000867** An error occured while parsing or otherwise processing a database
868** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
869** ALTER TABLE RENAME COLUMN program. The error message emitted by the
870** sub-routine is currently stored in pParse->zErrMsg. This function
871** adds context to the error message and then stores it in pCtx.
872*/
danb0137382018-08-20 20:01:01 +0000873static void renameColumnParseError(
874 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000875 int bPost,
danb0137382018-08-20 20:01:01 +0000876 sqlite3_value *pType,
877 sqlite3_value *pObject,
878 Parse *pParse
879){
drh79a5ee92018-08-23 19:32:04 +0000880 const char *zT = (const char*)sqlite3_value_text(pType);
881 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000882 char *zErr;
danb0137382018-08-20 20:01:01 +0000883
dan0d5fa6b2018-08-24 17:55:49 +0000884 zErr = sqlite3_mprintf("error in %s %s%s: %s",
885 zT, zN, (bPost ? " after rename" : ""),
886 pParse->zErrMsg
887 );
dan24fedb92018-08-18 17:35:38 +0000888 sqlite3_result_error(pCtx, zErr, -1);
889 sqlite3_free(zErr);
890}
891
892/*
dan06249392018-08-21 15:06:59 +0000893** For each name in the the expression-list pEList (i.e. each
894** pEList->a[i].zName) that matches the string in zOld, extract the
895** corresponding rename-token from Parse object pParse and add it
896** to the RenameCtx pCtx.
897*/
898static void renameColumnElistNames(
899 Parse *pParse,
900 RenameCtx *pCtx,
901 ExprList *pEList,
902 const char *zOld
903){
904 if( pEList ){
905 int i;
906 for(i=0; i<pEList->nExpr; i++){
907 char *zName = pEList->a[i].zName;
908 if( 0==sqlite3_stricmp(zName, zOld) ){
909 renameTokenFind(pParse, pCtx, (void*)zName);
910 }
911 }
912 }
913}
914
915/*
916** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
917** that matches the string in zOld, extract the corresponding rename-token
918** from Parse object pParse and add it to the RenameCtx pCtx.
919*/
920static void renameColumnIdlistNames(
921 Parse *pParse,
922 RenameCtx *pCtx,
923 IdList *pIdList,
924 const char *zOld
925){
926 if( pIdList ){
927 int i;
928 for(i=0; i<pIdList->nId; i++){
929 char *zName = pIdList->a[i].zName;
930 if( 0==sqlite3_stricmp(zName, zOld) ){
931 renameTokenFind(pParse, pCtx, (void*)zName);
932 }
933 }
934 }
935}
936
dandd1a9c82018-09-05 08:28:30 +0000937/*
938** Parse the SQL statement zSql using Parse object (*p). The Parse object
939** is initialized by this function before it is used.
940*/
danc9461ec2018-08-29 21:00:16 +0000941static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000942 Parse *p, /* Memory to use for Parse object */
943 const char *zDb, /* Name of schema SQL belongs to */
944 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
945 sqlite3 *db, /* Database handle */
946 const char *zSql, /* SQL to parse */
947 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000948){
949 int rc;
950 char *zErr = 0;
951
952 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
953
954 /* Parse the SQL statement passed as the first argument. If no error
955 ** occurs and the parse does not result in a new table, index or
956 ** trigger object, the database must be corrupt. */
957 memset(p, 0, sizeof(Parse));
958 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
959 p->db = db;
960 p->nQueryLoop = 1;
961 rc = sqlite3RunParser(p, zSql, &zErr);
962 assert( p->zErrMsg==0 );
963 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +0000964 p->zErrMsg = zErr;
965 if( db->mallocFailed ) rc = SQLITE_NOMEM;
966 if( rc==SQLITE_OK
967 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
968 ){
969 rc = SQLITE_CORRUPT_BKPT;
970 }
971
972#ifdef SQLITE_DEBUG
973 /* Ensure that all mappings in the Parse.pRename list really do map to
974 ** a part of the input string. */
975 if( rc==SQLITE_OK ){
976 int nSql = sqlite3Strlen30(zSql);
977 RenameToken *pToken;
978 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
979 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
980 }
981 }
982#endif
983
984 db->init.iDb = 0;
985 return rc;
986}
987
dandd1a9c82018-09-05 08:28:30 +0000988/*
989** This function edits SQL statement zSql, replacing each token identified
990** by the linked list pRename with the text of zNew. If argument bQuote is
991** true, then zNew is always quoted first. If no error occurs, the result
992** is loaded into context object pCtx as the result.
993**
994** Or, if an error occurs (i.e. an OOM condition), an error is left in
995** pCtx and an SQLite error code returned.
996*/
danc9461ec2018-08-29 21:00:16 +0000997static int renameEditSql(
998 sqlite3_context *pCtx, /* Return result here */
999 RenameCtx *pRename, /* Rename context */
1000 const char *zSql, /* SQL statement to edit */
1001 const char *zNew, /* New token text */
1002 int bQuote /* True to always quote token */
1003){
1004 int nNew = sqlite3Strlen30(zNew);
1005 int nSql = sqlite3Strlen30(zSql);
1006 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1007 int rc = SQLITE_OK;
1008 char *zQuot;
1009 char *zOut;
1010 int nQuot;
1011
1012 /* Set zQuot to point to a buffer containing a quoted copy of the
1013 ** identifier zNew. If the corresponding identifier in the original
1014 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1015 ** point to zQuot so that all substitutions are made using the
1016 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001017 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001018 if( zQuot==0 ){
1019 return SQLITE_NOMEM;
1020 }else{
1021 nQuot = sqlite3Strlen30(zQuot);
1022 }
1023 if( bQuote ){
1024 zNew = zQuot;
1025 nNew = nQuot;
1026 }
1027
1028 /* At this point pRename->pList contains a list of RenameToken objects
1029 ** corresponding to all tokens in the input SQL that must be replaced
1030 ** with the new column name. All that remains is to construct and
1031 ** return the edited SQL string. */
1032 assert( nQuot>=nNew );
1033 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1034 if( zOut ){
1035 int nOut = nSql;
1036 memcpy(zOut, zSql, nSql);
1037 while( pRename->pList ){
1038 int iOff; /* Offset of token to replace in zOut */
1039 RenameToken *pBest = renameColumnTokenNext(pRename);
1040
1041 u32 nReplace;
1042 const char *zReplace;
1043 if( sqlite3IsIdChar(*pBest->t.z) ){
1044 nReplace = nNew;
1045 zReplace = zNew;
1046 }else{
1047 nReplace = nQuot;
1048 zReplace = zQuot;
1049 }
1050
1051 iOff = pBest->t.z - zSql;
1052 if( pBest->t.n!=nReplace ){
1053 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1054 nOut - (iOff + pBest->t.n)
1055 );
1056 nOut += nReplace - pBest->t.n;
1057 zOut[nOut] = '\0';
1058 }
1059 memcpy(&zOut[iOff], zReplace, nReplace);
1060 sqlite3DbFree(db, pBest);
1061 }
1062
1063 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1064 sqlite3DbFree(db, zOut);
1065 }else{
1066 rc = SQLITE_NOMEM;
1067 }
1068
1069 sqlite3_free(zQuot);
1070 return rc;
1071}
1072
dandd1a9c82018-09-05 08:28:30 +00001073/*
1074** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1075** it was read from the schema of database zDb. Return SQLITE_OK if
1076** successful. Otherwise, return an SQLite error code and leave an error
1077** message in the Parse object.
1078*/
1079static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001080 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001081 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001082 TriggerStep *pStep;
1083 NameContext sNC;
1084 int rc = SQLITE_OK;
1085
1086 memset(&sNC, 0, sizeof(sNC));
1087 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001088 assert( pNew->pTabSchema );
1089 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1090 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1091 );
1092 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001093 /* ALWAYS() because if the table of the trigger does not exist, the
1094 ** error would have been hit before this point */
1095 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001096 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1097 }
danc9461ec2018-08-29 21:00:16 +00001098
1099 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001100 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001101 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001102 }
1103
dand5e6fef2018-09-07 15:50:31 +00001104 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001105 if( pStep->pSelect ){
1106 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1107 if( pParse->nErr ) rc = pParse->rc;
1108 }
dand5e6fef2018-09-07 15:50:31 +00001109 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001110 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1111 if( pTarget==0 ){
1112 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001113 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
dan0e14e982019-01-18 16:06:18 +00001114 SrcList sSrc;
danc9461ec2018-08-29 21:00:16 +00001115 memset(&sSrc, 0, sizeof(sSrc));
1116 sSrc.nSrc = 1;
1117 sSrc.a[0].zName = pStep->zTarget;
1118 sSrc.a[0].pTab = pTarget;
1119 sNC.pSrcList = &sSrc;
1120 if( pStep->pWhere ){
1121 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1122 }
1123 if( rc==SQLITE_OK ){
1124 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1125 }
1126 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1127 if( pStep->pUpsert ){
1128 Upsert *pUpsert = pStep->pUpsert;
1129 assert( rc==SQLITE_OK );
1130 pUpsert->pUpsertSrc = &sSrc;
1131 sNC.uNC.pUpsert = pUpsert;
1132 sNC.ncFlags = NC_UUpsert;
1133 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1134 if( rc==SQLITE_OK ){
1135 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1136 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1137 }
1138 if( rc==SQLITE_OK ){
1139 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1140 }
1141 if( rc==SQLITE_OK ){
1142 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1143 }
1144 sNC.ncFlags = 0;
1145 }
dan0e14e982019-01-18 16:06:18 +00001146 sNC.pSrcList = 0;
danc9461ec2018-08-29 21:00:16 +00001147 }
1148 }
1149 }
1150 return rc;
1151}
1152
dandd1a9c82018-09-05 08:28:30 +00001153/*
1154** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1155** objects that are part of the trigger passed as the second argument.
1156*/
danc9461ec2018-08-29 21:00:16 +00001157static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1158 TriggerStep *pStep;
1159
1160 /* Find tokens to edit in WHEN clause */
1161 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1162
1163 /* Find tokens to edit in trigger steps */
1164 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1165 sqlite3WalkSelect(pWalker, pStep->pSelect);
1166 sqlite3WalkExpr(pWalker, pStep->pWhere);
1167 sqlite3WalkExprList(pWalker, pStep->pExprList);
1168 if( pStep->pUpsert ){
1169 Upsert *pUpsert = pStep->pUpsert;
1170 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1171 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1172 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1173 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1174 }
1175 }
1176}
1177
dandd1a9c82018-09-05 08:28:30 +00001178/*
1179** Free the contents of Parse object (*pParse). Do not free the memory
1180** occupied by the Parse object itself.
1181*/
dan141e1192018-08-31 18:23:53 +00001182static void renameParseCleanup(Parse *pParse){
1183 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001184 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001185 if( pParse->pVdbe ){
1186 sqlite3VdbeFinalize(pParse->pVdbe);
1187 }
1188 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001189 while( (pIdx = pParse->pNewIndex)!=0 ){
1190 pParse->pNewIndex = pIdx->pNext;
1191 sqlite3FreeIndex(db, pIdx);
1192 }
dan141e1192018-08-31 18:23:53 +00001193 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1194 sqlite3DbFree(db, pParse->zErrMsg);
1195 renameTokenFree(db, pParse->pRename);
1196 sqlite3ParserReset(pParse);
1197}
1198
dan06249392018-08-21 15:06:59 +00001199/*
dan987db762018-08-14 20:18:50 +00001200** SQL function:
1201**
1202** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1203**
1204** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001205** 1. type: Type of object ("table", "view" etc.)
1206** 2. object: Name of object
1207** 3. Database: Database name (e.g. "main")
1208** 4. Table: Table name
1209** 5. iCol: Index of column to rename
1210** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001211** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001212** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001213**
1214** Do a column rename operation on the CREATE statement given in zSql.
1215** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1216** into zNew. The name should be quoted if bQuote is true.
1217**
1218** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001219** It is only accessible to SQL created using sqlite3NestedParse(). It is
1220** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001221*/
dancf8f2892018-08-09 20:47:01 +00001222static void renameColumnFunc(
1223 sqlite3_context *context,
1224 int NotUsed,
1225 sqlite3_value **argv
1226){
1227 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001228 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001229 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001230 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1231 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1232 int iCol = sqlite3_value_int(argv[5]);
1233 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001234 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001235 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001236 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001237 int rc;
dancf8f2892018-08-09 20:47:01 +00001238 Parse sParse;
1239 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001240 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001241 int i;
dan987db762018-08-14 20:18:50 +00001242 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001243#ifndef SQLITE_OMIT_AUTHORIZATION
1244 sqlite3_xauth xAuth = db->xAuth;
1245#endif
dancf8f2892018-08-09 20:47:01 +00001246
drh38d99642018-08-18 18:27:18 +00001247 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001248 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001249 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001250 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001251 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001252 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001253 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001254 if( pTab==0 || iCol>=pTab->nCol ){
1255 sqlite3BtreeLeaveAll(db);
1256 return;
1257 }
dan987db762018-08-14 20:18:50 +00001258 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001259 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001260 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001261
dan141e1192018-08-31 18:23:53 +00001262#ifndef SQLITE_OMIT_AUTHORIZATION
1263 db->xAuth = 0;
1264#endif
danc9461ec2018-08-29 21:00:16 +00001265 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001266
dancf8f2892018-08-09 20:47:01 +00001267 /* Find tokens that need to be replaced. */
1268 memset(&sWalker, 0, sizeof(Walker));
1269 sWalker.pParse = &sParse;
1270 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001271 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001272 sWalker.u.pRename = &sCtx;
1273
dan0cbb0b12018-08-16 19:49:16 +00001274 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001275 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001276 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001277 Select *pSelect = sParse.pNewTable->pSelect;
1278 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001279 sParse.rc = SQLITE_OK;
1280 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1281 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1282 if( rc==SQLITE_OK ){
1283 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001284 }
dan987db762018-08-14 20:18:50 +00001285 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1286 }else{
1287 /* A regular table */
1288 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1289 FKey *pFKey;
1290 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001291 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001292 if( bFKOnly==0 ){
1293 renameTokenFind(
1294 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1295 );
1296 if( sCtx.iCol<0 ){
1297 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001298 }
dan987db762018-08-14 20:18:50 +00001299 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1300 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1301 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1302 }
drh885eeb62019-01-09 02:02:24 +00001303 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1304 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1305 }
dan987db762018-08-14 20:18:50 +00001306 }
1307
1308 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1309 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001310 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001311 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1312 }
1313 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1314 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1315 ){
1316 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1317 }
dan6fe7f232018-08-10 19:19:33 +00001318 }
dancf8f2892018-08-09 20:47:01 +00001319 }
1320 }
dan5496d6a2018-08-13 17:14:26 +00001321 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001322 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1323 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001324 }else{
dan5be60c52018-08-15 20:28:39 +00001325 /* A trigger */
1326 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001327 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001328 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001329
danc9461ec2018-08-29 21:00:16 +00001330 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1331 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001332 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001333 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001334 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001335 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1336 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001337 }
danc9461ec2018-08-29 21:00:16 +00001338 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1339 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001340 }
1341 }
1342 }
1343
dan5be60c52018-08-15 20:28:39 +00001344
1345 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001346 if( sParse.pTriggerTab==pTab ){
1347 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001348 }
dan5be60c52018-08-15 20:28:39 +00001349
danc9461ec2018-08-29 21:00:16 +00001350 /* Find tokens to edit in various expressions and selects */
1351 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001352 }
1353
dan987db762018-08-14 20:18:50 +00001354 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001355 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001356
drh5fc22cd2018-08-13 13:43:11 +00001357renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001358 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001359 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001360 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001361 }else{
1362 sqlite3_result_error_code(context, rc);
1363 }
1364 }
1365
dan141e1192018-08-31 18:23:53 +00001366 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001367 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001368#ifndef SQLITE_OMIT_AUTHORIZATION
1369 db->xAuth = xAuth;
1370#endif
drhda76adc2018-08-25 02:04:05 +00001371 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001372}
1373
dandd1a9c82018-09-05 08:28:30 +00001374/*
1375** Walker expression callback used by "RENAME TABLE".
1376*/
danc9461ec2018-08-29 21:00:16 +00001377static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1378 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001379 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1380 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001381 }
1382 return WRC_Continue;
1383}
1384
1385/*
dandd1a9c82018-09-05 08:28:30 +00001386** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001387*/
1388static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1389 int i;
1390 RenameCtx *p = pWalker->u.pRename;
1391 SrcList *pSrc = pSelect->pSrc;
drh974b2482018-12-06 01:53:12 +00001392 if( pSrc==0 ){
1393 assert( pWalker->pParse->db->mallocFailed );
1394 return WRC_Abort;
1395 }
danc9461ec2018-08-29 21:00:16 +00001396 for(i=0; i<pSrc->nSrc; i++){
1397 struct SrcList_item *pItem = &pSrc->a[i];
1398 if( pItem->pTab==p->pTab ){
1399 renameTokenFind(pWalker->pParse, p, pItem->zName);
1400 }
1401 }
danea412512018-12-05 13:49:04 +00001402 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001403
1404 return WRC_Continue;
1405}
1406
1407
1408/*
1409** This C function implements an SQL user function that is used by SQL code
1410** generated by the ALTER TABLE ... RENAME command to modify the definition
1411** of any foreign key constraints that use the table being renamed as the
1412** parent table. It is passed three arguments:
1413**
dan141e1192018-08-31 18:23:53 +00001414** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001415** 1. type: Type of object ("table", "view" etc.)
1416** 2. object: Name of object
1417** 3: The complete text of the schema statement being modified,
1418** 4: The old name of the table being renamed, and
1419** 5: The new name of the table being renamed.
1420** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001421**
dan141e1192018-08-31 18:23:53 +00001422** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001423**
dan141e1192018-08-31 18:23:53 +00001424** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001425** -> 'CREATE TABLE t1(a REFERENCES t3)'
1426*/
1427static void renameTableFunc(
1428 sqlite3_context *context,
1429 int NotUsed,
1430 sqlite3_value **argv
1431){
1432 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001433 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001434 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1435 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1436 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1437 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001438 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001439
dan141e1192018-08-31 18:23:53 +00001440 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001441 Parse sParse;
1442 int rc;
1443 int bQuote = 1;
1444 RenameCtx sCtx;
1445 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001446
dan141e1192018-08-31 18:23:53 +00001447#ifndef SQLITE_OMIT_AUTHORIZATION
1448 sqlite3_xauth xAuth = db->xAuth;
1449 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001450#endif
1451
dan141e1192018-08-31 18:23:53 +00001452 sqlite3BtreeEnterAll(db);
1453
1454 memset(&sCtx, 0, sizeof(RenameCtx));
1455 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1456 memset(&sWalker, 0, sizeof(Walker));
1457 sWalker.pParse = &sParse;
1458 sWalker.xExprCallback = renameTableExprCb;
1459 sWalker.xSelectCallback = renameTableSelectCb;
1460 sWalker.u.pRename = &sCtx;
1461
1462 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1463
1464 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001465 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001466 if( sParse.pNewTable ){
1467 Table *pTab = sParse.pNewTable;
1468
1469 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001470 if( isLegacy==0 ){
1471 NameContext sNC;
1472 memset(&sNC, 0, sizeof(sNC));
1473 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001474
dan674b8942018-09-20 08:28:01 +00001475 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1476 if( sParse.nErr ) rc = sParse.rc;
1477 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1478 }
dan141e1192018-08-31 18:23:53 +00001479 }else{
1480 /* Modify any FK definitions to point to the new table. */
1481#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001482 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001483 FKey *pFKey;
1484 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1485 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1486 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1487 }
dan141e1192018-08-31 18:23:53 +00001488 }
1489 }
1490#endif
1491
1492 /* If this is the table being altered, fix any table refs in CHECK
1493 ** expressions. Also update the name that appears right after the
1494 ** "CREATE [VIRTUAL] TABLE" bit. */
1495 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1496 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001497 if( isLegacy==0 ){
1498 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1499 }
dan141e1192018-08-31 18:23:53 +00001500 renameTokenFind(&sParse, &sCtx, pTab->zName);
1501 }
danc9461ec2018-08-29 21:00:16 +00001502 }
1503 }
danc9461ec2018-08-29 21:00:16 +00001504
dan141e1192018-08-31 18:23:53 +00001505 else if( sParse.pNewIndex ){
1506 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001507 if( isLegacy==0 ){
1508 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1509 }
dan141e1192018-08-31 18:23:53 +00001510 }
danc9461ec2018-08-29 21:00:16 +00001511
1512#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001513 else{
dan141e1192018-08-31 18:23:53 +00001514 Trigger *pTrigger = sParse.pNewTrigger;
1515 TriggerStep *pStep;
1516 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1517 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1518 ){
1519 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1520 }
danc9461ec2018-08-29 21:00:16 +00001521
dan674b8942018-09-20 08:28:01 +00001522 if( isLegacy==0 ){
1523 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1524 if( rc==SQLITE_OK ){
1525 renameWalkTrigger(&sWalker, pTrigger);
1526 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1527 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1528 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1529 }
dan141e1192018-08-31 18:23:53 +00001530 }
dan0ccda962018-08-30 16:26:48 +00001531 }
danc9461ec2018-08-29 21:00:16 +00001532 }
1533 }
dan141e1192018-08-31 18:23:53 +00001534#endif
danc9461ec2018-08-29 21:00:16 +00001535 }
dan141e1192018-08-31 18:23:53 +00001536
1537 if( rc==SQLITE_OK ){
1538 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1539 }
1540 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001541 if( sParse.zErrMsg ){
1542 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1543 }else{
1544 sqlite3_result_error_code(context, rc);
1545 }
dan141e1192018-08-31 18:23:53 +00001546 }
1547
1548 renameParseCleanup(&sParse);
1549 renameTokenFree(db, sCtx.pList);
1550 sqlite3BtreeLeaveAll(db);
1551#ifndef SQLITE_OMIT_AUTHORIZATION
1552 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001553#endif
1554 }
1555
danc9461ec2018-08-29 21:00:16 +00001556 return;
1557}
1558
dandd1a9c82018-09-05 08:28:30 +00001559/*
1560** An SQL user function that checks that there are no parse or symbol
1561** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1562** After an ALTER TABLE .. RENAME operation is performed and the schema
1563** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001564** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001565**
1566** 0: Database name ("main", "temp" etc.).
1567** 1: SQL statement.
1568** 2: Object type ("view", "table", "trigger" or "index").
1569** 3: Object name.
1570** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001571**
1572** Unless it finds an error, this function normally returns NULL. However, it
1573** returns integer value 1 if:
1574**
1575** * the SQL argument creates a trigger, and
1576** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001577*/
dan9d324822018-08-30 20:03:44 +00001578static void renameTableTest(
1579 sqlite3_context *context,
1580 int NotUsed,
1581 sqlite3_value **argv
1582){
1583 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001584 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1585 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001586 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001587 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001588
dan141e1192018-08-31 18:23:53 +00001589#ifndef SQLITE_OMIT_AUTHORIZATION
1590 sqlite3_xauth xAuth = db->xAuth;
1591 db->xAuth = 0;
1592#endif
1593
drh5b1da302018-09-01 20:02:07 +00001594 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001595 if( zDb && zInput ){
1596 int rc;
1597 Parse sParse;
1598 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1599 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001600 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001601 NameContext sNC;
1602 memset(&sNC, 0, sizeof(sNC));
1603 sNC.pParse = &sParse;
1604 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1605 if( sParse.nErr ) rc = sParse.rc;
1606 }
1607
1608 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001609 if( isLegacy==0 ){
1610 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1611 }
drh3b700452018-09-07 19:12:08 +00001612 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001613 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1614 int i2 = sqlite3FindDbName(db, zDb);
1615 if( i1==i2 ) sqlite3_result_int(context, 1);
1616 }
dan09236502018-09-01 16:05:50 +00001617 }
dan9d324822018-08-30 20:03:44 +00001618 }
1619
dan09236502018-09-01 16:05:50 +00001620 if( rc!=SQLITE_OK ){
1621 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001622 }
dan09236502018-09-01 16:05:50 +00001623 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001624 }
1625
dan141e1192018-08-31 18:23:53 +00001626#ifndef SQLITE_OMIT_AUTHORIZATION
1627 db->xAuth = xAuth;
1628#endif
dan9d324822018-08-30 20:03:44 +00001629}
1630
dancf8f2892018-08-09 20:47:01 +00001631/*
1632** Register built-in functions used to help implement ALTER TABLE
1633*/
1634void sqlite3AlterFunctions(void){
1635 static FuncDef aAlterTableFuncs[] = {
drheea8eb62018-11-26 18:09:15 +00001636 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1637 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1638 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001639 };
1640 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1641}
drhd0e4a6c2005-02-15 20:47:57 +00001642#endif /* SQLITE_ALTER_TABLE */