blob: 65880752c9e58097168aa61e3ad38c5c3721eab0 [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/*
dan432cc5b2009-09-26 17:51:48 +000024** This function is used to create the text of expressions of the form:
25**
26** name=<constant1> OR name=<constant2> OR ...
27**
28** If argument zWhere is NULL, then a pointer string containing the text
29** "name=<constant>" is returned, where <constant> is the quoted version
30** of the string passed as argument zConstant. The returned buffer is
31** allocated using sqlite3DbMalloc(). It is the responsibility of the
32** caller to ensure that it is eventually freed.
33**
34** If argument zWhere is not NULL, then the string returned is
35** "<where> OR name=<constant>", where <where> is the contents of zWhere.
36** In this case zWhere is passed to sqlite3DbFree() before returning.
37**
38*/
39static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
40 char *zNew;
41 if( !zWhere ){
42 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
43 }else{
44 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
45 sqlite3DbFree(db, zWhere);
46 }
47 return zNew;
48}
49
dan856ef1a2009-09-29 06:33:23 +000050#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +000051/*
52** Generate the text of a WHERE expression which can be used to select all
53** tables that have foreign key constraints that refer to table pTab (i.e.
54** constraints for which pTab is the parent table) from the sqlite_master
55** table.
56*/
57static char *whereForeignKeys(Parse *pParse, Table *pTab){
58 FKey *p;
59 char *zWhere = 0;
60 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
61 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
62 }
63 return zWhere;
drh1f01ec12005-02-15 21:36:18 +000064}
dan856ef1a2009-09-29 06:33:23 +000065#endif
drh1f01ec12005-02-15 21:36:18 +000066
drhd0e4a6c2005-02-15 20:47:57 +000067/*
danielk197719a8e7e2005-03-17 05:03:38 +000068** Generate the text of a WHERE expression which can be used to select all
69** temporary triggers on table pTab from the sqlite_temp_master table. If
70** table pTab has no temporary triggers, or is itself stored in the
71** temporary database, NULL is returned.
72*/
73static char *whereTempTriggers(Parse *pParse, Table *pTab){
74 Trigger *pTrig;
75 char *zWhere = 0;
danielk1977e501b892006-01-09 06:29:47 +000076 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
danielk1977da184232006-01-05 11:34:32 +000077
78 /* If the table is not located in the temp-db (in which case NULL is
79 ** returned, loop through the tables list of triggers. For each trigger
80 ** that is not part of the temp-db schema, add a clause to the WHERE
81 ** expression being built up in zWhere.
82 */
83 if( pTab->pSchema!=pTempSchema ){
danielk19771e536952007-08-16 10:09:01 +000084 sqlite3 *db = pParse->db;
danielk19772f886d12009-02-28 10:47:41 +000085 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +000086 if( pTrig->pSchema==pTempSchema ){
dan432cc5b2009-09-26 17:51:48 +000087 zWhere = whereOrName(db, zWhere, pTrig->zName);
danielk197719a8e7e2005-03-17 05:03:38 +000088 }
89 }
90 }
dan39f1bcb2010-09-29 07:16:46 +000091 if( zWhere ){
92 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
93 sqlite3DbFree(pParse->db, zWhere);
94 zWhere = zNew;
95 }
danielk197719a8e7e2005-03-17 05:03:38 +000096 return zWhere;
97}
98
99/*
100** Generate code to drop and reload the internal representation of table
101** pTab from the database, including triggers and temporary triggers.
102** Argument zName is the name of the table in the database schema at
103** the time the generated code is executed. This can be different from
104** pTab->zName if this function is being called to code part of an
105** "ALTER TABLE RENAME TO" statement.
106*/
107static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
108 Vdbe *v;
109 char *zWhere;
danielk1977da184232006-01-05 11:34:32 +0000110 int iDb; /* Index of database containing pTab */
danielk197719a8e7e2005-03-17 05:03:38 +0000111#ifndef SQLITE_OMIT_TRIGGER
112 Trigger *pTrig;
113#endif
114
115 v = sqlite3GetVdbe(pParse);
drhd3264c72009-04-15 13:39:47 +0000116 if( NEVER(v==0) ) return;
drh1fee73e2007-08-29 04:00:57 +0000117 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +0000118 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119 assert( iDb>=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000120
121#ifndef SQLITE_OMIT_TRIGGER
122 /* Drop any table triggers from the internal schema. */
danielk19772f886d12009-02-28 10:47:41 +0000123 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000124 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
125 assert( iTrigDb==iDb || iTrigDb==1 );
dan165921a2009-08-28 18:53:45 +0000126 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000127 }
128#endif
129
dan432cc5b2009-09-26 17:51:48 +0000130 /* Drop the table and index from the internal schema. */
drh66a51672008-01-03 00:01:23 +0000131 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000132
133 /* Reload the table, index and permanent trigger schemas. */
danielk19771e536952007-08-16 10:09:01 +0000134 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000135 if( !zWhere ) return;
drh5d9c9da2011-06-03 20:11:17 +0000136 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
danielk197719a8e7e2005-03-17 05:03:38 +0000137
138#ifndef SQLITE_OMIT_TRIGGER
139 /* Now, if the table is not stored in the temp database, reload any temp
140 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
141 */
drhd9cb6ac2005-10-20 07:28:17 +0000142 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
drh5d9c9da2011-06-03 20:11:17 +0000143 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
danielk197719a8e7e2005-03-17 05:03:38 +0000144 }
145#endif
146}
147
148/*
danbe535002011-04-01 15:15:58 +0000149** Parameter zName is the name of a table that is about to be altered
150** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
151** If the table is a system table, this function leaves an error message
152** in pParse->zErr (system tables may not be altered) and returns non-zero.
153**
154** Or, if zName is not a system table, zero is returned.
155*/
156static int isSystemTable(Parse *pParse, const char *zName){
drh59a386e2017-06-28 01:12:53 +0000157 if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danbe535002011-04-01 15:15:58 +0000158 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
159 return 1;
160 }
161 return 0;
162}
163
164/*
drhd0e4a6c2005-02-15 20:47:57 +0000165** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
166** command.
167*/
168void sqlite3AlterRenameTable(
169 Parse *pParse, /* Parser context. */
170 SrcList *pSrc, /* The table to rename. */
171 Token *pName /* The new table name. */
172){
173 int iDb; /* Database that contains the table */
174 char *zDb; /* Name of database iDb */
175 Table *pTab; /* Table being renamed */
176 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000177 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000178 int nTabName; /* Number of UTF-8 characters in zTabName */
179 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000180 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +0000181 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000182 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000183
drh8257aa82017-07-26 19:59:13 +0000184 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000185 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000186 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000187 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000188
dan41fb5cd2012-10-04 19:33:00 +0000189 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000190 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000191 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000192 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000193 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000194
195 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000196 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000197 if( !zName ) goto exit_rename_table;
198
199 /* Check that a table or index named 'zName' does not already exist
200 ** in database iDb. If so, this is an error.
201 */
202 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
203 sqlite3ErrorMsg(pParse,
204 "there is already another table or index with this name: %s", zName);
205 goto exit_rename_table;
206 }
207
208 /* Make sure it is not a system table being altered, or a reserved name
209 ** that the table is being renamed to.
210 */
danbe535002011-04-01 15:15:58 +0000211 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
drhd0e4a6c2005-02-15 20:47:57 +0000212 goto exit_rename_table;
213 }
danbe535002011-04-01 15:15:58 +0000214 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
215 exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000216 }
217
danielk197761116ae2007-12-13 08:15:30 +0000218#ifndef SQLITE_OMIT_VIEW
219 if( pTab->pSelect ){
220 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
221 goto exit_rename_table;
222 }
223#endif
224
drhd0e4a6c2005-02-15 20:47:57 +0000225#ifndef SQLITE_OMIT_AUTHORIZATION
226 /* Invoke the authorization callback. */
227 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
228 goto exit_rename_table;
229 }
230#endif
231
danielk1977182c4ba2007-06-27 15:53:34 +0000232#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000233 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
234 goto exit_rename_table;
235 }
danielk1977595a5232009-07-24 17:58:53 +0000236 if( IsVirtual(pTab) ){
237 pVTab = sqlite3GetVTable(db, pTab);
238 if( pVTab->pVtab->pModule->xRename==0 ){
239 pVTab = 0;
240 }
danielk1977182c4ba2007-06-27 15:53:34 +0000241 }
242#endif
243
drhb22f7c82014-02-06 23:56:27 +0000244 /* Begin a transaction for database iDb.
drhd0e4a6c2005-02-15 20:47:57 +0000245 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000246 ** schema). Open a statement transaction if the table is a virtual
247 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000248 */
249 v = sqlite3GetVdbe(pParse);
250 if( v==0 ){
251 goto exit_rename_table;
252 }
danielk1977595a5232009-07-24 17:58:53 +0000253 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
drh9cbf3422008-01-17 16:22:13 +0000254 sqlite3ChangeCookie(pParse, iDb);
drhd0e4a6c2005-02-15 20:47:57 +0000255
danielk1977182c4ba2007-06-27 15:53:34 +0000256 /* If this is a virtual table, invoke the xRename() function if
257 ** one is defined. The xRename() callback will modify the names
258 ** of any resources used by the v-table implementation (including other
259 ** SQLite tables) that are identified by the name of the virtual table.
260 */
261#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000262 if( pVTab ){
danielk1977a29f18c2008-01-04 11:01:03 +0000263 int i = ++pParse->nMem;
drh076e85f2015-09-03 13:46:12 +0000264 sqlite3VdbeLoadString(v, i, zName);
danielk1977595a5232009-07-24 17:58:53 +0000265 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dane0af83a2009-09-08 19:15:01 +0000266 sqlite3MayAbort(pParse);
danielk1977182c4ba2007-06-27 15:53:34 +0000267 }
268#endif
269
drh4e5dd852007-05-15 03:56:49 +0000270 /* figure out how many UTF-8 characters are in zName */
271 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000272 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000273
danc9461ec2018-08-29 21:00:16 +0000274 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
275 ** the schema to use the new table name. */
276 sqlite3NestedParse(pParse,
277 "UPDATE \"%w\".%s SET "
278 "sql = sqlite_rename_table(%Q, sql, %Q, %Q, 0) "
279 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
280 "AND name NOT LIKE 'sqlite_%%'"
281 , zDb, MASTER_NAME, zDb, zTabName, zName, zTabName
282 );
dan432cc5b2009-09-26 17:51:48 +0000283
danc9461ec2018-08-29 21:00:16 +0000284 /* Update the tbl_name and name columns of the sqlite_master table
285 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000286 sqlite3NestedParse(pParse,
287 "UPDATE %Q.%s SET "
drhd0e4a6c2005-02-15 20:47:57 +0000288 "tbl_name = %Q, "
289 "name = CASE "
290 "WHEN type='table' THEN %Q "
291 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000292 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000293 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000294 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000295 "(type='table' OR type='index' OR type='trigger');",
danc9461ec2018-08-29 21:00:16 +0000296 zDb, MASTER_NAME,
297 zName, zName, zName,
298 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000299 );
300
301#ifndef SQLITE_OMIT_AUTOINCREMENT
302 /* If the sqlite_sequence table exists in this database, then update
303 ** it with the new table name.
304 */
305 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
306 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000307 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000308 zDb, zName, pTab->zName);
309 }
310#endif
311
danc9461ec2018-08-29 21:00:16 +0000312 /* If the table being renamed is not itself part of the temp database,
313 ** edit view and trigger definitions within the temp database
314 ** as required. */
315 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000316 sqlite3NestedParse(pParse,
317 "UPDATE sqlite_temp_master SET "
danc9461ec2018-08-29 21:00:16 +0000318 "sql = sqlite_rename_table(%Q, sql, %Q, %Q, 1), "
319 "tbl_name = "
320 "CASE WHEN tbl_name=%Q COLLATE nocase THEN %Q ELSE tbl_name END "
321 "WHERE type IN ('view', 'trigger')"
322 , zDb, zTabName, zName, zTabName, zTabName, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000323 }
drhd0e4a6c2005-02-15 20:47:57 +0000324
danc9461ec2018-08-29 21:00:16 +0000325 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
326 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
drhd0e4a6c2005-02-15 20:47:57 +0000327
328exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000329 sqlite3SrcListDelete(db, pSrc);
330 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000331 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000332}
danielk197719a8e7e2005-03-17 05:03:38 +0000333
drhd3001712009-05-12 17:46:53 +0000334/*
danielk197719a8e7e2005-03-17 05:03:38 +0000335** This function is called after an "ALTER TABLE ... ADD" statement
336** has been parsed. Argument pColDef contains the text of the new
337** column definition.
338**
339** The Table structure pParse->pNewTable was extended to include
340** the new column during parsing.
341*/
342void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
343 Table *pNew; /* Copy of pParse->pNewTable */
344 Table *pTab; /* Table being altered */
345 int iDb; /* Database number */
346 const char *zDb; /* Database name */
347 const char *zTab; /* Table name */
348 char *zCol; /* Null-terminated column definition */
349 Column *pCol; /* The new column */
350 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000351 sqlite3 *db; /* The database connection; */
drhbbde0182016-02-09 16:09:22 +0000352 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000353 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000354
danielk1977f150c9d2008-10-30 17:21:12 +0000355 db = pParse->db;
356 if( pParse->nErr || db->mallocFailed ) return;
drhbbde0182016-02-09 16:09:22 +0000357 assert( v!=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000358 pNew = pParse->pNewTable;
359 assert( pNew );
360
drh1fee73e2007-08-29 04:00:57 +0000361 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000362 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000363 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000364 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000365 pCol = &pNew->aCol[pNew->nCol-1];
366 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000367 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000368 assert( pTab );
369
drh81f2ccd2006-01-31 14:28:44 +0000370#ifndef SQLITE_OMIT_AUTHORIZATION
371 /* Invoke the authorization callback. */
372 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
373 return;
374 }
375#endif
376
danielk197719a8e7e2005-03-17 05:03:38 +0000377 /* If the default value for the new column was specified with a
378 ** literal NULL, then set pDflt to 0. This simplifies checking
379 ** for an SQL NULL default below.
380 */
drh94fa9c42016-02-27 21:16:04 +0000381 assert( pDflt==0 || pDflt->op==TK_SPAN );
382 if( pDflt && pDflt->pLeft->op==TK_NULL ){
danielk197719a8e7e2005-03-17 05:03:38 +0000383 pDflt = 0;
384 }
385
386 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
387 ** If there is a NOT NULL constraint, then the default value for the
388 ** column must not be NULL.
389 */
drha371ace2012-09-13 14:22:47 +0000390 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000391 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
392 return;
393 }
394 if( pNew->pIndex ){
395 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
396 return;
397 }
dan53c3fa82009-09-25 11:26:54 +0000398 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
399 sqlite3ErrorMsg(pParse,
400 "Cannot add a REFERENCES column with non-NULL default value");
401 return;
402 }
danielk197719a8e7e2005-03-17 05:03:38 +0000403 if( pCol->notNull && !pDflt ){
404 sqlite3ErrorMsg(pParse,
405 "Cannot add a NOT NULL column with default value NULL");
406 return;
407 }
408
409 /* Ensure the default expression is something that sqlite3ValueFromExpr()
410 ** can handle (i.e. not CURRENT_TIME etc.)
411 */
412 if( pDflt ){
dan7a419232013-08-06 20:01:43 +0000413 sqlite3_value *pVal = 0;
drh96f4ad22015-03-12 21:02:36 +0000414 int rc;
drh05883a32015-06-02 15:32:08 +0000415 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
drh96f4ad22015-03-12 21:02:36 +0000416 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
417 if( rc!=SQLITE_OK ){
pdrbb3da062016-02-06 14:14:43 +0000418 assert( db->mallocFailed == 1 );
danielk197719a8e7e2005-03-17 05:03:38 +0000419 return;
420 }
421 if( !pVal ){
422 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
423 return;
424 }
425 sqlite3ValueFree(pVal);
426 }
427
428 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000429 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000430 if( zCol ){
431 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000432 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000433 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000434 *zEnd-- = '\0';
435 }
drh8257aa82017-07-26 19:59:13 +0000436 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000437 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000438 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000439 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000440 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000441 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000442 zTab
443 );
drh633e6d52008-07-28 19:34:53 +0000444 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000445 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000446 }
447
drh86396212016-07-14 19:13:11 +0000448 /* Make sure the schema version is at least 3. But do not upgrade
449 ** from less than 3 to 4, as that will corrupt any preexisting DESC
450 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000451 */
drh86396212016-07-14 19:13:11 +0000452 r1 = sqlite3GetTempReg(pParse);
453 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
454 sqlite3VdbeUsesBtree(v, iDb);
455 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
456 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
457 VdbeCoverage(v);
458 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
459 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000460
461 /* Reload the schema of the modified table. */
462 reloadTableSchema(pParse, pTab, pTab->zName);
463}
464
drhfdd6e852005-12-16 01:06:16 +0000465/*
danielk197719a8e7e2005-03-17 05:03:38 +0000466** This function is called by the parser after the table-name in
467** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
468** pSrc is the full-name of the table being altered.
469**
470** This routine makes a (partial) copy of the Table structure
471** for the table being altered and sets Parse.pNewTable to point
472** to it. Routines called by the parser as the column definition
473** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
474** the copy. The copy of the Table structure is deleted by tokenize.c
475** after parsing is finished.
476**
477** Routine sqlite3AlterFinishAddColumn() will be called to complete
478** coding the "ALTER TABLE ... ADD" statement.
479*/
480void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
481 Table *pNew;
482 Table *pTab;
483 Vdbe *v;
484 int iDb;
485 int i;
486 int nAlloc;
drh17435752007-08-16 04:30:38 +0000487 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000488
489 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000490 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000491 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000492 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000493 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000494 if( !pTab ) goto exit_begin_add_column;
495
danielk19775ee9d692006-06-21 12:36:25 +0000496#ifndef SQLITE_OMIT_VIRTUALTABLE
497 if( IsVirtual(pTab) ){
498 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
499 goto exit_begin_add_column;
500 }
501#endif
502
danielk197719a8e7e2005-03-17 05:03:38 +0000503 /* Make sure this is not an attempt to ALTER a view. */
504 if( pTab->pSelect ){
505 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
506 goto exit_begin_add_column;
507 }
danbe535002011-04-01 15:15:58 +0000508 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
509 goto exit_begin_add_column;
510 }
danielk197719a8e7e2005-03-17 05:03:38 +0000511
512 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000513 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000514
515 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000516 ** sqlite3AddColumn() function and friends to modify. But modify
517 ** the name by adding an "sqlite_altertab_" prefix. By adding this
518 ** prefix, we insure that the name will not collide with an existing
519 ** table because user table are not allowed to have the "sqlite_"
520 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000521 */
drh17435752007-08-16 04:30:38 +0000522 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000523 if( !pNew ) goto exit_begin_add_column;
524 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000525 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000526 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000527 assert( pNew->nCol>0 );
528 nAlloc = (((pNew->nCol-1)/8)*8)+8;
529 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000530 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000531 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000532 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000533 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000534 goto exit_begin_add_column;
535 }
536 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
537 for(i=0; i<pNew->nCol; i++){
538 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000539 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000540 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000541 pCol->pDflt = 0;
542 }
drh17435752007-08-16 04:30:38 +0000543 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000544 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000545 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000546
547 /* Begin a transaction and increment the schema cookie. */
548 sqlite3BeginWriteOperation(pParse, 0, iDb);
549 v = sqlite3GetVdbe(pParse);
550 if( !v ) goto exit_begin_add_column;
drh9cbf3422008-01-17 16:22:13 +0000551 sqlite3ChangeCookie(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000552
553exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000554 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000555 return;
556}
dancf8f2892018-08-09 20:47:01 +0000557
drh4a2c7472018-08-13 15:09:48 +0000558/*
dan9d705572018-08-20 16:16:05 +0000559** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
560** command. This function checks if the table is a view or virtual
561** table (columns of views or virtual tables may not be renamed). If so,
562** it loads an error message into pParse and returns non-zero.
563**
564** Or, if pTab is not a view or virtual table, zero is returned.
565*/
566#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
567static int isRealTable(Parse *pParse, Table *pTab){
568 const char *zType = 0;
569#ifndef SQLITE_OMIT_VIEW
570 if( pTab->pSelect ){
571 zType = "view";
572 }else
573#endif
574#ifndef SQLITE_OMIT_VIRTUALTABLE
575 if( IsVirtual(pTab) ){
576 zType = "virtual table";
577 }
578#endif
579 if( zType ){
580 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000581 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000582 );
583 return 1;
584 }
585 return 0;
586}
587#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
588# define isRealTable(x,y) (0)
589#endif
590
591/*
drh4a2c7472018-08-13 15:09:48 +0000592** Handles the following parser reduction:
593**
594** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
595*/
dancf8f2892018-08-09 20:47:01 +0000596void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000597 Parse *pParse, /* Parsing context */
598 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
599 Token *pOld, /* Name of column being changed */
600 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000601){
drh4a2c7472018-08-13 15:09:48 +0000602 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000603 Table *pTab; /* Table being updated */
604 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000605 char *zOld = 0; /* Old column name */
606 char *zNew = 0; /* New column name */
607 const char *zDb; /* Name of schema containing the table */
608 int iSchema; /* Index of the schema */
609 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000610
drh4a2c7472018-08-13 15:09:48 +0000611 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000612 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
613 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000614
615 /* Cannot alter a system table */
dan872165f2018-08-11 17:34:38 +0000616 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000617 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000618
619 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000620 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
621 assert( iSchema>=0 );
622 zDb = db->aDb[iSchema].zDbSName;
623
drh4a2c7472018-08-13 15:09:48 +0000624 /* Make sure the old name really is a column name in the table to be
625 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000626 zOld = sqlite3NameFromToken(db, pOld);
627 if( !zOld ) goto exit_rename_column;
628 for(iCol=0; iCol<pTab->nCol; iCol++){
629 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
630 }
631 if( iCol==pTab->nCol ){
632 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
633 goto exit_rename_column;
634 }
635
drh4a2c7472018-08-13 15:09:48 +0000636 /* Do the rename operation using a recursive UPDATE statement that
637 ** uses the sqlite_rename_column() SQL function to compute the new
638 ** CREATE statement text for the sqlite_master table.
639 */
dancf8f2892018-08-09 20:47:01 +0000640 zNew = sqlite3NameFromToken(db, pNew);
641 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000642 assert( pNew->n>0 );
643 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000644 sqlite3NestedParse(pParse,
645 "UPDATE \"%w\".%s SET "
danb0137382018-08-20 20:01:01 +0000646 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d) "
dan499b8252018-08-17 18:08:28 +0000647 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
648 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000649 zDb, MASTER_NAME,
650 zDb, pTab->zName, iCol, zNew, bQuote,
651 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000652 );
653
dane325ffe2018-08-11 13:40:20 +0000654 /* Drop and reload the database schema. */
dan872165f2018-08-11 17:34:38 +0000655 if( pParse->pVdbe ){
dane325ffe2018-08-11 13:40:20 +0000656 sqlite3ChangeCookie(pParse, iSchema);
657 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iSchema, 0);
658 }
dancf8f2892018-08-09 20:47:01 +0000659
dan0d5fa6b2018-08-24 17:55:49 +0000660 sqlite3NestedParse(pParse,
661 "SELECT 1 "
662 "FROM \"%w\".%s "
663 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
664 " AND sql NOT LIKE 'create virtual%%'"
665 " AND sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, -1)=0 ",
666 zDb, MASTER_NAME,
667 pTab->zName,
668 zDb, pTab->zName, iCol, zNew
669 );
670
dancf8f2892018-08-09 20:47:01 +0000671 exit_rename_column:
672 sqlite3SrcListDelete(db, pSrc);
673 sqlite3DbFree(db, zOld);
674 sqlite3DbFree(db, zNew);
675 return;
676}
677
drh4a2c7472018-08-13 15:09:48 +0000678/*
679** Each RenameToken object maps an element of the parse tree into
680** the token that generated that element. The parse tree element
681** might be one of:
682**
683** * A pointer to an Expr that represents an ID
684** * The name of a table column in Column.zName
685**
686** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000687** Each new object is created by sqlite3RenameTokenMap().
688** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000689** routine is used to keep the mapping current.
690**
691** After the parse finishes, renameTokenFind() routine can be used
692** to look up the actual token value that created some element in
693** the parse tree.
694*/
dancf8f2892018-08-09 20:47:01 +0000695struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000696 void *p; /* Parse tree element created by token t */
697 Token t; /* The token that created parse tree element p */
698 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000699};
700
drh4a2c7472018-08-13 15:09:48 +0000701/*
702** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
703** down into the Walker.
704*/
dan5496d6a2018-08-13 17:14:26 +0000705typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000706struct RenameCtx {
707 RenameToken *pList; /* List of tokens to overwrite */
708 int nList; /* Number of tokens in pList */
709 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000710 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000711 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000712};
713
danc9461ec2018-08-29 21:00:16 +0000714void renameTokenClear(Parse *pParse, void *pPtr){
715 RenameToken *p;
716 assert( pPtr );
717 for(p=pParse->pRename; p; p=p->pNext){
718 if( p->p==pPtr ){
719 p->p = 0;
720 }
721 }
722}
723
drh4a2c7472018-08-13 15:09:48 +0000724/*
725** Add a new RenameToken object mapping parse tree element pPtr into
726** token *pToken to the Parse object currently under construction.
dan07e95232018-08-21 16:32:53 +0000727**
728** Return a copy of pPtr.
drh4a2c7472018-08-13 15:09:48 +0000729*/
dan07e95232018-08-21 16:32:53 +0000730void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000731 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000732 assert( pPtr || pParse->db->mallocFailed );
733
734 renameTokenClear(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000735 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
736 if( pNew ){
737 pNew->p = pPtr;
738 pNew->t = *pToken;
739 pNew->pNext = pParse->pRename;
740 pParse->pRename = pNew;
741 }
danc9461ec2018-08-29 21:00:16 +0000742
dand145e5f2018-08-21 08:29:48 +0000743 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000744}
745
drh4a2c7472018-08-13 15:09:48 +0000746/*
dan07e95232018-08-21 16:32:53 +0000747** It is assumed that there is already a RenameToken object associated
748** with parse tree element pFrom. This function remaps the associated token
749** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000750*/
dan07e95232018-08-21 16:32:53 +0000751void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000752 RenameToken *p;
danc9461ec2018-08-29 21:00:16 +0000753 if( pTo ) renameTokenClear(pParse, pTo);
754 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000755 if( p->p==pFrom ){
756 p->p = pTo;
757 break;
758 }
759 }
dancf8f2892018-08-09 20:47:01 +0000760}
761
drh4a2c7472018-08-13 15:09:48 +0000762/*
763** Free the list of RenameToken objects given in the second argument
764*/
dancf8f2892018-08-09 20:47:01 +0000765static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
766 RenameToken *pNext;
767 RenameToken *p;
768 for(p=pToken; p; p=pNext){
769 pNext = p->pNext;
770 sqlite3DbFree(db, p);
771 }
772}
773
dan987db762018-08-14 20:18:50 +0000774/*
775** Search the Parse object passed as the first argument for a RenameToken
776** object associated with parse tree element pPtr. If found, remove it
777** from the Parse object and add it to the list maintained by the
778** RenameCtx object passed as the second argument.
779*/
780static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000781 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000782 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000783 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
784 if( (*pp)->p==pPtr ){
785 RenameToken *pToken = *pp;
786 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000787 pToken->pNext = pCtx->pList;
788 pCtx->pList = pToken;
789 pCtx->nList++;
790 break;
dancf8f2892018-08-09 20:47:01 +0000791 }
792 }
dancf8f2892018-08-09 20:47:01 +0000793}
794
dan24fedb92018-08-18 17:35:38 +0000795/*
796** This is a Walker select callback. It does nothing. It is only required
797** because without a dummy callback, sqlite3WalkExpr() and similar do not
798** descend into sub-select statements.
799*/
dan987db762018-08-14 20:18:50 +0000800static int renameColumnSelectCb(Walker *pWalker, Select *p){
drh38d99642018-08-18 18:27:18 +0000801 UNUSED_PARAMETER(pWalker);
802 UNUSED_PARAMETER(p);
dan987db762018-08-14 20:18:50 +0000803 return WRC_Continue;
804}
805
dan987db762018-08-14 20:18:50 +0000806/*
807** This is a Walker expression callback.
808**
809** For every TK_COLUMN node in the expression tree, search to see
810** if the column being references is the column being renamed by an
811** ALTER TABLE statement. If it is, then attach its associated
812** RenameToken object to the list of RenameToken objects being
813** constructed in RenameCtx object at pWalker->u.pRename.
814*/
dancf8f2892018-08-09 20:47:01 +0000815static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000816 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000817 if( pExpr->op==TK_TRIGGER
818 && pExpr->iColumn==p->iCol
819 && pWalker->pParse->pTriggerTab==p->pTab
820 ){
dan5be60c52018-08-15 20:28:39 +0000821 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000822 }else if( pExpr->op==TK_COLUMN
823 && pExpr->iColumn==p->iCol
824 && p->pTab==pExpr->pTab
dan987db762018-08-14 20:18:50 +0000825 ){
dan5496d6a2018-08-13 17:14:26 +0000826 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000827 }
828 return WRC_Continue;
829}
830
dan987db762018-08-14 20:18:50 +0000831/*
832** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000833** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000834** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000835** RenameContext. "Last" means the last RenameToken encountered when
836** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000837** return all column name tokens in the order that they are encountered
838** in the SQL statement.
839*/
dan5496d6a2018-08-13 17:14:26 +0000840static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000841 RenameToken *pBest = pCtx->pList;
842 RenameToken *pToken;
843 RenameToken **pp;
844
845 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
846 if( pToken->t.z>pBest->t.z ) pBest = pToken;
847 }
848 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
849 *pp = pBest->pNext;
850
851 return pBest;
852}
853
dan6fe7f232018-08-10 19:19:33 +0000854/*
dan24fedb92018-08-18 17:35:38 +0000855** An error occured while parsing or otherwise processing a database
856** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
857** ALTER TABLE RENAME COLUMN program. The error message emitted by the
858** sub-routine is currently stored in pParse->zErrMsg. This function
859** adds context to the error message and then stores it in pCtx.
860*/
danb0137382018-08-20 20:01:01 +0000861static void renameColumnParseError(
862 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000863 int bPost,
danb0137382018-08-20 20:01:01 +0000864 sqlite3_value *pType,
865 sqlite3_value *pObject,
866 Parse *pParse
867){
drh79a5ee92018-08-23 19:32:04 +0000868 const char *zT = (const char*)sqlite3_value_text(pType);
869 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000870 char *zErr;
danb0137382018-08-20 20:01:01 +0000871
dan0d5fa6b2018-08-24 17:55:49 +0000872 zErr = sqlite3_mprintf("error in %s %s%s: %s",
873 zT, zN, (bPost ? " after rename" : ""),
874 pParse->zErrMsg
875 );
dan24fedb92018-08-18 17:35:38 +0000876 sqlite3_result_error(pCtx, zErr, -1);
877 sqlite3_free(zErr);
878}
879
880/*
dan06249392018-08-21 15:06:59 +0000881** For each name in the the expression-list pEList (i.e. each
882** pEList->a[i].zName) that matches the string in zOld, extract the
883** corresponding rename-token from Parse object pParse and add it
884** to the RenameCtx pCtx.
885*/
886static void renameColumnElistNames(
887 Parse *pParse,
888 RenameCtx *pCtx,
889 ExprList *pEList,
890 const char *zOld
891){
892 if( pEList ){
893 int i;
894 for(i=0; i<pEList->nExpr; i++){
895 char *zName = pEList->a[i].zName;
896 if( 0==sqlite3_stricmp(zName, zOld) ){
897 renameTokenFind(pParse, pCtx, (void*)zName);
898 }
899 }
900 }
901}
902
903/*
904** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
905** that matches the string in zOld, extract the corresponding rename-token
906** from Parse object pParse and add it to the RenameCtx pCtx.
907*/
908static void renameColumnIdlistNames(
909 Parse *pParse,
910 RenameCtx *pCtx,
911 IdList *pIdList,
912 const char *zOld
913){
914 if( pIdList ){
915 int i;
916 for(i=0; i<pIdList->nId; i++){
917 char *zName = pIdList->a[i].zName;
918 if( 0==sqlite3_stricmp(zName, zOld) ){
919 renameTokenFind(pParse, pCtx, (void*)zName);
920 }
921 }
922 }
923}
924
danc9461ec2018-08-29 21:00:16 +0000925static int renameParseSql(
926 Parse *p,
927 const char *zDb,
928 int bTable,
929 sqlite3 *db,
930 const char *zSql,
931 int bTemp
932){
933 int rc;
934 char *zErr = 0;
935
936 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
937
938 /* Parse the SQL statement passed as the first argument. If no error
939 ** occurs and the parse does not result in a new table, index or
940 ** trigger object, the database must be corrupt. */
941 memset(p, 0, sizeof(Parse));
942 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
943 p->db = db;
944 p->nQueryLoop = 1;
945 rc = sqlite3RunParser(p, zSql, &zErr);
946 assert( p->zErrMsg==0 );
947 assert( rc!=SQLITE_OK || zErr==0 );
948 assert( (0!=p->pNewTable) + (0!=p->pNewIndex) + (0!=p->pNewTrigger)<2 );
949 p->zErrMsg = zErr;
950 if( db->mallocFailed ) rc = SQLITE_NOMEM;
951 if( rc==SQLITE_OK
952 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
953 ){
954 rc = SQLITE_CORRUPT_BKPT;
955 }
956
957#ifdef SQLITE_DEBUG
958 /* Ensure that all mappings in the Parse.pRename list really do map to
959 ** a part of the input string. */
960 if( rc==SQLITE_OK ){
961 int nSql = sqlite3Strlen30(zSql);
962 RenameToken *pToken;
963 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
964 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
965 }
966 }
967#endif
968
969 db->init.iDb = 0;
970 return rc;
971}
972
973static int renameEditSql(
974 sqlite3_context *pCtx, /* Return result here */
975 RenameCtx *pRename, /* Rename context */
976 const char *zSql, /* SQL statement to edit */
977 const char *zNew, /* New token text */
978 int bQuote /* True to always quote token */
979){
980 int nNew = sqlite3Strlen30(zNew);
981 int nSql = sqlite3Strlen30(zSql);
982 sqlite3 *db = sqlite3_context_db_handle(pCtx);
983 int rc = SQLITE_OK;
984 char *zQuot;
985 char *zOut;
986 int nQuot;
987
988 /* Set zQuot to point to a buffer containing a quoted copy of the
989 ** identifier zNew. If the corresponding identifier in the original
990 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
991 ** point to zQuot so that all substitutions are made using the
992 ** quoted version of the new column name. */
993 zQuot = sqlite3_mprintf("\"%w\"", zNew);
994 if( zQuot==0 ){
995 return SQLITE_NOMEM;
996 }else{
997 nQuot = sqlite3Strlen30(zQuot);
998 }
999 if( bQuote ){
1000 zNew = zQuot;
1001 nNew = nQuot;
1002 }
1003
1004 /* At this point pRename->pList contains a list of RenameToken objects
1005 ** corresponding to all tokens in the input SQL that must be replaced
1006 ** with the new column name. All that remains is to construct and
1007 ** return the edited SQL string. */
1008 assert( nQuot>=nNew );
1009 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1010 if( zOut ){
1011 int nOut = nSql;
1012 memcpy(zOut, zSql, nSql);
1013 while( pRename->pList ){
1014 int iOff; /* Offset of token to replace in zOut */
1015 RenameToken *pBest = renameColumnTokenNext(pRename);
1016
1017 u32 nReplace;
1018 const char *zReplace;
1019 if( sqlite3IsIdChar(*pBest->t.z) ){
1020 nReplace = nNew;
1021 zReplace = zNew;
1022 }else{
1023 nReplace = nQuot;
1024 zReplace = zQuot;
1025 }
1026
1027 iOff = pBest->t.z - zSql;
1028 if( pBest->t.n!=nReplace ){
1029 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1030 nOut - (iOff + pBest->t.n)
1031 );
1032 nOut += nReplace - pBest->t.n;
1033 zOut[nOut] = '\0';
1034 }
1035 memcpy(&zOut[iOff], zReplace, nReplace);
1036 sqlite3DbFree(db, pBest);
1037 }
1038
1039 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1040 sqlite3DbFree(db, zOut);
1041 }else{
1042 rc = SQLITE_NOMEM;
1043 }
1044
1045 sqlite3_free(zQuot);
1046 return rc;
1047}
1048
1049static int renameResolveTrigger(
1050 Parse *pParse,
1051 const char *zDb
1052){
1053 sqlite3 *db = pParse->db;
1054 TriggerStep *pStep;
1055 NameContext sNC;
1056 int rc = SQLITE_OK;
1057
1058 memset(&sNC, 0, sizeof(sNC));
1059 sNC.pParse = pParse;
1060 pParse->pTriggerTab = sqlite3FindTable(db, pParse->pNewTrigger->table, zDb);
1061 pParse->eTriggerOp = pParse->pNewTrigger->op;
1062
1063 /* Resolve symbols in WHEN clause */
1064 if( pParse->pNewTrigger->pWhen ){
1065 rc = sqlite3ResolveExprNames(&sNC, pParse->pNewTrigger->pWhen);
1066 }
1067
1068 for(pStep=pParse->pNewTrigger->step_list;
1069 rc==SQLITE_OK && pStep;
1070 pStep=pStep->pNext
1071 ){
1072 if( pStep->pSelect ){
1073 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1074 if( pParse->nErr ) rc = pParse->rc;
1075 }
1076 if( rc==SQLITE_OK && pStep->zTarget ){
1077 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1078 if( pTarget==0 ){
1079 rc = SQLITE_ERROR;
1080 }else{
1081 SrcList sSrc;
1082 memset(&sSrc, 0, sizeof(sSrc));
1083 sSrc.nSrc = 1;
1084 sSrc.a[0].zName = pStep->zTarget;
1085 sSrc.a[0].pTab = pTarget;
1086 sNC.pSrcList = &sSrc;
1087 if( pStep->pWhere ){
1088 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1089 }
1090 if( rc==SQLITE_OK ){
1091 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1092 }
1093 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
1094 if( pStep->pUpsert ){
1095 Upsert *pUpsert = pStep->pUpsert;
1096 assert( rc==SQLITE_OK );
1097 pUpsert->pUpsertSrc = &sSrc;
1098 sNC.uNC.pUpsert = pUpsert;
1099 sNC.ncFlags = NC_UUpsert;
1100 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1101 if( rc==SQLITE_OK ){
1102 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1103 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1104 }
1105 if( rc==SQLITE_OK ){
1106 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1107 }
1108 if( rc==SQLITE_OK ){
1109 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1110 }
1111 sNC.ncFlags = 0;
1112 }
1113 }
1114 }
1115 }
1116 return rc;
1117}
1118
1119static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1120 TriggerStep *pStep;
1121
1122 /* Find tokens to edit in WHEN clause */
1123 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1124
1125 /* Find tokens to edit in trigger steps */
1126 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1127 sqlite3WalkSelect(pWalker, pStep->pSelect);
1128 sqlite3WalkExpr(pWalker, pStep->pWhere);
1129 sqlite3WalkExprList(pWalker, pStep->pExprList);
1130 if( pStep->pUpsert ){
1131 Upsert *pUpsert = pStep->pUpsert;
1132 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1133 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1134 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1135 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1136 }
1137 }
1138}
1139
dan06249392018-08-21 15:06:59 +00001140/*
dan987db762018-08-14 20:18:50 +00001141** SQL function:
1142**
1143** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1144**
1145** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001146** 1. type: Type of object ("table", "view" etc.)
1147** 2. object: Name of object
1148** 3. Database: Database name (e.g. "main")
1149** 4. Table: Table name
1150** 5. iCol: Index of column to rename
1151** 6. zNew: New column name
dan0d5fa6b2018-08-24 17:55:49 +00001152** 7. bQuote: Non-zero if the new column name should be quoted. Negative
1153** if this function is being called to check that the schema
1154** can still be parsed and symbols resolved after the column
1155** has been renamed.
dan987db762018-08-14 20:18:50 +00001156**
1157** Do a column rename operation on the CREATE statement given in zSql.
1158** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1159** into zNew. The name should be quoted if bQuote is true.
1160**
1161** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1162** Though accessible to application code, it is not intended for use by
1163** applications. The existance of this function, and the way it works,
1164** is subject to change without notice.
1165**
1166** If any of the parameters are out-of-bounds, then simply return NULL.
1167** An out-of-bounds parameter can only occur when the application calls
1168** this function directly. The parameters will always be well-formed when
1169** this routine is invoked by the bytecode for a legitimate ALTER TABLE
1170** statement.
dan6fe7f232018-08-10 19:19:33 +00001171*/
dancf8f2892018-08-09 20:47:01 +00001172static void renameColumnFunc(
1173 sqlite3_context *context,
1174 int NotUsed,
1175 sqlite3_value **argv
1176){
1177 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001178 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001179 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
dancf8f2892018-08-09 20:47:01 +00001180 int nSql = sqlite3_value_bytes(argv[0]);
danb0137382018-08-20 20:01:01 +00001181 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1182 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1183 int iCol = sqlite3_value_int(argv[5]);
1184 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
1185 int nNew = sqlite3_value_bytes(argv[6]);
1186 int bQuote = sqlite3_value_int(argv[7]);
dan987db762018-08-14 20:18:50 +00001187 const char *zOld;
danc9461ec2018-08-29 21:00:16 +00001188 int bTemp = 0;
dan6fe7f232018-08-10 19:19:33 +00001189
dancf8f2892018-08-09 20:47:01 +00001190 int rc;
1191 char *zErr = 0;
1192 Parse sParse;
1193 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001194 Index *pIdx;
1195 char *zOut = 0;
1196
dancf8f2892018-08-09 20:47:01 +00001197 int i;
dan987db762018-08-14 20:18:50 +00001198 Table *pTab;
dancf8f2892018-08-09 20:47:01 +00001199
drh38d99642018-08-18 18:27:18 +00001200 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001201 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001202 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001203 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001204 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001205 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001206 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001207 if( pTab==0 || iCol>=pTab->nCol ){
1208 sqlite3BtreeLeaveAll(db);
1209 return;
1210 }
dan987db762018-08-14 20:18:50 +00001211 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001212 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001213 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001214
danc9461ec2018-08-29 21:00:16 +00001215 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001216
dancf8f2892018-08-09 20:47:01 +00001217 /* Find tokens that need to be replaced. */
1218 memset(&sWalker, 0, sizeof(Walker));
1219 sWalker.pParse = &sParse;
1220 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001221 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001222 sWalker.u.pRename = &sCtx;
1223
dan0cbb0b12018-08-16 19:49:16 +00001224 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001225 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001226 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001227 Select *pSelect = sParse.pNewTable->pSelect;
1228 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001229 sParse.rc = SQLITE_OK;
1230 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1231 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1232 if( rc==SQLITE_OK ){
1233 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001234 }
dan987db762018-08-14 20:18:50 +00001235 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1236 }else{
1237 /* A regular table */
1238 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1239 FKey *pFKey;
1240 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001241 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001242 if( bFKOnly==0 ){
1243 renameTokenFind(
1244 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1245 );
1246 if( sCtx.iCol<0 ){
1247 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001248 }
dan987db762018-08-14 20:18:50 +00001249 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1250 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1251 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1252 }
1253 }
1254
1255 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1256 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001257 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001258 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1259 }
1260 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1261 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1262 ){
1263 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1264 }
dan6fe7f232018-08-10 19:19:33 +00001265 }
dancf8f2892018-08-09 20:47:01 +00001266 }
1267 }
dan5496d6a2018-08-13 17:14:26 +00001268 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001269 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1270 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001271 }else{
dan5be60c52018-08-15 20:28:39 +00001272 /* A trigger */
1273 TriggerStep *pStep;
danc9461ec2018-08-29 21:00:16 +00001274 rc = renameResolveTrigger(&sParse, zDb);
1275 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001276
danc9461ec2018-08-29 21:00:16 +00001277 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1278 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001279 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001280 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001281 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001282 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1283 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001284 }
danc9461ec2018-08-29 21:00:16 +00001285 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1286 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001287 }
1288 }
1289 }
1290
dan5be60c52018-08-15 20:28:39 +00001291
1292 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001293 if( sParse.pTriggerTab==pTab ){
1294 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001295 }
dan5be60c52018-08-15 20:28:39 +00001296
danc9461ec2018-08-29 21:00:16 +00001297 /* Find tokens to edit in various expressions and selects */
1298 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001299 }
1300
dan987db762018-08-14 20:18:50 +00001301 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001302 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001303
drh5fc22cd2018-08-13 13:43:11 +00001304renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001305 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001306 if( sParse.zErrMsg ){
dan0d5fa6b2018-08-24 17:55:49 +00001307 renameColumnParseError(context, (bQuote<0), argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001308 }else{
1309 sqlite3_result_error_code(context, rc);
1310 }
1311 }
1312
dancf8f2892018-08-09 20:47:01 +00001313 if( sParse.pVdbe ){
1314 sqlite3VdbeFinalize(sParse.pVdbe);
1315 }
1316 sqlite3DeleteTable(db, sParse.pNewTable);
1317 if( sParse.pNewIndex ) sqlite3FreeIndex(db, sParse.pNewIndex);
dan5496d6a2018-08-13 17:14:26 +00001318 sqlite3DeleteTrigger(db, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001319 renameTokenFree(db, sParse.pRename);
drh4a2c7472018-08-13 15:09:48 +00001320 renameTokenFree(db, sCtx.pList);
dan24fedb92018-08-18 17:35:38 +00001321 sqlite3DbFree(db, sParse.zErrMsg);
dancf8f2892018-08-09 20:47:01 +00001322 sqlite3ParserReset(&sParse);
drhda76adc2018-08-25 02:04:05 +00001323 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001324}
1325
danc9461ec2018-08-29 21:00:16 +00001326static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1327 RenameCtx *p = pWalker->u.pRename;
1328 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->pTab ){
1329 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->pTab);
1330 }
1331 return WRC_Continue;
1332}
1333
1334/*
1335** This is a Walker select callback.
1336*/
1337static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1338 int i;
1339 RenameCtx *p = pWalker->u.pRename;
1340 SrcList *pSrc = pSelect->pSrc;
1341 for(i=0; i<pSrc->nSrc; i++){
1342 struct SrcList_item *pItem = &pSrc->a[i];
1343 if( pItem->pTab==p->pTab ){
1344 renameTokenFind(pWalker->pParse, p, pItem->zName);
1345 }
1346 }
1347
1348 return WRC_Continue;
1349}
1350
1351
1352/*
1353** This C function implements an SQL user function that is used by SQL code
1354** generated by the ALTER TABLE ... RENAME command to modify the definition
1355** of any foreign key constraints that use the table being renamed as the
1356** parent table. It is passed three arguments:
1357**
1358** 1) The complete text of the CREATE TABLE statement being modified,
1359** 2) The old name of the table being renamed, and
1360** 3) The new name of the table being renamed.
1361**
1362** It returns the new CREATE TABLE statement. For example:
1363**
1364** sqlite_rename_table('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
1365** -> 'CREATE TABLE t1(a REFERENCES t3)'
1366*/
1367static void renameTableFunc(
1368 sqlite3_context *context,
1369 int NotUsed,
1370 sqlite3_value **argv
1371){
1372 sqlite3 *db = sqlite3_context_db_handle(context);
1373 char *zOutput = 0;
1374 char *zResult;
1375 unsigned char const *zDb = sqlite3_value_text(argv[0]);
1376 unsigned char const *zInput = sqlite3_value_text(argv[1]);
1377 unsigned char const *zOld = sqlite3_value_text(argv[2]);
1378 unsigned char const *zNew = sqlite3_value_text(argv[3]);
1379 int bTemp = sqlite3_value_int(argv[4]);
1380
1381 unsigned const char *z; /* Pointer to token */
1382 int n; /* Length of token z */
1383 int token; /* Type of token */
1384
1385 Parse sParse;
1386 int rc;
1387 int bQuote = 1;
1388 RenameCtx sCtx;
1389 Walker sWalker;
1390
1391 if( zInput==0 || zOld==0 || zNew==0 ) return;
1392
1393 memset(&sCtx, 0, sizeof(RenameCtx));
1394 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1395 memset(&sWalker, 0, sizeof(Walker));
1396 sWalker.pParse = &sParse;
1397 sWalker.xExprCallback = renameTableExprCb;
1398 sWalker.xSelectCallback = renameTableSelectCb;
1399 sWalker.u.pRename = &sCtx;
1400
1401 sqlite3BtreeEnterAll(db);
1402
1403 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1404
1405 if( rc==SQLITE_OK ){
1406 if( sParse.pNewTable ){
1407 Table *pTab = sParse.pNewTable;
1408
1409 if( pTab->pSelect ){
1410 NameContext sNC;
1411 memset(&sNC, 0, sizeof(sNC));
1412 sNC.pParse = &sParse;
1413
1414 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1415 if( sParse.nErr ) rc = sParse.rc;
1416 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1417 }else{
1418 /* Modify any FK definitions to point to the new table. */
1419#ifndef SQLITE_OMIT_FOREIGN_KEY
1420 FKey *pFKey;
1421 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1422 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1423 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1424 }
1425 }
1426#endif
1427
1428 /* If this is the table being altered, fix any table refs in CHECK
1429 ** expressions. Also update the name that appears right after the
1430 ** "CREATE [VIRTUAL] TABLE" bit. */
1431 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1432 sCtx.pTab = pTab;
1433 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1434 renameTokenFind(&sParse, &sCtx, pTab->zName);
1435 }
1436 }
1437 }
1438
1439 else if( sParse.pNewIndex ){
1440 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1441 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1442 }
1443
1444#ifndef SQLITE_OMIT_TRIGGER
1445 else if( sParse.pNewTrigger ){
1446 Trigger *pTrigger = sParse.pNewTrigger;
1447 TriggerStep *pStep;
1448 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1449 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1450 ){
1451 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1452 }
1453
1454 rc = renameResolveTrigger(&sParse, zDb);
1455 if( rc==SQLITE_OK ){
1456 renameWalkTrigger(&sWalker, pTrigger);
1457 }
1458
1459 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1460 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1461 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1462 }
1463 }
1464 }
1465#endif
1466 }
1467
1468 if( rc==SQLITE_OK ){
1469 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1470 }
1471
1472 if( rc!=SQLITE_OK ){
1473 sqlite3_result_error_code(context, rc);
1474 }
1475 if( sParse.pVdbe ){
1476 sqlite3VdbeFinalize(sParse.pVdbe);
1477 }
1478 sqlite3DeleteTable(db, sParse.pNewTable);
1479 if( sParse.pNewIndex ) sqlite3FreeIndex(db, sParse.pNewIndex);
1480 sqlite3DeleteTrigger(db, sParse.pNewTrigger);
1481 renameTokenFree(db, sParse.pRename);
1482 renameTokenFree(db, sCtx.pList);
1483 sqlite3DbFree(db, sParse.zErrMsg);
1484 sqlite3ParserReset(&sParse);
1485 sqlite3BtreeLeaveAll(db);
1486
1487 return;
1488}
1489
dancf8f2892018-08-09 20:47:01 +00001490/*
1491** Register built-in functions used to help implement ALTER TABLE
1492*/
1493void sqlite3AlterFunctions(void){
1494 static FuncDef aAlterTableFuncs[] = {
dan06249392018-08-21 15:06:59 +00001495 FUNCTION(sqlite_rename_column, 8, 0, 0, renameColumnFunc),
danc9461ec2018-08-29 21:00:16 +00001496 FUNCTION(sqlite_rename_table, 5, 0, 0, renameTableFunc),
dancf8f2892018-08-09 20:47:01 +00001497 };
1498 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1499}
drhd0e4a6c2005-02-15 20:47:57 +00001500#endif /* SQLITE_ALTER_TABLE */