blob: 38446f9987a76d8e7ac077a543f8c5512ff36597 [file] [log] [blame]
drhd0e4a6c2005-02-15 20:47:57 +00001/*
2** 2005 February 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains C code routines that used to generate VDBE code
13** that implements the ALTER TABLE command.
drhd0e4a6c2005-02-15 20:47:57 +000014*/
15#include "sqliteInt.h"
16
drh1f01ec12005-02-15 21:36:18 +000017/*
18** The code in this file only exists if we are not omitting the
19** ALTER TABLE logic from the build.
20*/
drhd0e4a6c2005-02-15 20:47:57 +000021#ifndef SQLITE_OMIT_ALTERTABLE
drh1f01ec12005-02-15 21:36:18 +000022
drh1f01ec12005-02-15 21:36:18 +000023/*
danbe535002011-04-01 15:15:58 +000024** Parameter zName is the name of a table that is about to be altered
25** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
26** If the table is a system table, this function leaves an error message
27** in pParse->zErr (system tables may not be altered) and returns non-zero.
28**
29** Or, if zName is not a system table, zero is returned.
30*/
dan397a78d2018-12-18 20:31:14 +000031static int isAlterableTable(Parse *pParse, Table *pTab){
32 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
33#ifndef SQLITE_OMIT_VIRTUALTABLE
drh070ae3b2019-11-16 13:51:31 +000034 || ( (pTab->tabFlags & TF_Shadow)!=0
35 && sqlite3ReadOnlyShadowTables(pParse->db)
dan397a78d2018-12-18 20:31:14 +000036 )
37#endif
38 ){
39 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
danbe535002011-04-01 15:15:58 +000040 return 1;
41 }
42 return 0;
43}
44
dan09236502018-09-01 16:05:50 +000045/*
46** Generate code to verify that the schemas of database zDb and, if
47** bTemp is not true, database "temp", can still be parsed. This is
48** called at the end of the generation of an ALTER TABLE ... RENAME ...
49** statement to ensure that the operation has not rendered any schema
50** objects unusable.
51*/
drh16b870d2018-09-12 15:51:56 +000052static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
dan9d324822018-08-30 20:03:44 +000053 sqlite3NestedParse(pParse,
54 "SELECT 1 "
55 "FROM \"%w\".%s "
dan65455fc2019-04-19 16:34:22 +000056 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000057 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000058 " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
dan9d324822018-08-30 20:03:44 +000059 zDb, MASTER_NAME,
60 zDb, bTemp
61 );
62
63 if( bTemp==0 ){
64 sqlite3NestedParse(pParse,
65 "SELECT 1 "
66 "FROM temp.%s "
dan65455fc2019-04-19 16:34:22 +000067 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan9d324822018-08-30 20:03:44 +000068 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000069 " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
dan9d324822018-08-30 20:03:44 +000070 MASTER_NAME, zDb
71 );
72 }
73}
74
danbe535002011-04-01 15:15:58 +000075/*
dan09236502018-09-01 16:05:50 +000076** Generate code to reload the schema for database iDb. And, if iDb!=1, for
77** the temp database as well.
78*/
drh16b870d2018-09-12 15:51:56 +000079static void renameReloadSchema(Parse *pParse, int iDb){
dan09236502018-09-01 16:05:50 +000080 Vdbe *v = pParse->pVdbe;
81 if( v ){
82 sqlite3ChangeCookie(pParse, iDb);
83 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
84 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
85 }
86}
87
88/*
drhd0e4a6c2005-02-15 20:47:57 +000089** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
90** command.
91*/
92void sqlite3AlterRenameTable(
93 Parse *pParse, /* Parser context. */
94 SrcList *pSrc, /* The table to rename. */
95 Token *pName /* The new table name. */
96){
97 int iDb; /* Database that contains the table */
98 char *zDb; /* Name of database iDb */
99 Table *pTab; /* Table being renamed */
100 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000101 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000102 int nTabName; /* Number of UTF-8 characters in zTabName */
103 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000104 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000105 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000106 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000107
drh8257aa82017-07-26 19:59:13 +0000108 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000109 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000110 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000111 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000112
dan41fb5cd2012-10-04 19:33:00 +0000113 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000114 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000115 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000116 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000117 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000118
119 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000120 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000121 if( !zName ) goto exit_rename_table;
122
123 /* Check that a table or index named 'zName' does not already exist
124 ** in database iDb. If so, this is an error.
125 */
126 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
127 sqlite3ErrorMsg(pParse,
128 "there is already another table or index with this name: %s", zName);
129 goto exit_rename_table;
130 }
131
132 /* Make sure it is not a system table being altered, or a reserved name
133 ** that the table is being renamed to.
134 */
dan397a78d2018-12-18 20:31:14 +0000135 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
drhd0e4a6c2005-02-15 20:47:57 +0000136 goto exit_rename_table;
137 }
drhc5a93d42019-08-12 00:08:07 +0000138 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){
139 goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000140 }
141
danielk197761116ae2007-12-13 08:15:30 +0000142#ifndef SQLITE_OMIT_VIEW
143 if( pTab->pSelect ){
144 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
145 goto exit_rename_table;
146 }
147#endif
148
drhd0e4a6c2005-02-15 20:47:57 +0000149#ifndef SQLITE_OMIT_AUTHORIZATION
150 /* Invoke the authorization callback. */
151 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
152 goto exit_rename_table;
153 }
154#endif
155
danielk1977182c4ba2007-06-27 15:53:34 +0000156#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000157 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
158 goto exit_rename_table;
159 }
danielk1977595a5232009-07-24 17:58:53 +0000160 if( IsVirtual(pTab) ){
161 pVTab = sqlite3GetVTable(db, pTab);
162 if( pVTab->pVtab->pModule->xRename==0 ){
163 pVTab = 0;
164 }
danielk1977182c4ba2007-06-27 15:53:34 +0000165 }
166#endif
167
dan1f3b2842019-03-15 16:17:32 +0000168 /* Begin a transaction for database iDb. Then modify the schema cookie
169 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(),
170 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the
171 ** nested SQL may raise an exception. */
drhd0e4a6c2005-02-15 20:47:57 +0000172 v = sqlite3GetVdbe(pParse);
173 if( v==0 ){
174 goto exit_rename_table;
175 }
dan1f3b2842019-03-15 16:17:32 +0000176 sqlite3MayAbort(pParse);
drhd0e4a6c2005-02-15 20:47:57 +0000177
drh4e5dd852007-05-15 03:56:49 +0000178 /* figure out how many UTF-8 characters are in zName */
179 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000180 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000181
danc9461ec2018-08-29 21:00:16 +0000182 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
183 ** the schema to use the new table name. */
184 sqlite3NestedParse(pParse,
185 "UPDATE \"%w\".%s SET "
dan65372fa2018-09-03 20:05:15 +0000186 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000187 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
dan65455fc2019-04-19 16:34:22 +0000188 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'"
dan0ccda962018-08-30 16:26:48 +0000189 , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000190 );
dan432cc5b2009-09-26 17:51:48 +0000191
danc9461ec2018-08-29 21:00:16 +0000192 /* Update the tbl_name and name columns of the sqlite_master table
193 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000194 sqlite3NestedParse(pParse,
195 "UPDATE %Q.%s SET "
drhd0e4a6c2005-02-15 20:47:57 +0000196 "tbl_name = %Q, "
197 "name = CASE "
198 "WHEN type='table' THEN %Q "
dan65455fc2019-04-19 16:34:22 +0000199 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' "
200 " 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
301 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
302 ** If there is a NOT NULL constraint, then the default value for the
303 ** column must not be NULL.
304 */
drha371ace2012-09-13 14:22:47 +0000305 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000306 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
307 return;
308 }
309 if( pNew->pIndex ){
310 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
311 return;
312 }
drhc27ea2a2019-10-16 20:05:56 +0000313 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
314 /* If the default value for the new column was specified with a
315 ** literal NULL, then set pDflt to 0. This simplifies checking
316 ** for an SQL NULL default below.
317 */
318 assert( pDflt==0 || pDflt->op==TK_SPAN );
319 if( pDflt && pDflt->pLeft->op==TK_NULL ){
320 pDflt = 0;
321 }
322 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
323 sqlite3ErrorMsg(pParse,
324 "Cannot add a REFERENCES column with non-NULL default value");
325 return;
326 }
327 if( pCol->notNull && !pDflt ){
328 sqlite3ErrorMsg(pParse,
329 "Cannot add a NOT NULL column with default value NULL");
330 return;
331 }
332
333 /* Ensure the default expression is something that sqlite3ValueFromExpr()
334 ** can handle (i.e. not CURRENT_TIME etc.)
335 */
336 if( pDflt ){
337 sqlite3_value *pVal = 0;
338 int rc;
339 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
340 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
341 if( rc!=SQLITE_OK ){
342 assert( db->mallocFailed == 1 );
343 return;
344 }
345 if( !pVal ){
346 sqlite3ErrorMsg(pParse,"Cannot add a column with non-constant default");
347 return;
348 }
349 sqlite3ValueFree(pVal);
350 }
drh035f6d92019-10-24 01:04:10 +0000351 }else if( pCol->colFlags & COLFLAG_STORED ){
352 sqlite3ErrorMsg(pParse, "cannot add a STORED column");
353 return;
danielk197719a8e7e2005-03-17 05:03:38 +0000354 }
355
danielk197719a8e7e2005-03-17 05:03:38 +0000356
357 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000358 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000359 if( zCol ){
360 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000361 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000362 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000363 *zEnd-- = '\0';
364 }
drh8257aa82017-07-26 19:59:13 +0000365 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000366 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000367 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000368 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000369 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000370 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000371 zTab
372 );
drh633e6d52008-07-28 19:34:53 +0000373 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000374 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000375 }
376
drh86396212016-07-14 19:13:11 +0000377 /* Make sure the schema version is at least 3. But do not upgrade
378 ** from less than 3 to 4, as that will corrupt any preexisting DESC
379 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000380 */
dan09236502018-09-01 16:05:50 +0000381 v = sqlite3GetVdbe(pParse);
382 if( v ){
383 r1 = sqlite3GetTempReg(pParse);
384 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
385 sqlite3VdbeUsesBtree(v, iDb);
386 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
387 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
388 VdbeCoverage(v);
389 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
390 sqlite3ReleaseTempReg(pParse, r1);
391 }
danielk197719a8e7e2005-03-17 05:03:38 +0000392
dan09236502018-09-01 16:05:50 +0000393 /* Reload the table definition */
394 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000395}
396
drhfdd6e852005-12-16 01:06:16 +0000397/*
danielk197719a8e7e2005-03-17 05:03:38 +0000398** This function is called by the parser after the table-name in
399** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
400** pSrc is the full-name of the table being altered.
401**
402** This routine makes a (partial) copy of the Table structure
403** for the table being altered and sets Parse.pNewTable to point
404** to it. Routines called by the parser as the column definition
405** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
406** the copy. The copy of the Table structure is deleted by tokenize.c
407** after parsing is finished.
408**
409** Routine sqlite3AlterFinishAddColumn() will be called to complete
410** coding the "ALTER TABLE ... ADD" statement.
411*/
412void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
413 Table *pNew;
414 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000415 int iDb;
416 int i;
417 int nAlloc;
drh17435752007-08-16 04:30:38 +0000418 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000419
420 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000421 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000422 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000423 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000424 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000425 if( !pTab ) goto exit_begin_add_column;
426
danielk19775ee9d692006-06-21 12:36:25 +0000427#ifndef SQLITE_OMIT_VIRTUALTABLE
428 if( IsVirtual(pTab) ){
429 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
430 goto exit_begin_add_column;
431 }
432#endif
433
danielk197719a8e7e2005-03-17 05:03:38 +0000434 /* Make sure this is not an attempt to ALTER a view. */
435 if( pTab->pSelect ){
436 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
437 goto exit_begin_add_column;
438 }
dan397a78d2018-12-18 20:31:14 +0000439 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){
danbe535002011-04-01 15:15:58 +0000440 goto exit_begin_add_column;
441 }
danielk197719a8e7e2005-03-17 05:03:38 +0000442
dan03e025e2019-10-07 18:43:21 +0000443 sqlite3MayAbort(pParse);
danielk197719a8e7e2005-03-17 05:03:38 +0000444 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000445 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000446
447 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000448 ** sqlite3AddColumn() function and friends to modify. But modify
449 ** the name by adding an "sqlite_altertab_" prefix. By adding this
450 ** prefix, we insure that the name will not collide with an existing
451 ** table because user table are not allowed to have the "sqlite_"
452 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000453 */
drh17435752007-08-16 04:30:38 +0000454 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000455 if( !pNew ) goto exit_begin_add_column;
456 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000457 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000458 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000459 assert( pNew->nCol>0 );
460 nAlloc = (((pNew->nCol-1)/8)*8)+8;
461 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000462 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000463 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000464 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000465 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000466 goto exit_begin_add_column;
467 }
468 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
469 for(i=0; i<pNew->nCol; i++){
470 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000471 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000472 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000473 pCol->pDflt = 0;
474 }
drh17435752007-08-16 04:30:38 +0000475 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000476 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000477 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000478
danielk197719a8e7e2005-03-17 05:03:38 +0000479exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000480 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000481 return;
482}
dancf8f2892018-08-09 20:47:01 +0000483
drh4a2c7472018-08-13 15:09:48 +0000484/*
dan9d705572018-08-20 16:16:05 +0000485** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
486** command. This function checks if the table is a view or virtual
487** table (columns of views or virtual tables may not be renamed). If so,
488** it loads an error message into pParse and returns non-zero.
489**
490** Or, if pTab is not a view or virtual table, zero is returned.
491*/
492#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
493static int isRealTable(Parse *pParse, Table *pTab){
494 const char *zType = 0;
495#ifndef SQLITE_OMIT_VIEW
496 if( pTab->pSelect ){
497 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000498 }
dan9d705572018-08-20 16:16:05 +0000499#endif
500#ifndef SQLITE_OMIT_VIRTUALTABLE
501 if( IsVirtual(pTab) ){
502 zType = "virtual table";
503 }
504#endif
505 if( zType ){
506 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000507 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000508 );
509 return 1;
510 }
511 return 0;
512}
513#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
514# define isRealTable(x,y) (0)
515#endif
516
517/*
drh4a2c7472018-08-13 15:09:48 +0000518** Handles the following parser reduction:
519**
520** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
521*/
dancf8f2892018-08-09 20:47:01 +0000522void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000523 Parse *pParse, /* Parsing context */
524 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
525 Token *pOld, /* Name of column being changed */
526 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000527){
drh4a2c7472018-08-13 15:09:48 +0000528 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000529 Table *pTab; /* Table being updated */
530 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000531 char *zOld = 0; /* Old column name */
532 char *zNew = 0; /* New column name */
533 const char *zDb; /* Name of schema containing the table */
534 int iSchema; /* Index of the schema */
535 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000536
drh4a2c7472018-08-13 15:09:48 +0000537 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000538 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
539 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000540
541 /* Cannot alter a system table */
dan397a78d2018-12-18 20:31:14 +0000542 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000543 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000544
545 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000546 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
547 assert( iSchema>=0 );
548 zDb = db->aDb[iSchema].zDbSName;
549
drh0d019b92018-08-25 16:14:46 +0000550#ifndef SQLITE_OMIT_AUTHORIZATION
551 /* Invoke the authorization callback. */
552 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
553 goto exit_rename_column;
554 }
555#endif
556
drh4a2c7472018-08-13 15:09:48 +0000557 /* Make sure the old name really is a column name in the table to be
558 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000559 zOld = sqlite3NameFromToken(db, pOld);
560 if( !zOld ) goto exit_rename_column;
561 for(iCol=0; iCol<pTab->nCol; iCol++){
562 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
563 }
564 if( iCol==pTab->nCol ){
565 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
566 goto exit_rename_column;
567 }
568
drh4a2c7472018-08-13 15:09:48 +0000569 /* Do the rename operation using a recursive UPDATE statement that
570 ** uses the sqlite_rename_column() SQL function to compute the new
571 ** CREATE statement text for the sqlite_master table.
572 */
dan1f3b2842019-03-15 16:17:32 +0000573 sqlite3MayAbort(pParse);
dancf8f2892018-08-09 20:47:01 +0000574 zNew = sqlite3NameFromToken(db, pNew);
575 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000576 assert( pNew->n>0 );
577 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000578 sqlite3NestedParse(pParse,
579 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000580 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan65455fc2019-04-19 16:34:22 +0000581 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' "
582 " AND (type != 'index' OR tbl_name = %Q)"
dan499b8252018-08-17 18:08:28 +0000583 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000584 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000585 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000586 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000587 );
588
dan9d324822018-08-30 20:03:44 +0000589 sqlite3NestedParse(pParse,
590 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000591 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000592 "WHERE type IN ('trigger', 'view')",
593 MASTER_NAME,
594 zDb, pTab->zName, iCol, zNew, bQuote
595 );
596
dane325ffe2018-08-11 13:40:20 +0000597 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000598 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000599 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000600
dancf8f2892018-08-09 20:47:01 +0000601 exit_rename_column:
602 sqlite3SrcListDelete(db, pSrc);
603 sqlite3DbFree(db, zOld);
604 sqlite3DbFree(db, zNew);
605 return;
606}
607
drh4a2c7472018-08-13 15:09:48 +0000608/*
609** Each RenameToken object maps an element of the parse tree into
610** the token that generated that element. The parse tree element
611** might be one of:
612**
613** * A pointer to an Expr that represents an ID
614** * The name of a table column in Column.zName
615**
616** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000617** Each new object is created by sqlite3RenameTokenMap().
618** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000619** routine is used to keep the mapping current.
620**
621** After the parse finishes, renameTokenFind() routine can be used
622** to look up the actual token value that created some element in
623** the parse tree.
624*/
dancf8f2892018-08-09 20:47:01 +0000625struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000626 void *p; /* Parse tree element created by token t */
627 Token t; /* The token that created parse tree element p */
628 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000629};
630
drh4a2c7472018-08-13 15:09:48 +0000631/*
632** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
633** down into the Walker.
634*/
dan5496d6a2018-08-13 17:14:26 +0000635typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000636struct RenameCtx {
637 RenameToken *pList; /* List of tokens to overwrite */
638 int nList; /* Number of tokens in pList */
639 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000640 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000641 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000642};
643
dan8900a482018-09-05 14:36:05 +0000644#ifdef SQLITE_DEBUG
645/*
646** This function is only for debugging. It performs two tasks:
647**
648** 1. Checks that pointer pPtr does not already appear in the
649** rename-token list.
650**
651** 2. Dereferences each pointer in the rename-token list.
652**
653** The second is most effective when debugging under valgrind or
654** address-sanitizer or similar. If any of these pointers no longer
655** point to valid objects, an exception is raised by the memory-checking
656** tool.
657**
658** The point of this is to prevent comparisons of invalid pointer values.
659** Even though this always seems to work, it is undefined according to the
660** C standard. Example of undefined comparison:
661**
662** sqlite3_free(x);
663** if( x==y ) ...
664**
665** Technically, as x no longer points into a valid object or to the byte
666** following a valid object, it may not be used in comparison operations.
667*/
drh16b870d2018-09-12 15:51:56 +0000668static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000669 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
670 RenameToken *p;
671 u8 i = 0;
672 for(p=pParse->pRename; p; p=p->pNext){
673 if( p->p ){
674 assert( p->p!=pPtr );
675 i += *(u8*)(p->p);
676 }
danc9461ec2018-08-29 21:00:16 +0000677 }
678 }
679}
dan8900a482018-09-05 14:36:05 +0000680#else
681# define renameTokenCheckAll(x,y)
682#endif
danc9461ec2018-08-29 21:00:16 +0000683
drh4a2c7472018-08-13 15:09:48 +0000684/*
drh49b269e2018-11-26 15:00:25 +0000685** Remember that the parser tree element pPtr was created using
686** the token pToken.
dan07e95232018-08-21 16:32:53 +0000687**
drh49b269e2018-11-26 15:00:25 +0000688** In other words, construct a new RenameToken object and add it
689** to the list of RenameToken objects currently being built up
690** in pParse->pRename.
691**
692** The pPtr argument is returned so that this routine can be used
693** with tail recursion in tokenExpr() routine, for a small performance
694** improvement.
drh4a2c7472018-08-13 15:09:48 +0000695*/
dan07e95232018-08-21 16:32:53 +0000696void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000697 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000698 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000699 renameTokenCheckAll(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000700 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
701 if( pNew ){
702 pNew->p = pPtr;
703 pNew->t = *pToken;
704 pNew->pNext = pParse->pRename;
705 pParse->pRename = pNew;
706 }
danc9461ec2018-08-29 21:00:16 +0000707
dand145e5f2018-08-21 08:29:48 +0000708 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000709}
710
drh4a2c7472018-08-13 15:09:48 +0000711/*
dan07e95232018-08-21 16:32:53 +0000712** It is assumed that there is already a RenameToken object associated
713** with parse tree element pFrom. This function remaps the associated token
714** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000715*/
dan07e95232018-08-21 16:32:53 +0000716void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000717 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000718 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000719 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000720 if( p->p==pFrom ){
721 p->p = pTo;
722 break;
723 }
724 }
dancf8f2892018-08-09 20:47:01 +0000725}
726
drh4a2c7472018-08-13 15:09:48 +0000727/*
dan8900a482018-09-05 14:36:05 +0000728** Walker callback used by sqlite3RenameExprUnmap().
729*/
730static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
731 Parse *pParse = pWalker->pParse;
732 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
733 return WRC_Continue;
734}
735
736/*
dan0b277a92019-06-11 12:03:10 +0000737** Walker callback used by sqlite3RenameExprUnmap().
738*/
739static int renameUnmapSelectCb(Walker *pWalker, Select *p){
drhbdf4cf02019-06-15 15:21:49 +0000740 Parse *pParse = pWalker->pParse;
741 int i;
742 if( ALWAYS(p->pEList) ){
743 ExprList *pList = p->pEList;
744 for(i=0; i<pList->nExpr; i++){
745 if( pList->a[i].zName ){
746 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zName);
747 }
748 }
749 }
drh2c3f4652019-06-11 16:43:58 +0000750 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
drhbdf4cf02019-06-15 15:21:49 +0000751 SrcList *pSrc = p->pSrc;
752 for(i=0; i<pSrc->nSrc; i++){
753 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
dan0b277a92019-06-11 12:03:10 +0000754 }
755 }
756 return WRC_Continue;
757}
758
759/*
dan8900a482018-09-05 14:36:05 +0000760** Remove all nodes that are part of expression pExpr from the rename list.
761*/
762void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
763 Walker sWalker;
764 memset(&sWalker, 0, sizeof(Walker));
765 sWalker.pParse = pParse;
766 sWalker.xExprCallback = renameUnmapExprCb;
dan0b277a92019-06-11 12:03:10 +0000767 sWalker.xSelectCallback = renameUnmapSelectCb;
dan8900a482018-09-05 14:36:05 +0000768 sqlite3WalkExpr(&sWalker, pExpr);
769}
770
771/*
dane8ab40d2018-09-12 08:51:48 +0000772** Remove all nodes that are part of expression-list pEList from the
773** rename list.
774*/
775void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
776 if( pEList ){
777 int i;
778 Walker sWalker;
779 memset(&sWalker, 0, sizeof(Walker));
780 sWalker.pParse = pParse;
781 sWalker.xExprCallback = renameUnmapExprCb;
782 sqlite3WalkExprList(&sWalker, pEList);
783 for(i=0; i<pEList->nExpr; i++){
784 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
785 }
786 }
787}
788
789/*
drh4a2c7472018-08-13 15:09:48 +0000790** Free the list of RenameToken objects given in the second argument
791*/
dancf8f2892018-08-09 20:47:01 +0000792static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
793 RenameToken *pNext;
794 RenameToken *p;
795 for(p=pToken; p; p=pNext){
796 pNext = p->pNext;
797 sqlite3DbFree(db, p);
798 }
799}
800
dan987db762018-08-14 20:18:50 +0000801/*
802** Search the Parse object passed as the first argument for a RenameToken
803** object associated with parse tree element pPtr. If found, remove it
804** from the Parse object and add it to the list maintained by the
805** RenameCtx object passed as the second argument.
806*/
807static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000808 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000809 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000810 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
811 if( (*pp)->p==pPtr ){
812 RenameToken *pToken = *pp;
813 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000814 pToken->pNext = pCtx->pList;
815 pCtx->pList = pToken;
816 pCtx->nList++;
817 break;
dancf8f2892018-08-09 20:47:01 +0000818 }
819 }
dancf8f2892018-08-09 20:47:01 +0000820}
821
dan24fedb92018-08-18 17:35:38 +0000822/*
danea412512018-12-05 13:49:04 +0000823** Iterate through the Select objects that are part of WITH clauses attached
824** to select statement pSelect.
825*/
826static void renameWalkWith(Walker *pWalker, Select *pSelect){
827 if( pSelect->pWith ){
828 int i;
829 for(i=0; i<pSelect->pWith->nCte; i++){
830 Select *p = pSelect->pWith->a[i].pSelect;
831 NameContext sNC;
832 memset(&sNC, 0, sizeof(sNC));
833 sNC.pParse = pWalker->pParse;
834 sqlite3SelectPrep(sNC.pParse, p, &sNC);
835 sqlite3WalkSelect(pWalker, p);
836 }
837 }
838}
839
840/*
dan24fedb92018-08-18 17:35:38 +0000841** This is a Walker select callback. It does nothing. It is only required
842** because without a dummy callback, sqlite3WalkExpr() and similar do not
843** descend into sub-select statements.
844*/
dan987db762018-08-14 20:18:50 +0000845static int renameColumnSelectCb(Walker *pWalker, Select *p){
danea412512018-12-05 13:49:04 +0000846 renameWalkWith(pWalker, p);
dan987db762018-08-14 20:18:50 +0000847 return WRC_Continue;
848}
849
dan987db762018-08-14 20:18:50 +0000850/*
851** This is a Walker expression callback.
852**
853** For every TK_COLUMN node in the expression tree, search to see
854** if the column being references is the column being renamed by an
855** ALTER TABLE statement. If it is, then attach its associated
856** RenameToken object to the list of RenameToken objects being
857** constructed in RenameCtx object at pWalker->u.pRename.
858*/
dancf8f2892018-08-09 20:47:01 +0000859static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000860 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000861 if( pExpr->op==TK_TRIGGER
862 && pExpr->iColumn==p->iCol
863 && pWalker->pParse->pTriggerTab==p->pTab
864 ){
dan5be60c52018-08-15 20:28:39 +0000865 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000866 }else if( pExpr->op==TK_COLUMN
867 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000868 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000869 ){
dan5496d6a2018-08-13 17:14:26 +0000870 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000871 }
872 return WRC_Continue;
873}
874
dan987db762018-08-14 20:18:50 +0000875/*
876** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000877** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000878** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000879** RenameContext. "Last" means the last RenameToken encountered when
880** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000881** return all column name tokens in the order that they are encountered
882** in the SQL statement.
883*/
dan5496d6a2018-08-13 17:14:26 +0000884static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000885 RenameToken *pBest = pCtx->pList;
886 RenameToken *pToken;
887 RenameToken **pp;
888
889 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
890 if( pToken->t.z>pBest->t.z ) pBest = pToken;
891 }
892 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
893 *pp = pBest->pNext;
894
895 return pBest;
896}
897
dan6fe7f232018-08-10 19:19:33 +0000898/*
dan24fedb92018-08-18 17:35:38 +0000899** An error occured while parsing or otherwise processing a database
900** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
901** ALTER TABLE RENAME COLUMN program. The error message emitted by the
902** sub-routine is currently stored in pParse->zErrMsg. This function
903** adds context to the error message and then stores it in pCtx.
904*/
danb0137382018-08-20 20:01:01 +0000905static void renameColumnParseError(
906 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000907 int bPost,
danb0137382018-08-20 20:01:01 +0000908 sqlite3_value *pType,
909 sqlite3_value *pObject,
910 Parse *pParse
911){
drh79a5ee92018-08-23 19:32:04 +0000912 const char *zT = (const char*)sqlite3_value_text(pType);
913 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000914 char *zErr;
danb0137382018-08-20 20:01:01 +0000915
dan0d5fa6b2018-08-24 17:55:49 +0000916 zErr = sqlite3_mprintf("error in %s %s%s: %s",
917 zT, zN, (bPost ? " after rename" : ""),
918 pParse->zErrMsg
919 );
dan24fedb92018-08-18 17:35:38 +0000920 sqlite3_result_error(pCtx, zErr, -1);
921 sqlite3_free(zErr);
922}
923
924/*
dan06249392018-08-21 15:06:59 +0000925** For each name in the the expression-list pEList (i.e. each
926** pEList->a[i].zName) that matches the string in zOld, extract the
927** corresponding rename-token from Parse object pParse and add it
928** to the RenameCtx pCtx.
929*/
930static void renameColumnElistNames(
931 Parse *pParse,
932 RenameCtx *pCtx,
933 ExprList *pEList,
934 const char *zOld
935){
936 if( pEList ){
937 int i;
938 for(i=0; i<pEList->nExpr; i++){
939 char *zName = pEList->a[i].zName;
940 if( 0==sqlite3_stricmp(zName, zOld) ){
941 renameTokenFind(pParse, pCtx, (void*)zName);
942 }
943 }
944 }
945}
946
947/*
948** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
949** that matches the string in zOld, extract the corresponding rename-token
950** from Parse object pParse and add it to the RenameCtx pCtx.
951*/
952static void renameColumnIdlistNames(
953 Parse *pParse,
954 RenameCtx *pCtx,
955 IdList *pIdList,
956 const char *zOld
957){
958 if( pIdList ){
959 int i;
960 for(i=0; i<pIdList->nId; i++){
961 char *zName = pIdList->a[i].zName;
962 if( 0==sqlite3_stricmp(zName, zOld) ){
963 renameTokenFind(pParse, pCtx, (void*)zName);
964 }
965 }
966 }
967}
968
dandd1a9c82018-09-05 08:28:30 +0000969/*
970** Parse the SQL statement zSql using Parse object (*p). The Parse object
971** is initialized by this function before it is used.
972*/
danc9461ec2018-08-29 21:00:16 +0000973static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000974 Parse *p, /* Memory to use for Parse object */
975 const char *zDb, /* Name of schema SQL belongs to */
976 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
977 sqlite3 *db, /* Database handle */
978 const char *zSql, /* SQL to parse */
979 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000980){
981 int rc;
982 char *zErr = 0;
983
984 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
985
986 /* Parse the SQL statement passed as the first argument. If no error
987 ** occurs and the parse does not result in a new table, index or
988 ** trigger object, the database must be corrupt. */
989 memset(p, 0, sizeof(Parse));
990 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
991 p->db = db;
992 p->nQueryLoop = 1;
993 rc = sqlite3RunParser(p, zSql, &zErr);
994 assert( p->zErrMsg==0 );
995 assert( rc!=SQLITE_OK || zErr==0 );
danc9461ec2018-08-29 21:00:16 +0000996 p->zErrMsg = zErr;
997 if( db->mallocFailed ) rc = SQLITE_NOMEM;
998 if( rc==SQLITE_OK
999 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
1000 ){
1001 rc = SQLITE_CORRUPT_BKPT;
1002 }
1003
1004#ifdef SQLITE_DEBUG
1005 /* Ensure that all mappings in the Parse.pRename list really do map to
1006 ** a part of the input string. */
1007 if( rc==SQLITE_OK ){
1008 int nSql = sqlite3Strlen30(zSql);
1009 RenameToken *pToken;
1010 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
1011 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1012 }
1013 }
1014#endif
1015
1016 db->init.iDb = 0;
1017 return rc;
1018}
1019
dandd1a9c82018-09-05 08:28:30 +00001020/*
1021** This function edits SQL statement zSql, replacing each token identified
1022** by the linked list pRename with the text of zNew. If argument bQuote is
1023** true, then zNew is always quoted first. If no error occurs, the result
1024** is loaded into context object pCtx as the result.
1025**
1026** Or, if an error occurs (i.e. an OOM condition), an error is left in
1027** pCtx and an SQLite error code returned.
1028*/
danc9461ec2018-08-29 21:00:16 +00001029static int renameEditSql(
1030 sqlite3_context *pCtx, /* Return result here */
1031 RenameCtx *pRename, /* Rename context */
1032 const char *zSql, /* SQL statement to edit */
1033 const char *zNew, /* New token text */
1034 int bQuote /* True to always quote token */
1035){
1036 int nNew = sqlite3Strlen30(zNew);
1037 int nSql = sqlite3Strlen30(zSql);
1038 sqlite3 *db = sqlite3_context_db_handle(pCtx);
1039 int rc = SQLITE_OK;
1040 char *zQuot;
1041 char *zOut;
1042 int nQuot;
1043
1044 /* Set zQuot to point to a buffer containing a quoted copy of the
1045 ** identifier zNew. If the corresponding identifier in the original
1046 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1047 ** point to zQuot so that all substitutions are made using the
1048 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001049 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001050 if( zQuot==0 ){
1051 return SQLITE_NOMEM;
1052 }else{
1053 nQuot = sqlite3Strlen30(zQuot);
1054 }
1055 if( bQuote ){
1056 zNew = zQuot;
1057 nNew = nQuot;
1058 }
1059
1060 /* At this point pRename->pList contains a list of RenameToken objects
1061 ** corresponding to all tokens in the input SQL that must be replaced
1062 ** with the new column name. All that remains is to construct and
1063 ** return the edited SQL string. */
1064 assert( nQuot>=nNew );
1065 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1066 if( zOut ){
1067 int nOut = nSql;
1068 memcpy(zOut, zSql, nSql);
1069 while( pRename->pList ){
1070 int iOff; /* Offset of token to replace in zOut */
1071 RenameToken *pBest = renameColumnTokenNext(pRename);
1072
1073 u32 nReplace;
1074 const char *zReplace;
1075 if( sqlite3IsIdChar(*pBest->t.z) ){
1076 nReplace = nNew;
1077 zReplace = zNew;
1078 }else{
1079 nReplace = nQuot;
1080 zReplace = zQuot;
1081 }
1082
1083 iOff = pBest->t.z - zSql;
1084 if( pBest->t.n!=nReplace ){
1085 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1086 nOut - (iOff + pBest->t.n)
1087 );
1088 nOut += nReplace - pBest->t.n;
1089 zOut[nOut] = '\0';
1090 }
1091 memcpy(&zOut[iOff], zReplace, nReplace);
1092 sqlite3DbFree(db, pBest);
1093 }
1094
1095 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1096 sqlite3DbFree(db, zOut);
1097 }else{
1098 rc = SQLITE_NOMEM;
1099 }
1100
1101 sqlite3_free(zQuot);
1102 return rc;
1103}
1104
dandd1a9c82018-09-05 08:28:30 +00001105/*
1106** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1107** it was read from the schema of database zDb. Return SQLITE_OK if
1108** successful. Otherwise, return an SQLite error code and leave an error
1109** message in the Parse object.
1110*/
1111static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001112 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001113 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001114 TriggerStep *pStep;
1115 NameContext sNC;
1116 int rc = SQLITE_OK;
1117
1118 memset(&sNC, 0, sizeof(sNC));
1119 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001120 assert( pNew->pTabSchema );
1121 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1122 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1123 );
1124 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001125 /* ALWAYS() because if the table of the trigger does not exist, the
1126 ** error would have been hit before this point */
1127 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001128 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1129 }
danc9461ec2018-08-29 21:00:16 +00001130
1131 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001132 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001133 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001134 }
1135
dand5e6fef2018-09-07 15:50:31 +00001136 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001137 if( pStep->pSelect ){
1138 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1139 if( pParse->nErr ) rc = pParse->rc;
1140 }
dand5e6fef2018-09-07 15:50:31 +00001141 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001142 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1143 if( pTarget==0 ){
1144 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001145 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
dan0e14e982019-01-18 16:06:18 +00001146 SrcList sSrc;
danc9461ec2018-08-29 21:00:16 +00001147 memset(&sSrc, 0, sizeof(sSrc));
1148 sSrc.nSrc = 1;
1149 sSrc.a[0].zName = pStep->zTarget;
1150 sSrc.a[0].pTab = pTarget;
1151 sNC.pSrcList = &sSrc;
1152 if( pStep->pWhere ){
1153 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1154 }
1155 if( rc==SQLITE_OK ){
1156 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1157 }
1158 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1159 if( pStep->pUpsert ){
1160 Upsert *pUpsert = pStep->pUpsert;
1161 assert( rc==SQLITE_OK );
1162 pUpsert->pUpsertSrc = &sSrc;
1163 sNC.uNC.pUpsert = pUpsert;
1164 sNC.ncFlags = NC_UUpsert;
1165 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1166 if( rc==SQLITE_OK ){
1167 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1168 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1169 }
1170 if( rc==SQLITE_OK ){
1171 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1172 }
1173 if( rc==SQLITE_OK ){
1174 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1175 }
1176 sNC.ncFlags = 0;
1177 }
dan0e14e982019-01-18 16:06:18 +00001178 sNC.pSrcList = 0;
danc9461ec2018-08-29 21:00:16 +00001179 }
1180 }
1181 }
1182 return rc;
1183}
1184
dandd1a9c82018-09-05 08:28:30 +00001185/*
1186** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1187** objects that are part of the trigger passed as the second argument.
1188*/
danc9461ec2018-08-29 21:00:16 +00001189static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1190 TriggerStep *pStep;
1191
1192 /* Find tokens to edit in WHEN clause */
1193 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1194
1195 /* Find tokens to edit in trigger steps */
1196 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1197 sqlite3WalkSelect(pWalker, pStep->pSelect);
1198 sqlite3WalkExpr(pWalker, pStep->pWhere);
1199 sqlite3WalkExprList(pWalker, pStep->pExprList);
1200 if( pStep->pUpsert ){
1201 Upsert *pUpsert = pStep->pUpsert;
1202 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1203 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1204 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1205 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1206 }
1207 }
1208}
1209
dandd1a9c82018-09-05 08:28:30 +00001210/*
1211** Free the contents of Parse object (*pParse). Do not free the memory
1212** occupied by the Parse object itself.
1213*/
dan141e1192018-08-31 18:23:53 +00001214static void renameParseCleanup(Parse *pParse){
1215 sqlite3 *db = pParse->db;
drh885eeb62019-01-09 02:02:24 +00001216 Index *pIdx;
dan141e1192018-08-31 18:23:53 +00001217 if( pParse->pVdbe ){
1218 sqlite3VdbeFinalize(pParse->pVdbe);
1219 }
1220 sqlite3DeleteTable(db, pParse->pNewTable);
drh885eeb62019-01-09 02:02:24 +00001221 while( (pIdx = pParse->pNewIndex)!=0 ){
1222 pParse->pNewIndex = pIdx->pNext;
1223 sqlite3FreeIndex(db, pIdx);
1224 }
dan141e1192018-08-31 18:23:53 +00001225 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1226 sqlite3DbFree(db, pParse->zErrMsg);
1227 renameTokenFree(db, pParse->pRename);
1228 sqlite3ParserReset(pParse);
1229}
1230
dan06249392018-08-21 15:06:59 +00001231/*
dan987db762018-08-14 20:18:50 +00001232** SQL function:
1233**
1234** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1235**
1236** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001237** 1. type: Type of object ("table", "view" etc.)
1238** 2. object: Name of object
1239** 3. Database: Database name (e.g. "main")
1240** 4. Table: Table name
1241** 5. iCol: Index of column to rename
1242** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001243** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001244** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001245**
1246** Do a column rename operation on the CREATE statement given in zSql.
1247** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1248** into zNew. The name should be quoted if bQuote is true.
1249**
1250** This function is used internally by the ALTER TABLE RENAME COLUMN command.
drheea8eb62018-11-26 18:09:15 +00001251** It is only accessible to SQL created using sqlite3NestedParse(). It is
1252** not reachable from ordinary SQL passed into sqlite3_prepare().
dan6fe7f232018-08-10 19:19:33 +00001253*/
dancf8f2892018-08-09 20:47:01 +00001254static void renameColumnFunc(
1255 sqlite3_context *context,
1256 int NotUsed,
1257 sqlite3_value **argv
1258){
1259 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001260 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001261 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001262 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1263 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1264 int iCol = sqlite3_value_int(argv[5]);
1265 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001266 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001267 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001268 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001269 int rc;
dancf8f2892018-08-09 20:47:01 +00001270 Parse sParse;
1271 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001272 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001273 int i;
dan987db762018-08-14 20:18:50 +00001274 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001275#ifndef SQLITE_OMIT_AUTHORIZATION
1276 sqlite3_xauth xAuth = db->xAuth;
1277#endif
dancf8f2892018-08-09 20:47:01 +00001278
drh38d99642018-08-18 18:27:18 +00001279 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001280 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001281 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001282 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001283 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001284 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001285 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001286 if( pTab==0 || iCol>=pTab->nCol ){
1287 sqlite3BtreeLeaveAll(db);
1288 return;
1289 }
dan987db762018-08-14 20:18:50 +00001290 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001291 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001292 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001293
dan141e1192018-08-31 18:23:53 +00001294#ifndef SQLITE_OMIT_AUTHORIZATION
1295 db->xAuth = 0;
1296#endif
danc9461ec2018-08-29 21:00:16 +00001297 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001298
dancf8f2892018-08-09 20:47:01 +00001299 /* Find tokens that need to be replaced. */
1300 memset(&sWalker, 0, sizeof(Walker));
1301 sWalker.pParse = &sParse;
1302 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001303 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001304 sWalker.u.pRename = &sCtx;
1305
dan0cbb0b12018-08-16 19:49:16 +00001306 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001307 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001308 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001309 Select *pSelect = sParse.pNewTable->pSelect;
1310 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001311 sParse.rc = SQLITE_OK;
1312 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1313 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1314 if( rc==SQLITE_OK ){
1315 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001316 }
dan987db762018-08-14 20:18:50 +00001317 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1318 }else{
1319 /* A regular table */
1320 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1321 FKey *pFKey;
1322 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001323 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001324 if( bFKOnly==0 ){
1325 renameTokenFind(
1326 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1327 );
1328 if( sCtx.iCol<0 ){
1329 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001330 }
dan987db762018-08-14 20:18:50 +00001331 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1332 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1333 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1334 }
drh885eeb62019-01-09 02:02:24 +00001335 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
1336 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1337 }
dan987db762018-08-14 20:18:50 +00001338 }
drhb9bcf7c2019-10-19 13:29:10 +00001339#ifndef SQLITE_OMIT_GENERATED_COLUMNS
1340 for(i=0; i<sParse.pNewTable->nCol; i++){
1341 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt);
1342 }
1343#endif
dan987db762018-08-14 20:18:50 +00001344
1345 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1346 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001347 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001348 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1349 }
1350 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1351 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1352 ){
1353 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1354 }
dan6fe7f232018-08-10 19:19:33 +00001355 }
dancf8f2892018-08-09 20:47:01 +00001356 }
1357 }
dan5496d6a2018-08-13 17:14:26 +00001358 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001359 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1360 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001361 }else{
dan5be60c52018-08-15 20:28:39 +00001362 /* A trigger */
1363 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001364 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001365 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001366
danc9461ec2018-08-29 21:00:16 +00001367 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1368 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001369 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001370 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001371 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001372 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1373 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001374 }
danc9461ec2018-08-29 21:00:16 +00001375 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1376 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001377 }
1378 }
1379 }
1380
dan5be60c52018-08-15 20:28:39 +00001381
1382 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001383 if( sParse.pTriggerTab==pTab ){
1384 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001385 }
dan5be60c52018-08-15 20:28:39 +00001386
danc9461ec2018-08-29 21:00:16 +00001387 /* Find tokens to edit in various expressions and selects */
1388 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001389 }
1390
dan987db762018-08-14 20:18:50 +00001391 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001392 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001393
drh5fc22cd2018-08-13 13:43:11 +00001394renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001395 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001396 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001397 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001398 }else{
1399 sqlite3_result_error_code(context, rc);
1400 }
1401 }
1402
dan141e1192018-08-31 18:23:53 +00001403 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001404 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001405#ifndef SQLITE_OMIT_AUTHORIZATION
1406 db->xAuth = xAuth;
1407#endif
drhda76adc2018-08-25 02:04:05 +00001408 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001409}
1410
dandd1a9c82018-09-05 08:28:30 +00001411/*
1412** Walker expression callback used by "RENAME TABLE".
1413*/
danc9461ec2018-08-29 21:00:16 +00001414static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1415 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001416 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1417 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001418 }
1419 return WRC_Continue;
1420}
1421
1422/*
dandd1a9c82018-09-05 08:28:30 +00001423** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001424*/
1425static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1426 int i;
1427 RenameCtx *p = pWalker->u.pRename;
1428 SrcList *pSrc = pSelect->pSrc;
drh92a28242019-10-09 15:37:58 +00001429 if( pSrc==0 ){
1430 assert( pWalker->pParse->db->mallocFailed );
drh974b2482018-12-06 01:53:12 +00001431 return WRC_Abort;
1432 }
danc9461ec2018-08-29 21:00:16 +00001433 for(i=0; i<pSrc->nSrc; i++){
1434 struct SrcList_item *pItem = &pSrc->a[i];
1435 if( pItem->pTab==p->pTab ){
1436 renameTokenFind(pWalker->pParse, p, pItem->zName);
1437 }
1438 }
danea412512018-12-05 13:49:04 +00001439 renameWalkWith(pWalker, pSelect);
danc9461ec2018-08-29 21:00:16 +00001440
1441 return WRC_Continue;
1442}
1443
1444
1445/*
1446** This C function implements an SQL user function that is used by SQL code
1447** generated by the ALTER TABLE ... RENAME command to modify the definition
1448** of any foreign key constraints that use the table being renamed as the
1449** parent table. It is passed three arguments:
1450**
dan141e1192018-08-31 18:23:53 +00001451** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001452** 1. type: Type of object ("table", "view" etc.)
1453** 2. object: Name of object
1454** 3: The complete text of the schema statement being modified,
1455** 4: The old name of the table being renamed, and
1456** 5: The new name of the table being renamed.
1457** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001458**
dan141e1192018-08-31 18:23:53 +00001459** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001460**
dan141e1192018-08-31 18:23:53 +00001461** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001462** -> 'CREATE TABLE t1(a REFERENCES t3)'
1463*/
1464static void renameTableFunc(
1465 sqlite3_context *context,
1466 int NotUsed,
1467 sqlite3_value **argv
1468){
1469 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001470 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001471 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1472 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1473 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1474 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001475 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001476
dan141e1192018-08-31 18:23:53 +00001477 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001478 Parse sParse;
1479 int rc;
1480 int bQuote = 1;
1481 RenameCtx sCtx;
1482 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001483
dan141e1192018-08-31 18:23:53 +00001484#ifndef SQLITE_OMIT_AUTHORIZATION
1485 sqlite3_xauth xAuth = db->xAuth;
1486 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001487#endif
1488
dan141e1192018-08-31 18:23:53 +00001489 sqlite3BtreeEnterAll(db);
1490
1491 memset(&sCtx, 0, sizeof(RenameCtx));
1492 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1493 memset(&sWalker, 0, sizeof(Walker));
1494 sWalker.pParse = &sParse;
1495 sWalker.xExprCallback = renameTableExprCb;
1496 sWalker.xSelectCallback = renameTableSelectCb;
1497 sWalker.u.pRename = &sCtx;
1498
1499 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1500
1501 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001502 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001503 if( sParse.pNewTable ){
1504 Table *pTab = sParse.pNewTable;
1505
1506 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001507 if( isLegacy==0 ){
1508 NameContext sNC;
1509 memset(&sNC, 0, sizeof(sNC));
1510 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001511
dan674b8942018-09-20 08:28:01 +00001512 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1513 if( sParse.nErr ) rc = sParse.rc;
1514 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1515 }
dan141e1192018-08-31 18:23:53 +00001516 }else{
1517 /* Modify any FK definitions to point to the new table. */
1518#ifndef SQLITE_OMIT_FOREIGN_KEY
danb4307012018-11-09 20:04:05 +00001519 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){
dan202a0272018-09-07 11:51:21 +00001520 FKey *pFKey;
1521 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1522 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1523 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1524 }
dan141e1192018-08-31 18:23:53 +00001525 }
1526 }
1527#endif
1528
1529 /* If this is the table being altered, fix any table refs in CHECK
1530 ** expressions. Also update the name that appears right after the
1531 ** "CREATE [VIRTUAL] TABLE" bit. */
1532 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1533 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001534 if( isLegacy==0 ){
1535 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1536 }
dan141e1192018-08-31 18:23:53 +00001537 renameTokenFind(&sParse, &sCtx, pTab->zName);
1538 }
danc9461ec2018-08-29 21:00:16 +00001539 }
1540 }
danc9461ec2018-08-29 21:00:16 +00001541
dan141e1192018-08-31 18:23:53 +00001542 else if( sParse.pNewIndex ){
1543 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001544 if( isLegacy==0 ){
1545 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1546 }
dan141e1192018-08-31 18:23:53 +00001547 }
danc9461ec2018-08-29 21:00:16 +00001548
1549#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001550 else{
dan141e1192018-08-31 18:23:53 +00001551 Trigger *pTrigger = sParse.pNewTrigger;
1552 TriggerStep *pStep;
1553 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1554 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1555 ){
1556 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1557 }
danc9461ec2018-08-29 21:00:16 +00001558
dan674b8942018-09-20 08:28:01 +00001559 if( isLegacy==0 ){
1560 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1561 if( rc==SQLITE_OK ){
1562 renameWalkTrigger(&sWalker, pTrigger);
1563 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1564 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1565 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1566 }
dan141e1192018-08-31 18:23:53 +00001567 }
dan0ccda962018-08-30 16:26:48 +00001568 }
danc9461ec2018-08-29 21:00:16 +00001569 }
1570 }
dan141e1192018-08-31 18:23:53 +00001571#endif
danc9461ec2018-08-29 21:00:16 +00001572 }
dan141e1192018-08-31 18:23:53 +00001573
1574 if( rc==SQLITE_OK ){
1575 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1576 }
1577 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001578 if( sParse.zErrMsg ){
1579 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1580 }else{
1581 sqlite3_result_error_code(context, rc);
1582 }
dan141e1192018-08-31 18:23:53 +00001583 }
1584
1585 renameParseCleanup(&sParse);
1586 renameTokenFree(db, sCtx.pList);
1587 sqlite3BtreeLeaveAll(db);
1588#ifndef SQLITE_OMIT_AUTHORIZATION
1589 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001590#endif
1591 }
1592
danc9461ec2018-08-29 21:00:16 +00001593 return;
1594}
1595
dandd1a9c82018-09-05 08:28:30 +00001596/*
1597** An SQL user function that checks that there are no parse or symbol
1598** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1599** After an ALTER TABLE .. RENAME operation is performed and the schema
1600** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001601** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001602**
1603** 0: Database name ("main", "temp" etc.).
1604** 1: SQL statement.
1605** 2: Object type ("view", "table", "trigger" or "index").
1606** 3: Object name.
1607** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001608**
1609** Unless it finds an error, this function normally returns NULL. However, it
1610** returns integer value 1 if:
1611**
1612** * the SQL argument creates a trigger, and
1613** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001614*/
dan9d324822018-08-30 20:03:44 +00001615static void renameTableTest(
1616 sqlite3_context *context,
1617 int NotUsed,
1618 sqlite3_value **argv
1619){
1620 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001621 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1622 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001623 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001624 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001625
dan141e1192018-08-31 18:23:53 +00001626#ifndef SQLITE_OMIT_AUTHORIZATION
1627 sqlite3_xauth xAuth = db->xAuth;
1628 db->xAuth = 0;
1629#endif
1630
drh5b1da302018-09-01 20:02:07 +00001631 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001632 if( zDb && zInput ){
1633 int rc;
1634 Parse sParse;
1635 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1636 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001637 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001638 NameContext sNC;
1639 memset(&sNC, 0, sizeof(sNC));
1640 sNC.pParse = &sParse;
1641 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1642 if( sParse.nErr ) rc = sParse.rc;
1643 }
1644
1645 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001646 if( isLegacy==0 ){
1647 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1648 }
drh3b700452018-09-07 19:12:08 +00001649 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001650 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1651 int i2 = sqlite3FindDbName(db, zDb);
1652 if( i1==i2 ) sqlite3_result_int(context, 1);
1653 }
dan09236502018-09-01 16:05:50 +00001654 }
dan9d324822018-08-30 20:03:44 +00001655 }
1656
dan09236502018-09-01 16:05:50 +00001657 if( rc!=SQLITE_OK ){
1658 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001659 }
dan09236502018-09-01 16:05:50 +00001660 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001661 }
1662
dan141e1192018-08-31 18:23:53 +00001663#ifndef SQLITE_OMIT_AUTHORIZATION
1664 db->xAuth = xAuth;
1665#endif
dan9d324822018-08-30 20:03:44 +00001666}
1667
dancf8f2892018-08-09 20:47:01 +00001668/*
1669** Register built-in functions used to help implement ALTER TABLE
1670*/
1671void sqlite3AlterFunctions(void){
1672 static FuncDef aAlterTableFuncs[] = {
drheea8eb62018-11-26 18:09:15 +00001673 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc),
1674 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc),
1675 INTERNAL_FUNCTION(sqlite_rename_test, 5, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001676 };
1677 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1678}
drhd0e4a6c2005-02-15 20:47:57 +00001679#endif /* SQLITE_ALTER_TABLE */