blob: c02e730b6410be71c283e8b32701857212e98607 [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*/
31static int isSystemTable(Parse *pParse, const char *zName){
drh59a386e2017-06-28 01:12:53 +000032 if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danbe535002011-04-01 15:15:58 +000033 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
34 return 1;
35 }
36 return 0;
37}
38
dan09236502018-09-01 16:05:50 +000039/*
40** Generate code to verify that the schemas of database zDb and, if
41** bTemp is not true, database "temp", can still be parsed. This is
42** called at the end of the generation of an ALTER TABLE ... RENAME ...
43** statement to ensure that the operation has not rendered any schema
44** objects unusable.
45*/
drh16b870d2018-09-12 15:51:56 +000046static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
dan9d324822018-08-30 20:03:44 +000047 sqlite3NestedParse(pParse,
48 "SELECT 1 "
49 "FROM \"%w\".%s "
50 "WHERE name NOT LIKE 'sqlite_%%'"
51 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000052 " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
dan9d324822018-08-30 20:03:44 +000053 zDb, MASTER_NAME,
54 zDb, bTemp
55 );
56
57 if( bTemp==0 ){
58 sqlite3NestedParse(pParse,
59 "SELECT 1 "
60 "FROM temp.%s "
61 "WHERE name NOT LIKE 'sqlite_%%'"
62 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000063 " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
dan9d324822018-08-30 20:03:44 +000064 MASTER_NAME, zDb
65 );
66 }
67}
68
danbe535002011-04-01 15:15:58 +000069/*
dan09236502018-09-01 16:05:50 +000070** Generate code to reload the schema for database iDb. And, if iDb!=1, for
71** the temp database as well.
72*/
drh16b870d2018-09-12 15:51:56 +000073static void renameReloadSchema(Parse *pParse, int iDb){
dan09236502018-09-01 16:05:50 +000074 Vdbe *v = pParse->pVdbe;
75 if( v ){
76 sqlite3ChangeCookie(pParse, iDb);
77 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
78 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
79 }
80}
81
82/*
drhd0e4a6c2005-02-15 20:47:57 +000083** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
84** command.
85*/
86void sqlite3AlterRenameTable(
87 Parse *pParse, /* Parser context. */
88 SrcList *pSrc, /* The table to rename. */
89 Token *pName /* The new table name. */
90){
91 int iDb; /* Database that contains the table */
92 char *zDb; /* Name of database iDb */
93 Table *pTab; /* Table being renamed */
94 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +000095 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +000096 int nTabName; /* Number of UTF-8 characters in zTabName */
97 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +000098 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +000099 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000100 u32 savedDbFlags; /* Saved value of db->mDbFlags */
danc07a7052018-10-06 14:33:41 +0000101#ifndef SQLITE_OMIT_AUTHORIZATION
102 sqlite3_xauth xAuth = db->xAuth;
103#endif
drh545f5872010-04-24 14:02:59 +0000104
drh8257aa82017-07-26 19:59:13 +0000105 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000106 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000107 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000108 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000109
dan41fb5cd2012-10-04 19:33:00 +0000110 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000111 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000112 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000113 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000114 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000115
116 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000117 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000118 if( !zName ) goto exit_rename_table;
119
120 /* Check that a table or index named 'zName' does not already exist
121 ** in database iDb. If so, this is an error.
122 */
123 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
124 sqlite3ErrorMsg(pParse,
125 "there is already another table or index with this name: %s", zName);
126 goto exit_rename_table;
127 }
128
129 /* Make sure it is not a system table being altered, or a reserved name
130 ** that the table is being renamed to.
131 */
danbe535002011-04-01 15:15:58 +0000132 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
drhd0e4a6c2005-02-15 20:47:57 +0000133 goto exit_rename_table;
134 }
danbe535002011-04-01 15:15:58 +0000135 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
136 exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000137 }
138
danielk197761116ae2007-12-13 08:15:30 +0000139#ifndef SQLITE_OMIT_VIEW
140 if( pTab->pSelect ){
141 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
142 goto exit_rename_table;
143 }
144#endif
145
drhd0e4a6c2005-02-15 20:47:57 +0000146#ifndef SQLITE_OMIT_AUTHORIZATION
147 /* Invoke the authorization callback. */
148 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
149 goto exit_rename_table;
150 }
danc07a7052018-10-06 14:33:41 +0000151 db->xAuth = 0;
drhd0e4a6c2005-02-15 20:47:57 +0000152#endif
153
danielk1977182c4ba2007-06-27 15:53:34 +0000154#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000155 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
156 goto exit_rename_table;
157 }
danielk1977595a5232009-07-24 17:58:53 +0000158 if( IsVirtual(pTab) ){
159 pVTab = sqlite3GetVTable(db, pTab);
160 if( pVTab->pVtab->pModule->xRename==0 ){
161 pVTab = 0;
162 }
danielk1977182c4ba2007-06-27 15:53:34 +0000163 }
164#endif
165
drhb22f7c82014-02-06 23:56:27 +0000166 /* Begin a transaction for database iDb.
drhd0e4a6c2005-02-15 20:47:57 +0000167 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000168 ** schema). Open a statement transaction if the table is a virtual
169 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000170 */
171 v = sqlite3GetVdbe(pParse);
172 if( v==0 ){
173 goto exit_rename_table;
174 }
drhd0e4a6c2005-02-15 20:47:57 +0000175
drh4e5dd852007-05-15 03:56:49 +0000176 /* figure out how many UTF-8 characters are in zName */
177 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000178 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000179
danc9461ec2018-08-29 21:00:16 +0000180 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
181 ** the schema to use the new table name. */
182 sqlite3NestedParse(pParse,
183 "UPDATE \"%w\".%s SET "
dan65372fa2018-09-03 20:05:15 +0000184 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000185 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
186 "AND name NOT LIKE 'sqlite_%%'"
dan0ccda962018-08-30 16:26:48 +0000187 , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000188 );
dan432cc5b2009-09-26 17:51:48 +0000189
danc9461ec2018-08-29 21:00:16 +0000190 /* Update the tbl_name and name columns of the sqlite_master table
191 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000192 sqlite3NestedParse(pParse,
193 "UPDATE %Q.%s SET "
drhd0e4a6c2005-02-15 20:47:57 +0000194 "tbl_name = %Q, "
195 "name = CASE "
196 "WHEN type='table' THEN %Q "
197 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000198 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000199 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000200 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000201 "(type='table' OR type='index' OR type='trigger');",
danc9461ec2018-08-29 21:00:16 +0000202 zDb, MASTER_NAME,
203 zName, zName, zName,
204 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000205 );
206
207#ifndef SQLITE_OMIT_AUTOINCREMENT
208 /* If the sqlite_sequence table exists in this database, then update
209 ** it with the new table name.
210 */
211 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
212 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000213 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000214 zDb, zName, pTab->zName);
215 }
216#endif
217
danc9461ec2018-08-29 21:00:16 +0000218 /* If the table being renamed is not itself part of the temp database,
219 ** edit view and trigger definitions within the temp database
220 ** as required. */
221 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000222 sqlite3NestedParse(pParse,
223 "UPDATE sqlite_temp_master SET "
dan65372fa2018-09-03 20:05:15 +0000224 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000225 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000226 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
227 " sqlite_rename_test(%Q, sql, type, name, 1) "
228 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000229 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000230 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000231 }
drhd0e4a6c2005-02-15 20:47:57 +0000232
dan34566c42018-09-20 17:21:21 +0000233 /* If this is a virtual table, invoke the xRename() function if
234 ** one is defined. The xRename() callback will modify the names
235 ** of any resources used by the v-table implementation (including other
236 ** SQLite tables) that are identified by the name of the virtual table.
237 */
238#ifndef SQLITE_OMIT_VIRTUALTABLE
239 if( pVTab ){
240 int i = ++pParse->nMem;
241 sqlite3VdbeLoadString(v, i, zName);
242 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
243 sqlite3MayAbort(pParse);
244 }
245#endif
246
dan09236502018-09-01 16:05:50 +0000247 renameReloadSchema(pParse, iDb);
dan9d324822018-08-30 20:03:44 +0000248 renameTestSchema(pParse, zDb, iDb==1);
249
drhd0e4a6c2005-02-15 20:47:57 +0000250exit_rename_table:
danc07a7052018-10-06 14:33:41 +0000251#ifndef SQLITE_OMIT_AUTHORIZATION
252 db->xAuth = xAuth;
253#endif
drh633e6d52008-07-28 19:34:53 +0000254 sqlite3SrcListDelete(db, pSrc);
255 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000256 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000257}
danielk197719a8e7e2005-03-17 05:03:38 +0000258
drhd3001712009-05-12 17:46:53 +0000259/*
danielk197719a8e7e2005-03-17 05:03:38 +0000260** This function is called after an "ALTER TABLE ... ADD" statement
261** has been parsed. Argument pColDef contains the text of the new
262** column definition.
263**
264** The Table structure pParse->pNewTable was extended to include
265** the new column during parsing.
266*/
267void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
268 Table *pNew; /* Copy of pParse->pNewTable */
269 Table *pTab; /* Table being altered */
270 int iDb; /* Database number */
271 const char *zDb; /* Database name */
272 const char *zTab; /* Table name */
273 char *zCol; /* Null-terminated column definition */
274 Column *pCol; /* The new column */
275 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000276 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000277 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000278 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000279
danielk1977f150c9d2008-10-30 17:21:12 +0000280 db = pParse->db;
281 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000282 pNew = pParse->pNewTable;
283 assert( pNew );
284
drh1fee73e2007-08-29 04:00:57 +0000285 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000286 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000287 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000288 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000289 pCol = &pNew->aCol[pNew->nCol-1];
290 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000291 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000292 assert( pTab );
293
drh81f2ccd2006-01-31 14:28:44 +0000294#ifndef SQLITE_OMIT_AUTHORIZATION
295 /* Invoke the authorization callback. */
296 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
297 return;
298 }
299#endif
300
danielk197719a8e7e2005-03-17 05:03:38 +0000301 /* If the default value for the new column was specified with a
302 ** literal NULL, then set pDflt to 0. This simplifies checking
303 ** for an SQL NULL default below.
304 */
drh94fa9c42016-02-27 21:16:04 +0000305 assert( pDflt==0 || pDflt->op==TK_SPAN );
306 if( pDflt && pDflt->pLeft->op==TK_NULL ){
danielk197719a8e7e2005-03-17 05:03:38 +0000307 pDflt = 0;
308 }
309
310 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
311 ** If there is a NOT NULL constraint, then the default value for the
312 ** column must not be NULL.
313 */
drha371ace2012-09-13 14:22:47 +0000314 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000315 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
316 return;
317 }
318 if( pNew->pIndex ){
319 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
320 return;
321 }
dan53c3fa82009-09-25 11:26:54 +0000322 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 }
danielk197719a8e7e2005-03-17 05:03:38 +0000327 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 ){
dan7a419232013-08-06 20:01:43 +0000337 sqlite3_value *pVal = 0;
drh96f4ad22015-03-12 21:02:36 +0000338 int rc;
drh05883a32015-06-02 15:32:08 +0000339 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
drh96f4ad22015-03-12 21:02:36 +0000340 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
341 if( rc!=SQLITE_OK ){
pdrbb3da062016-02-06 14:14:43 +0000342 assert( db->mallocFailed == 1 );
danielk197719a8e7e2005-03-17 05:03:38 +0000343 return;
344 }
345 if( !pVal ){
346 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
347 return;
348 }
349 sqlite3ValueFree(pVal);
350 }
351
352 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000353 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000354 if( zCol ){
355 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000356 u32 savedDbFlags = db->mDbFlags;
danc07a7052018-10-06 14:33:41 +0000357#ifndef SQLITE_OMIT_AUTHORIZATION
358 sqlite3_xauth xAuth = db->xAuth;
359 db->xAuth = 0;
360#endif
drh56d56f72009-04-16 16:30:17 +0000361 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000362 *zEnd-- = '\0';
363 }
drh8257aa82017-07-26 19:59:13 +0000364 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000365 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000366 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000367 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000368 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000369 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000370 zTab
371 );
drh633e6d52008-07-28 19:34:53 +0000372 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000373 db->mDbFlags = savedDbFlags;
danc07a7052018-10-06 14:33:41 +0000374#ifndef SQLITE_OMIT_AUTHORIZATION
375 db->xAuth = xAuth;
376#endif
danielk197719a8e7e2005-03-17 05:03:38 +0000377 }
378
drh86396212016-07-14 19:13:11 +0000379 /* Make sure the schema version is at least 3. But do not upgrade
380 ** from less than 3 to 4, as that will corrupt any preexisting DESC
381 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000382 */
dan09236502018-09-01 16:05:50 +0000383 v = sqlite3GetVdbe(pParse);
384 if( v ){
385 r1 = sqlite3GetTempReg(pParse);
386 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
387 sqlite3VdbeUsesBtree(v, iDb);
388 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
389 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
390 VdbeCoverage(v);
391 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
392 sqlite3ReleaseTempReg(pParse, r1);
393 }
danielk197719a8e7e2005-03-17 05:03:38 +0000394
dan09236502018-09-01 16:05:50 +0000395 /* Reload the table definition */
396 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000397}
398
drhfdd6e852005-12-16 01:06:16 +0000399/*
danielk197719a8e7e2005-03-17 05:03:38 +0000400** This function is called by the parser after the table-name in
401** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
402** pSrc is the full-name of the table being altered.
403**
404** This routine makes a (partial) copy of the Table structure
405** for the table being altered and sets Parse.pNewTable to point
406** to it. Routines called by the parser as the column definition
407** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
408** the copy. The copy of the Table structure is deleted by tokenize.c
409** after parsing is finished.
410**
411** Routine sqlite3AlterFinishAddColumn() will be called to complete
412** coding the "ALTER TABLE ... ADD" statement.
413*/
414void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
415 Table *pNew;
416 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000417 int iDb;
418 int i;
419 int nAlloc;
drh17435752007-08-16 04:30:38 +0000420 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000421
422 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000423 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000424 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000425 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000426 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000427 if( !pTab ) goto exit_begin_add_column;
428
danielk19775ee9d692006-06-21 12:36:25 +0000429#ifndef SQLITE_OMIT_VIRTUALTABLE
430 if( IsVirtual(pTab) ){
431 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
432 goto exit_begin_add_column;
433 }
434#endif
435
danielk197719a8e7e2005-03-17 05:03:38 +0000436 /* Make sure this is not an attempt to ALTER a view. */
437 if( pTab->pSelect ){
438 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
439 goto exit_begin_add_column;
440 }
danbe535002011-04-01 15:15:58 +0000441 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
442 goto exit_begin_add_column;
443 }
danielk197719a8e7e2005-03-17 05:03:38 +0000444
445 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000446 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000447
448 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000449 ** sqlite3AddColumn() function and friends to modify. But modify
450 ** the name by adding an "sqlite_altertab_" prefix. By adding this
451 ** prefix, we insure that the name will not collide with an existing
452 ** table because user table are not allowed to have the "sqlite_"
453 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000454 */
drh17435752007-08-16 04:30:38 +0000455 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000456 if( !pNew ) goto exit_begin_add_column;
457 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000458 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000459 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000460 assert( pNew->nCol>0 );
461 nAlloc = (((pNew->nCol-1)/8)*8)+8;
462 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000463 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000464 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000465 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000466 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000467 goto exit_begin_add_column;
468 }
469 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
470 for(i=0; i<pNew->nCol; i++){
471 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000472 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000473 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000474 pCol->pDflt = 0;
475 }
drh17435752007-08-16 04:30:38 +0000476 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000477 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000478 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000479
danielk197719a8e7e2005-03-17 05:03:38 +0000480exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000481 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000482 return;
483}
dancf8f2892018-08-09 20:47:01 +0000484
drh4a2c7472018-08-13 15:09:48 +0000485/*
dan9d705572018-08-20 16:16:05 +0000486** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
487** command. This function checks if the table is a view or virtual
488** table (columns of views or virtual tables may not be renamed). If so,
489** it loads an error message into pParse and returns non-zero.
490**
491** Or, if pTab is not a view or virtual table, zero is returned.
492*/
493#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
494static int isRealTable(Parse *pParse, Table *pTab){
495 const char *zType = 0;
496#ifndef SQLITE_OMIT_VIEW
497 if( pTab->pSelect ){
498 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000499 }
dan9d705572018-08-20 16:16:05 +0000500#endif
501#ifndef SQLITE_OMIT_VIRTUALTABLE
502 if( IsVirtual(pTab) ){
503 zType = "virtual table";
504 }
505#endif
506 if( zType ){
507 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000508 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000509 );
510 return 1;
511 }
512 return 0;
513}
514#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
515# define isRealTable(x,y) (0)
516#endif
517
518/*
drh4a2c7472018-08-13 15:09:48 +0000519** Handles the following parser reduction:
520**
521** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
522*/
dancf8f2892018-08-09 20:47:01 +0000523void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000524 Parse *pParse, /* Parsing context */
525 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
526 Token *pOld, /* Name of column being changed */
527 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000528){
drh4a2c7472018-08-13 15:09:48 +0000529 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000530 Table *pTab; /* Table being updated */
531 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000532 char *zOld = 0; /* Old column name */
533 char *zNew = 0; /* New column name */
534 const char *zDb; /* Name of schema containing the table */
535 int iSchema; /* Index of the schema */
536 int bQuote; /* True to quote the new name */
danc07a7052018-10-06 14:33:41 +0000537#ifndef SQLITE_OMIT_AUTHORIZATION
538 sqlite3_xauth xAuth = db->xAuth;
539#endif
dancf8f2892018-08-09 20:47:01 +0000540
drh4a2c7472018-08-13 15:09:48 +0000541 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000542 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
543 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000544
545 /* Cannot alter a system table */
dan872165f2018-08-11 17:34:38 +0000546 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000547 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000548
549 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000550 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
551 assert( iSchema>=0 );
552 zDb = db->aDb[iSchema].zDbSName;
553
drh0d019b92018-08-25 16:14:46 +0000554#ifndef SQLITE_OMIT_AUTHORIZATION
555 /* Invoke the authorization callback. */
556 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
557 goto exit_rename_column;
558 }
danc07a7052018-10-06 14:33:41 +0000559 db->xAuth = 0;
drh0d019b92018-08-25 16:14:46 +0000560#endif
561
drh4a2c7472018-08-13 15:09:48 +0000562 /* Make sure the old name really is a column name in the table to be
563 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000564 zOld = sqlite3NameFromToken(db, pOld);
565 if( !zOld ) goto exit_rename_column;
566 for(iCol=0; iCol<pTab->nCol; iCol++){
567 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
568 }
569 if( iCol==pTab->nCol ){
570 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
571 goto exit_rename_column;
572 }
573
drh4a2c7472018-08-13 15:09:48 +0000574 /* Do the rename operation using a recursive UPDATE statement that
575 ** uses the sqlite_rename_column() SQL function to compute the new
576 ** CREATE statement text for the sqlite_master table.
577 */
dancf8f2892018-08-09 20:47:01 +0000578 zNew = sqlite3NameFromToken(db, pNew);
579 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000580 assert( pNew->n>0 );
581 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000582 sqlite3NestedParse(pParse,
583 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000584 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan499b8252018-08-17 18:08:28 +0000585 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
586 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000587 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000588 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000589 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000590 );
591
dan9d324822018-08-30 20:03:44 +0000592 sqlite3NestedParse(pParse,
593 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000594 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000595 "WHERE type IN ('trigger', 'view')",
596 MASTER_NAME,
597 zDb, pTab->zName, iCol, zNew, bQuote
598 );
599
dane325ffe2018-08-11 13:40:20 +0000600 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000601 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000602 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000603
dancf8f2892018-08-09 20:47:01 +0000604 exit_rename_column:
danc07a7052018-10-06 14:33:41 +0000605#ifndef SQLITE_OMIT_AUTHORIZATION
606 db->xAuth = xAuth;
607#endif
dancf8f2892018-08-09 20:47:01 +0000608 sqlite3SrcListDelete(db, pSrc);
609 sqlite3DbFree(db, zOld);
610 sqlite3DbFree(db, zNew);
611 return;
612}
613
drh4a2c7472018-08-13 15:09:48 +0000614/*
615** Each RenameToken object maps an element of the parse tree into
616** the token that generated that element. The parse tree element
617** might be one of:
618**
619** * A pointer to an Expr that represents an ID
620** * The name of a table column in Column.zName
621**
622** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000623** Each new object is created by sqlite3RenameTokenMap().
624** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000625** routine is used to keep the mapping current.
626**
627** After the parse finishes, renameTokenFind() routine can be used
628** to look up the actual token value that created some element in
629** the parse tree.
630*/
dancf8f2892018-08-09 20:47:01 +0000631struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000632 void *p; /* Parse tree element created by token t */
633 Token t; /* The token that created parse tree element p */
634 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000635};
636
drh4a2c7472018-08-13 15:09:48 +0000637/*
638** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
639** down into the Walker.
640*/
dan5496d6a2018-08-13 17:14:26 +0000641typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000642struct RenameCtx {
643 RenameToken *pList; /* List of tokens to overwrite */
644 int nList; /* Number of tokens in pList */
645 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000646 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000647 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000648};
649
dan8900a482018-09-05 14:36:05 +0000650#ifdef SQLITE_DEBUG
651/*
652** This function is only for debugging. It performs two tasks:
653**
654** 1. Checks that pointer pPtr does not already appear in the
655** rename-token list.
656**
657** 2. Dereferences each pointer in the rename-token list.
658**
659** The second is most effective when debugging under valgrind or
660** address-sanitizer or similar. If any of these pointers no longer
661** point to valid objects, an exception is raised by the memory-checking
662** tool.
663**
664** The point of this is to prevent comparisons of invalid pointer values.
665** Even though this always seems to work, it is undefined according to the
666** C standard. Example of undefined comparison:
667**
668** sqlite3_free(x);
669** if( x==y ) ...
670**
671** Technically, as x no longer points into a valid object or to the byte
672** following a valid object, it may not be used in comparison operations.
673*/
drh16b870d2018-09-12 15:51:56 +0000674static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000675 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
676 RenameToken *p;
677 u8 i = 0;
678 for(p=pParse->pRename; p; p=p->pNext){
679 if( p->p ){
680 assert( p->p!=pPtr );
681 i += *(u8*)(p->p);
682 }
danc9461ec2018-08-29 21:00:16 +0000683 }
684 }
685}
dan8900a482018-09-05 14:36:05 +0000686#else
687# define renameTokenCheckAll(x,y)
688#endif
danc9461ec2018-08-29 21:00:16 +0000689
drh4a2c7472018-08-13 15:09:48 +0000690/*
691** Add a new RenameToken object mapping parse tree element pPtr into
692** token *pToken to the Parse object currently under construction.
dan07e95232018-08-21 16:32:53 +0000693**
694** Return a copy of pPtr.
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/*
737** Remove all nodes that are part of expression pExpr from the rename list.
738*/
739void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
740 Walker sWalker;
741 memset(&sWalker, 0, sizeof(Walker));
742 sWalker.pParse = pParse;
743 sWalker.xExprCallback = renameUnmapExprCb;
744 sqlite3WalkExpr(&sWalker, pExpr);
745}
746
747/*
dane8ab40d2018-09-12 08:51:48 +0000748** Remove all nodes that are part of expression-list pEList from the
749** rename list.
750*/
751void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
752 if( pEList ){
753 int i;
754 Walker sWalker;
755 memset(&sWalker, 0, sizeof(Walker));
756 sWalker.pParse = pParse;
757 sWalker.xExprCallback = renameUnmapExprCb;
758 sqlite3WalkExprList(&sWalker, pEList);
759 for(i=0; i<pEList->nExpr; i++){
760 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
761 }
762 }
763}
764
765/*
drh4a2c7472018-08-13 15:09:48 +0000766** Free the list of RenameToken objects given in the second argument
767*/
dancf8f2892018-08-09 20:47:01 +0000768static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
769 RenameToken *pNext;
770 RenameToken *p;
771 for(p=pToken; p; p=pNext){
772 pNext = p->pNext;
773 sqlite3DbFree(db, p);
774 }
775}
776
dan987db762018-08-14 20:18:50 +0000777/*
778** Search the Parse object passed as the first argument for a RenameToken
779** object associated with parse tree element pPtr. If found, remove it
780** from the Parse object and add it to the list maintained by the
781** RenameCtx object passed as the second argument.
782*/
783static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000784 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000785 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000786 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
787 if( (*pp)->p==pPtr ){
788 RenameToken *pToken = *pp;
789 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000790 pToken->pNext = pCtx->pList;
791 pCtx->pList = pToken;
792 pCtx->nList++;
793 break;
dancf8f2892018-08-09 20:47:01 +0000794 }
795 }
dancf8f2892018-08-09 20:47:01 +0000796}
797
dan24fedb92018-08-18 17:35:38 +0000798/*
799** This is a Walker select callback. It does nothing. It is only required
800** because without a dummy callback, sqlite3WalkExpr() and similar do not
801** descend into sub-select statements.
802*/
dan987db762018-08-14 20:18:50 +0000803static int renameColumnSelectCb(Walker *pWalker, Select *p){
drh38d99642018-08-18 18:27:18 +0000804 UNUSED_PARAMETER(pWalker);
805 UNUSED_PARAMETER(p);
dan987db762018-08-14 20:18:50 +0000806 return WRC_Continue;
807}
808
dan987db762018-08-14 20:18:50 +0000809/*
810** This is a Walker expression callback.
811**
812** For every TK_COLUMN node in the expression tree, search to see
813** if the column being references is the column being renamed by an
814** ALTER TABLE statement. If it is, then attach its associated
815** RenameToken object to the list of RenameToken objects being
816** constructed in RenameCtx object at pWalker->u.pRename.
817*/
dancf8f2892018-08-09 20:47:01 +0000818static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000819 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000820 if( pExpr->op==TK_TRIGGER
821 && pExpr->iColumn==p->iCol
822 && pWalker->pParse->pTriggerTab==p->pTab
823 ){
dan5be60c52018-08-15 20:28:39 +0000824 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000825 }else if( pExpr->op==TK_COLUMN
826 && pExpr->iColumn==p->iCol
drheda079c2018-09-20 19:02:15 +0000827 && p->pTab==pExpr->y.pTab
dan987db762018-08-14 20:18:50 +0000828 ){
dan5496d6a2018-08-13 17:14:26 +0000829 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000830 }
831 return WRC_Continue;
832}
833
dan987db762018-08-14 20:18:50 +0000834/*
835** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000836** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000837** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000838** RenameContext. "Last" means the last RenameToken encountered when
839** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000840** return all column name tokens in the order that they are encountered
841** in the SQL statement.
842*/
dan5496d6a2018-08-13 17:14:26 +0000843static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000844 RenameToken *pBest = pCtx->pList;
845 RenameToken *pToken;
846 RenameToken **pp;
847
848 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
849 if( pToken->t.z>pBest->t.z ) pBest = pToken;
850 }
851 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
852 *pp = pBest->pNext;
853
854 return pBest;
855}
856
dan6fe7f232018-08-10 19:19:33 +0000857/*
dan24fedb92018-08-18 17:35:38 +0000858** An error occured while parsing or otherwise processing a database
859** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
860** ALTER TABLE RENAME COLUMN program. The error message emitted by the
861** sub-routine is currently stored in pParse->zErrMsg. This function
862** adds context to the error message and then stores it in pCtx.
863*/
danb0137382018-08-20 20:01:01 +0000864static void renameColumnParseError(
865 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000866 int bPost,
danb0137382018-08-20 20:01:01 +0000867 sqlite3_value *pType,
868 sqlite3_value *pObject,
869 Parse *pParse
870){
drh79a5ee92018-08-23 19:32:04 +0000871 const char *zT = (const char*)sqlite3_value_text(pType);
872 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000873 char *zErr;
danb0137382018-08-20 20:01:01 +0000874
dan0d5fa6b2018-08-24 17:55:49 +0000875 zErr = sqlite3_mprintf("error in %s %s%s: %s",
876 zT, zN, (bPost ? " after rename" : ""),
877 pParse->zErrMsg
878 );
dan24fedb92018-08-18 17:35:38 +0000879 sqlite3_result_error(pCtx, zErr, -1);
880 sqlite3_free(zErr);
881}
882
883/*
dan06249392018-08-21 15:06:59 +0000884** For each name in the the expression-list pEList (i.e. each
885** pEList->a[i].zName) that matches the string in zOld, extract the
886** corresponding rename-token from Parse object pParse and add it
887** to the RenameCtx pCtx.
888*/
889static void renameColumnElistNames(
890 Parse *pParse,
891 RenameCtx *pCtx,
892 ExprList *pEList,
893 const char *zOld
894){
895 if( pEList ){
896 int i;
897 for(i=0; i<pEList->nExpr; i++){
898 char *zName = pEList->a[i].zName;
899 if( 0==sqlite3_stricmp(zName, zOld) ){
900 renameTokenFind(pParse, pCtx, (void*)zName);
901 }
902 }
903 }
904}
905
906/*
907** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
908** that matches the string in zOld, extract the corresponding rename-token
909** from Parse object pParse and add it to the RenameCtx pCtx.
910*/
911static void renameColumnIdlistNames(
912 Parse *pParse,
913 RenameCtx *pCtx,
914 IdList *pIdList,
915 const char *zOld
916){
917 if( pIdList ){
918 int i;
919 for(i=0; i<pIdList->nId; i++){
920 char *zName = pIdList->a[i].zName;
921 if( 0==sqlite3_stricmp(zName, zOld) ){
922 renameTokenFind(pParse, pCtx, (void*)zName);
923 }
924 }
925 }
926}
927
dandd1a9c82018-09-05 08:28:30 +0000928/*
929** Parse the SQL statement zSql using Parse object (*p). The Parse object
930** is initialized by this function before it is used.
931*/
danc9461ec2018-08-29 21:00:16 +0000932static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000933 Parse *p, /* Memory to use for Parse object */
934 const char *zDb, /* Name of schema SQL belongs to */
935 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
936 sqlite3 *db, /* Database handle */
937 const char *zSql, /* SQL to parse */
938 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000939){
940 int rc;
941 char *zErr = 0;
942
943 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
944
945 /* Parse the SQL statement passed as the first argument. If no error
946 ** occurs and the parse does not result in a new table, index or
947 ** trigger object, the database must be corrupt. */
948 memset(p, 0, sizeof(Parse));
949 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
950 p->db = db;
951 p->nQueryLoop = 1;
952 rc = sqlite3RunParser(p, zSql, &zErr);
953 assert( p->zErrMsg==0 );
954 assert( rc!=SQLITE_OK || zErr==0 );
955 assert( (0!=p->pNewTable) + (0!=p->pNewIndex) + (0!=p->pNewTrigger)<2 );
956 p->zErrMsg = zErr;
957 if( db->mallocFailed ) rc = SQLITE_NOMEM;
958 if( rc==SQLITE_OK
959 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
960 ){
961 rc = SQLITE_CORRUPT_BKPT;
962 }
963
964#ifdef SQLITE_DEBUG
965 /* Ensure that all mappings in the Parse.pRename list really do map to
966 ** a part of the input string. */
967 if( rc==SQLITE_OK ){
968 int nSql = sqlite3Strlen30(zSql);
969 RenameToken *pToken;
970 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
971 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
972 }
973 }
974#endif
975
976 db->init.iDb = 0;
977 return rc;
978}
979
dandd1a9c82018-09-05 08:28:30 +0000980/*
981** This function edits SQL statement zSql, replacing each token identified
982** by the linked list pRename with the text of zNew. If argument bQuote is
983** true, then zNew is always quoted first. If no error occurs, the result
984** is loaded into context object pCtx as the result.
985**
986** Or, if an error occurs (i.e. an OOM condition), an error is left in
987** pCtx and an SQLite error code returned.
988*/
danc9461ec2018-08-29 21:00:16 +0000989static int renameEditSql(
990 sqlite3_context *pCtx, /* Return result here */
991 RenameCtx *pRename, /* Rename context */
992 const char *zSql, /* SQL statement to edit */
993 const char *zNew, /* New token text */
994 int bQuote /* True to always quote token */
995){
996 int nNew = sqlite3Strlen30(zNew);
997 int nSql = sqlite3Strlen30(zSql);
998 sqlite3 *db = sqlite3_context_db_handle(pCtx);
999 int rc = SQLITE_OK;
1000 char *zQuot;
1001 char *zOut;
1002 int nQuot;
1003
1004 /* Set zQuot to point to a buffer containing a quoted copy of the
1005 ** identifier zNew. If the corresponding identifier in the original
1006 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1007 ** point to zQuot so that all substitutions are made using the
1008 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +00001009 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +00001010 if( zQuot==0 ){
1011 return SQLITE_NOMEM;
1012 }else{
1013 nQuot = sqlite3Strlen30(zQuot);
1014 }
1015 if( bQuote ){
1016 zNew = zQuot;
1017 nNew = nQuot;
1018 }
1019
1020 /* At this point pRename->pList contains a list of RenameToken objects
1021 ** corresponding to all tokens in the input SQL that must be replaced
1022 ** with the new column name. All that remains is to construct and
1023 ** return the edited SQL string. */
1024 assert( nQuot>=nNew );
1025 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1026 if( zOut ){
1027 int nOut = nSql;
1028 memcpy(zOut, zSql, nSql);
1029 while( pRename->pList ){
1030 int iOff; /* Offset of token to replace in zOut */
1031 RenameToken *pBest = renameColumnTokenNext(pRename);
1032
1033 u32 nReplace;
1034 const char *zReplace;
1035 if( sqlite3IsIdChar(*pBest->t.z) ){
1036 nReplace = nNew;
1037 zReplace = zNew;
1038 }else{
1039 nReplace = nQuot;
1040 zReplace = zQuot;
1041 }
1042
1043 iOff = pBest->t.z - zSql;
1044 if( pBest->t.n!=nReplace ){
1045 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1046 nOut - (iOff + pBest->t.n)
1047 );
1048 nOut += nReplace - pBest->t.n;
1049 zOut[nOut] = '\0';
1050 }
1051 memcpy(&zOut[iOff], zReplace, nReplace);
1052 sqlite3DbFree(db, pBest);
1053 }
1054
1055 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1056 sqlite3DbFree(db, zOut);
1057 }else{
1058 rc = SQLITE_NOMEM;
1059 }
1060
1061 sqlite3_free(zQuot);
1062 return rc;
1063}
1064
dandd1a9c82018-09-05 08:28:30 +00001065/*
1066** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1067** it was read from the schema of database zDb. Return SQLITE_OK if
1068** successful. Otherwise, return an SQLite error code and leave an error
1069** message in the Parse object.
1070*/
1071static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001072 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001073 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001074 TriggerStep *pStep;
1075 NameContext sNC;
1076 int rc = SQLITE_OK;
1077
1078 memset(&sNC, 0, sizeof(sNC));
1079 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001080 assert( pNew->pTabSchema );
1081 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1082 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1083 );
1084 pParse->eTriggerOp = pNew->op;
drhf470c372018-10-03 18:05:36 +00001085 /* ALWAYS() because if the table of the trigger does not exist, the
1086 ** error would have been hit before this point */
1087 if( ALWAYS(pParse->pTriggerTab) ){
dan5351e882018-10-01 07:04:12 +00001088 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
1089 }
danc9461ec2018-08-29 21:00:16 +00001090
1091 /* Resolve symbols in WHEN clause */
dan5351e882018-10-01 07:04:12 +00001092 if( rc==SQLITE_OK && pNew->pWhen ){
dand5e6fef2018-09-07 15:50:31 +00001093 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001094 }
1095
dand5e6fef2018-09-07 15:50:31 +00001096 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001097 if( pStep->pSelect ){
1098 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1099 if( pParse->nErr ) rc = pParse->rc;
1100 }
dand5e6fef2018-09-07 15:50:31 +00001101 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001102 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1103 if( pTarget==0 ){
1104 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001105 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
danc9461ec2018-08-29 21:00:16 +00001106 SrcList sSrc;
1107 memset(&sSrc, 0, sizeof(sSrc));
1108 sSrc.nSrc = 1;
1109 sSrc.a[0].zName = pStep->zTarget;
1110 sSrc.a[0].pTab = pTarget;
1111 sNC.pSrcList = &sSrc;
1112 if( pStep->pWhere ){
1113 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1114 }
1115 if( rc==SQLITE_OK ){
1116 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1117 }
1118 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1119 if( pStep->pUpsert ){
1120 Upsert *pUpsert = pStep->pUpsert;
1121 assert( rc==SQLITE_OK );
1122 pUpsert->pUpsertSrc = &sSrc;
1123 sNC.uNC.pUpsert = pUpsert;
1124 sNC.ncFlags = NC_UUpsert;
1125 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1126 if( rc==SQLITE_OK ){
1127 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1128 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1129 }
1130 if( rc==SQLITE_OK ){
1131 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1132 }
1133 if( rc==SQLITE_OK ){
1134 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1135 }
1136 sNC.ncFlags = 0;
1137 }
1138 }
1139 }
1140 }
1141 return rc;
1142}
1143
dandd1a9c82018-09-05 08:28:30 +00001144/*
1145** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1146** objects that are part of the trigger passed as the second argument.
1147*/
danc9461ec2018-08-29 21:00:16 +00001148static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1149 TriggerStep *pStep;
1150
1151 /* Find tokens to edit in WHEN clause */
1152 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1153
1154 /* Find tokens to edit in trigger steps */
1155 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1156 sqlite3WalkSelect(pWalker, pStep->pSelect);
1157 sqlite3WalkExpr(pWalker, pStep->pWhere);
1158 sqlite3WalkExprList(pWalker, pStep->pExprList);
1159 if( pStep->pUpsert ){
1160 Upsert *pUpsert = pStep->pUpsert;
1161 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1162 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1163 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1164 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1165 }
1166 }
1167}
1168
dandd1a9c82018-09-05 08:28:30 +00001169/*
1170** Free the contents of Parse object (*pParse). Do not free the memory
1171** occupied by the Parse object itself.
1172*/
dan141e1192018-08-31 18:23:53 +00001173static void renameParseCleanup(Parse *pParse){
1174 sqlite3 *db = pParse->db;
1175 if( pParse->pVdbe ){
1176 sqlite3VdbeFinalize(pParse->pVdbe);
1177 }
1178 sqlite3DeleteTable(db, pParse->pNewTable);
1179 if( pParse->pNewIndex ) sqlite3FreeIndex(db, pParse->pNewIndex);
1180 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1181 sqlite3DbFree(db, pParse->zErrMsg);
1182 renameTokenFree(db, pParse->pRename);
1183 sqlite3ParserReset(pParse);
1184}
1185
dan06249392018-08-21 15:06:59 +00001186/*
dan987db762018-08-14 20:18:50 +00001187** SQL function:
1188**
1189** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1190**
1191** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001192** 1. type: Type of object ("table", "view" etc.)
1193** 2. object: Name of object
1194** 3. Database: Database name (e.g. "main")
1195** 4. Table: Table name
1196** 5. iCol: Index of column to rename
1197** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001198** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001199** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001200**
1201** Do a column rename operation on the CREATE statement given in zSql.
1202** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1203** into zNew. The name should be quoted if bQuote is true.
1204**
1205** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1206** Though accessible to application code, it is not intended for use by
1207** applications. The existance of this function, and the way it works,
1208** is subject to change without notice.
1209**
1210** If any of the parameters are out-of-bounds, then simply return NULL.
1211** An out-of-bounds parameter can only occur when the application calls
1212** this function directly. The parameters will always be well-formed when
1213** this routine is invoked by the bytecode for a legitimate ALTER TABLE
1214** statement.
dan6fe7f232018-08-10 19:19:33 +00001215*/
dancf8f2892018-08-09 20:47:01 +00001216static void renameColumnFunc(
1217 sqlite3_context *context,
1218 int NotUsed,
1219 sqlite3_value **argv
1220){
1221 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001222 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001223 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001224 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1225 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1226 int iCol = sqlite3_value_int(argv[5]);
1227 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001228 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001229 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001230 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001231 int rc;
dancf8f2892018-08-09 20:47:01 +00001232 Parse sParse;
1233 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001234 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001235 int i;
dan987db762018-08-14 20:18:50 +00001236 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001237#ifndef SQLITE_OMIT_AUTHORIZATION
1238 sqlite3_xauth xAuth = db->xAuth;
1239#endif
dancf8f2892018-08-09 20:47:01 +00001240
drh38d99642018-08-18 18:27:18 +00001241 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001242 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001243 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001244 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001245 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001246 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001247 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001248 if( pTab==0 || iCol>=pTab->nCol ){
1249 sqlite3BtreeLeaveAll(db);
1250 return;
1251 }
dan987db762018-08-14 20:18:50 +00001252 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001253 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001254 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001255
dan141e1192018-08-31 18:23:53 +00001256#ifndef SQLITE_OMIT_AUTHORIZATION
1257 db->xAuth = 0;
1258#endif
danc9461ec2018-08-29 21:00:16 +00001259 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001260
dancf8f2892018-08-09 20:47:01 +00001261 /* Find tokens that need to be replaced. */
1262 memset(&sWalker, 0, sizeof(Walker));
1263 sWalker.pParse = &sParse;
1264 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001265 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001266 sWalker.u.pRename = &sCtx;
1267
dan0cbb0b12018-08-16 19:49:16 +00001268 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001269 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001270 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001271 Select *pSelect = sParse.pNewTable->pSelect;
1272 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001273 sParse.rc = SQLITE_OK;
1274 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1275 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1276 if( rc==SQLITE_OK ){
1277 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001278 }
dan987db762018-08-14 20:18:50 +00001279 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1280 }else{
1281 /* A regular table */
1282 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1283 FKey *pFKey;
1284 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001285 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001286 if( bFKOnly==0 ){
1287 renameTokenFind(
1288 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1289 );
1290 if( sCtx.iCol<0 ){
1291 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001292 }
dan987db762018-08-14 20:18:50 +00001293 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1294 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1295 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1296 }
1297 }
1298
1299 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1300 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001301 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001302 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1303 }
1304 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1305 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1306 ){
1307 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1308 }
dan6fe7f232018-08-10 19:19:33 +00001309 }
dancf8f2892018-08-09 20:47:01 +00001310 }
1311 }
dan5496d6a2018-08-13 17:14:26 +00001312 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001313 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1314 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001315 }else{
dan5be60c52018-08-15 20:28:39 +00001316 /* A trigger */
1317 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001318 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001319 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001320
danc9461ec2018-08-29 21:00:16 +00001321 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1322 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001323 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001324 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001325 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001326 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1327 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001328 }
danc9461ec2018-08-29 21:00:16 +00001329 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1330 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001331 }
1332 }
1333 }
1334
dan5be60c52018-08-15 20:28:39 +00001335
1336 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001337 if( sParse.pTriggerTab==pTab ){
1338 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001339 }
dan5be60c52018-08-15 20:28:39 +00001340
danc9461ec2018-08-29 21:00:16 +00001341 /* Find tokens to edit in various expressions and selects */
1342 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001343 }
1344
dan987db762018-08-14 20:18:50 +00001345 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001346 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001347
drh5fc22cd2018-08-13 13:43:11 +00001348renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001349 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001350 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001351 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001352 }else{
1353 sqlite3_result_error_code(context, rc);
1354 }
1355 }
1356
dan141e1192018-08-31 18:23:53 +00001357 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001358 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001359#ifndef SQLITE_OMIT_AUTHORIZATION
1360 db->xAuth = xAuth;
1361#endif
drhda76adc2018-08-25 02:04:05 +00001362 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001363}
1364
dandd1a9c82018-09-05 08:28:30 +00001365/*
1366** Walker expression callback used by "RENAME TABLE".
1367*/
danc9461ec2018-08-29 21:00:16 +00001368static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1369 RenameCtx *p = pWalker->u.pRename;
drheda079c2018-09-20 19:02:15 +00001370 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){
1371 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16 +00001372 }
1373 return WRC_Continue;
1374}
1375
1376/*
dandd1a9c82018-09-05 08:28:30 +00001377** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001378*/
1379static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1380 int i;
1381 RenameCtx *p = pWalker->u.pRename;
1382 SrcList *pSrc = pSelect->pSrc;
1383 for(i=0; i<pSrc->nSrc; i++){
1384 struct SrcList_item *pItem = &pSrc->a[i];
1385 if( pItem->pTab==p->pTab ){
1386 renameTokenFind(pWalker->pParse, p, pItem->zName);
1387 }
1388 }
1389
1390 return WRC_Continue;
1391}
1392
1393
1394/*
1395** This C function implements an SQL user function that is used by SQL code
1396** generated by the ALTER TABLE ... RENAME command to modify the definition
1397** of any foreign key constraints that use the table being renamed as the
1398** parent table. It is passed three arguments:
1399**
dan141e1192018-08-31 18:23:53 +00001400** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001401** 1. type: Type of object ("table", "view" etc.)
1402** 2. object: Name of object
1403** 3: The complete text of the schema statement being modified,
1404** 4: The old name of the table being renamed, and
1405** 5: The new name of the table being renamed.
1406** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001407**
dan141e1192018-08-31 18:23:53 +00001408** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001409**
dan141e1192018-08-31 18:23:53 +00001410** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001411** -> 'CREATE TABLE t1(a REFERENCES t3)'
1412*/
1413static void renameTableFunc(
1414 sqlite3_context *context,
1415 int NotUsed,
1416 sqlite3_value **argv
1417){
1418 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001419 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001420 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1421 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1422 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1423 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001424 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001425
dan141e1192018-08-31 18:23:53 +00001426 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001427 Parse sParse;
1428 int rc;
1429 int bQuote = 1;
1430 RenameCtx sCtx;
1431 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001432
dan141e1192018-08-31 18:23:53 +00001433#ifndef SQLITE_OMIT_AUTHORIZATION
1434 sqlite3_xauth xAuth = db->xAuth;
1435 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001436#endif
1437
dan141e1192018-08-31 18:23:53 +00001438 sqlite3BtreeEnterAll(db);
1439
1440 memset(&sCtx, 0, sizeof(RenameCtx));
1441 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1442 memset(&sWalker, 0, sizeof(Walker));
1443 sWalker.pParse = &sParse;
1444 sWalker.xExprCallback = renameTableExprCb;
1445 sWalker.xSelectCallback = renameTableSelectCb;
1446 sWalker.u.pRename = &sCtx;
1447
1448 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1449
1450 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001451 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan141e1192018-08-31 18:23:53 +00001452 if( sParse.pNewTable ){
1453 Table *pTab = sParse.pNewTable;
1454
1455 if( pTab->pSelect ){
dan674b8942018-09-20 08:28:01 +00001456 if( isLegacy==0 ){
1457 NameContext sNC;
1458 memset(&sNC, 0, sizeof(sNC));
1459 sNC.pParse = &sParse;
dan141e1192018-08-31 18:23:53 +00001460
dan674b8942018-09-20 08:28:01 +00001461 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1462 if( sParse.nErr ) rc = sParse.rc;
1463 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1464 }
dan141e1192018-08-31 18:23:53 +00001465 }else{
1466 /* Modify any FK definitions to point to the new table. */
1467#ifndef SQLITE_OMIT_FOREIGN_KEY
dan202a0272018-09-07 11:51:21 +00001468 if( db->flags & SQLITE_ForeignKeys ){
1469 FKey *pFKey;
1470 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1471 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1472 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1473 }
dan141e1192018-08-31 18:23:53 +00001474 }
1475 }
1476#endif
1477
1478 /* If this is the table being altered, fix any table refs in CHECK
1479 ** expressions. Also update the name that appears right after the
1480 ** "CREATE [VIRTUAL] TABLE" bit. */
1481 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1482 sCtx.pTab = pTab;
dan674b8942018-09-20 08:28:01 +00001483 if( isLegacy==0 ){
1484 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1485 }
dan141e1192018-08-31 18:23:53 +00001486 renameTokenFind(&sParse, &sCtx, pTab->zName);
1487 }
danc9461ec2018-08-29 21:00:16 +00001488 }
1489 }
danc9461ec2018-08-29 21:00:16 +00001490
dan141e1192018-08-31 18:23:53 +00001491 else if( sParse.pNewIndex ){
1492 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
dan674b8942018-09-20 08:28:01 +00001493 if( isLegacy==0 ){
1494 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1495 }
dan141e1192018-08-31 18:23:53 +00001496 }
danc9461ec2018-08-29 21:00:16 +00001497
1498#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001499 else{
dan141e1192018-08-31 18:23:53 +00001500 Trigger *pTrigger = sParse.pNewTrigger;
1501 TriggerStep *pStep;
1502 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1503 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1504 ){
1505 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1506 }
danc9461ec2018-08-29 21:00:16 +00001507
dan674b8942018-09-20 08:28:01 +00001508 if( isLegacy==0 ){
1509 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1510 if( rc==SQLITE_OK ){
1511 renameWalkTrigger(&sWalker, pTrigger);
1512 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1513 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1514 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1515 }
dan141e1192018-08-31 18:23:53 +00001516 }
dan0ccda962018-08-30 16:26:48 +00001517 }
danc9461ec2018-08-29 21:00:16 +00001518 }
1519 }
dan141e1192018-08-31 18:23:53 +00001520#endif
danc9461ec2018-08-29 21:00:16 +00001521 }
dan141e1192018-08-31 18:23:53 +00001522
1523 if( rc==SQLITE_OK ){
1524 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1525 }
1526 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001527 if( sParse.zErrMsg ){
1528 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1529 }else{
1530 sqlite3_result_error_code(context, rc);
1531 }
dan141e1192018-08-31 18:23:53 +00001532 }
1533
1534 renameParseCleanup(&sParse);
1535 renameTokenFree(db, sCtx.pList);
1536 sqlite3BtreeLeaveAll(db);
1537#ifndef SQLITE_OMIT_AUTHORIZATION
1538 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001539#endif
1540 }
1541
danc9461ec2018-08-29 21:00:16 +00001542 return;
1543}
1544
dandd1a9c82018-09-05 08:28:30 +00001545/*
1546** An SQL user function that checks that there are no parse or symbol
1547** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1548** After an ALTER TABLE .. RENAME operation is performed and the schema
1549** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001550** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001551**
1552** 0: Database name ("main", "temp" etc.).
1553** 1: SQL statement.
1554** 2: Object type ("view", "table", "trigger" or "index").
1555** 3: Object name.
1556** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001557**
1558** Unless it finds an error, this function normally returns NULL. However, it
1559** returns integer value 1 if:
1560**
1561** * the SQL argument creates a trigger, and
1562** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001563*/
dan9d324822018-08-30 20:03:44 +00001564static void renameTableTest(
1565 sqlite3_context *context,
1566 int NotUsed,
1567 sqlite3_value **argv
1568){
1569 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001570 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1571 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001572 int bTemp = sqlite3_value_int(argv[4]);
dan674b8942018-09-20 08:28:01 +00001573 int isLegacy = (db->flags & SQLITE_LegacyAlter);
dan9d324822018-08-30 20:03:44 +00001574
dan141e1192018-08-31 18:23:53 +00001575#ifndef SQLITE_OMIT_AUTHORIZATION
1576 sqlite3_xauth xAuth = db->xAuth;
1577 db->xAuth = 0;
1578#endif
1579
drh5b1da302018-09-01 20:02:07 +00001580 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001581 if( zDb && zInput ){
1582 int rc;
1583 Parse sParse;
1584 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1585 if( rc==SQLITE_OK ){
dan674b8942018-09-20 08:28:01 +00001586 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){
dan09236502018-09-01 16:05:50 +00001587 NameContext sNC;
1588 memset(&sNC, 0, sizeof(sNC));
1589 sNC.pParse = &sParse;
1590 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1591 if( sParse.nErr ) rc = sParse.rc;
1592 }
1593
1594 else if( sParse.pNewTrigger ){
dan674b8942018-09-20 08:28:01 +00001595 if( isLegacy==0 ){
1596 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1597 }
drh3b700452018-09-07 19:12:08 +00001598 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001599 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1600 int i2 = sqlite3FindDbName(db, zDb);
1601 if( i1==i2 ) sqlite3_result_int(context, 1);
1602 }
dan09236502018-09-01 16:05:50 +00001603 }
dan9d324822018-08-30 20:03:44 +00001604 }
1605
dan09236502018-09-01 16:05:50 +00001606 if( rc!=SQLITE_OK ){
1607 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001608 }
dan09236502018-09-01 16:05:50 +00001609 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001610 }
1611
dan141e1192018-08-31 18:23:53 +00001612#ifndef SQLITE_OMIT_AUTHORIZATION
1613 db->xAuth = xAuth;
1614#endif
dan9d324822018-08-30 20:03:44 +00001615}
1616
dancf8f2892018-08-09 20:47:01 +00001617/*
1618** Register built-in functions used to help implement ALTER TABLE
1619*/
1620void sqlite3AlterFunctions(void){
1621 static FuncDef aAlterTableFuncs[] = {
danb87a9a82018-09-01 20:23:28 +00001622 FUNCTION(sqlite_rename_column, 9, 0, 0, renameColumnFunc),
dan65372fa2018-09-03 20:05:15 +00001623 FUNCTION(sqlite_rename_table, 7, 0, 0, renameTableFunc),
dan9d324822018-08-30 20:03:44 +00001624 FUNCTION(sqlite_rename_test, 5, 0, 0, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001625 };
1626 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1627}
drhd0e4a6c2005-02-15 20:47:57 +00001628#endif /* SQLITE_ALTER_TABLE */