blob: 12885fd0e4145a5fb33466a827f04c102a40933f [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
23
24/*
25** This function is used by SQL generated to implement the
26** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
27** CREATE INDEX command. The second is a table name. The table name in
drhf11c34d2006-09-08 12:27:36 +000028** the CREATE TABLE or CREATE INDEX statement is replaced with the third
drh1f01ec12005-02-15 21:36:18 +000029** argument and the result returned. Examples:
30**
31** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
32** -> 'CREATE TABLE def(a, b, c)'
33**
34** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
35** -> 'CREATE INDEX i ON def(a, b, c)'
36*/
37static void renameTableFunc(
38 sqlite3_context *context,
danielk197762c14b32008-11-19 09:05:26 +000039 int NotUsed,
drh1f01ec12005-02-15 21:36:18 +000040 sqlite3_value **argv
41){
42 unsigned char const *zSql = sqlite3_value_text(argv[0]);
43 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
44
45 int token;
46 Token tname;
drh2646da72005-12-09 20:02:05 +000047 unsigned char const *zCsr = zSql;
drh1f01ec12005-02-15 21:36:18 +000048 int len = 0;
49 char *zRet;
50
drhfa4a4b92008-03-19 21:45:51 +000051 sqlite3 *db = sqlite3_context_db_handle(context);
danielk19771e536952007-08-16 10:09:01 +000052
danielk197762c14b32008-11-19 09:05:26 +000053 UNUSED_PARAMETER(NotUsed);
54
drh1f01ec12005-02-15 21:36:18 +000055 /* The principle used to locate the table name in the CREATE TABLE
drh73829452008-05-09 14:17:51 +000056 ** statement is that the table name is the first non-space token that
drh6aa1edc2008-07-07 12:44:58 +000057 ** is immediately followed by a TK_LP or TK_USING token.
drh1f01ec12005-02-15 21:36:18 +000058 */
59 if( zSql ){
60 do {
danielk1977dce872b2007-05-08 12:37:45 +000061 if( !*zCsr ){
62 /* Ran out of input before finding an opening bracket. Return NULL. */
63 return;
64 }
65
drh1f01ec12005-02-15 21:36:18 +000066 /* Store the token that zCsr points to in tname. */
drhb7916a72009-05-27 10:31:29 +000067 tname.z = (char*)zCsr;
drh1f01ec12005-02-15 21:36:18 +000068 tname.n = len;
69
70 /* Advance zCsr to the next token. Store that token type in 'token',
drh85b623f2007-12-13 21:54:09 +000071 ** and its length in 'len' (to be used next iteration of this loop).
drh1f01ec12005-02-15 21:36:18 +000072 */
73 do {
74 zCsr += len;
75 len = sqlite3GetToken(zCsr, &token);
drh200a81d2008-08-08 14:19:41 +000076 } while( token==TK_SPACE );
dan2b5f1522018-06-30 20:00:35 +000077 assert( len>0 || !*zCsr );
danielk1977182c4ba2007-06-27 15:53:34 +000078 } while( token!=TK_LP && token!=TK_USING );
drh1f01ec12005-02-15 21:36:18 +000079
drh4300c1a2014-02-20 19:23:15 +000080 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
81 zSql, zTableName, tname.z+tname.n);
drh633e6d52008-07-28 19:34:53 +000082 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
drh1f01ec12005-02-15 21:36:18 +000083 }
84}
85
dan432cc5b2009-09-26 17:51:48 +000086/*
87** This C function implements an SQL user function that is used by SQL code
88** generated by the ALTER TABLE ... RENAME command to modify the definition
89** of any foreign key constraints that use the table being renamed as the
90** parent table. It is passed three arguments:
91**
92** 1) The complete text of the CREATE TABLE statement being modified,
93** 2) The old name of the table being renamed, and
94** 3) The new name of the table being renamed.
95**
96** It returns the new CREATE TABLE statement. For example:
97**
98** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
99** -> 'CREATE TABLE t1(a REFERENCES t3)'
100*/
101#ifndef SQLITE_OMIT_FOREIGN_KEY
102static void renameParentFunc(
103 sqlite3_context *context,
104 int NotUsed,
105 sqlite3_value **argv
106){
107 sqlite3 *db = sqlite3_context_db_handle(context);
108 char *zOutput = 0;
109 char *zResult;
110 unsigned char const *zInput = sqlite3_value_text(argv[0]);
111 unsigned char const *zOld = sqlite3_value_text(argv[1]);
112 unsigned char const *zNew = sqlite3_value_text(argv[2]);
113
114 unsigned const char *z; /* Pointer to token */
115 int n; /* Length of token z */
116 int token; /* Type of token */
117
drhd3ceeb52009-10-13 13:08:19 +0000118 UNUSED_PARAMETER(NotUsed);
drh65b9ac52014-04-14 19:48:25 +0000119 if( zInput==0 || zOld==0 ) return;
dan432cc5b2009-09-26 17:51:48 +0000120 for(z=zInput; *z; z=z+n){
121 n = sqlite3GetToken(z, &token);
122 if( token==TK_REFERENCES ){
123 char *zParent;
124 do {
125 z += n;
126 n = sqlite3GetToken(z, &token);
127 }while( token==TK_SPACE );
128
dand68d1f42015-04-28 14:07:02 +0000129 if( token==TK_ILLEGAL ) break;
dan432cc5b2009-09-26 17:51:48 +0000130 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
drha172c342009-10-08 01:43:55 +0000131 if( zParent==0 ) break;
dan432cc5b2009-09-26 17:51:48 +0000132 sqlite3Dequote(zParent);
133 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
134 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
drh4300c1a2014-02-20 19:23:15 +0000135 (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
dan432cc5b2009-09-26 17:51:48 +0000136 );
137 sqlite3DbFree(db, zOutput);
138 zOutput = zOut;
139 zInput = &z[n];
140 }
141 sqlite3DbFree(db, zParent);
142 }
143 }
144
drhdf125952018-06-06 23:31:26 +0000145 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput);
dan432cc5b2009-09-26 17:51:48 +0000146 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
147 sqlite3DbFree(db, zOutput);
148}
149#endif
150
drh1f01ec12005-02-15 21:36:18 +0000151#ifndef SQLITE_OMIT_TRIGGER
drhf11c34d2006-09-08 12:27:36 +0000152/* This function is used by SQL generated to implement the
drh1f01ec12005-02-15 21:36:18 +0000153** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
154** statement. The second is a table name. The table name in the CREATE
drhf11c34d2006-09-08 12:27:36 +0000155** TRIGGER statement is replaced with the third argument and the result
drh1f01ec12005-02-15 21:36:18 +0000156** returned. This is analagous to renameTableFunc() above, except for CREATE
157** TRIGGER, not CREATE INDEX and CREATE TABLE.
158*/
159static void renameTriggerFunc(
160 sqlite3_context *context,
danielk197762c14b32008-11-19 09:05:26 +0000161 int NotUsed,
drh1f01ec12005-02-15 21:36:18 +0000162 sqlite3_value **argv
163){
164 unsigned char const *zSql = sqlite3_value_text(argv[0]);
165 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
166
167 int token;
168 Token tname;
169 int dist = 3;
drh2646da72005-12-09 20:02:05 +0000170 unsigned char const *zCsr = zSql;
drh1f01ec12005-02-15 21:36:18 +0000171 int len = 0;
172 char *zRet;
drhfa4a4b92008-03-19 21:45:51 +0000173 sqlite3 *db = sqlite3_context_db_handle(context);
danielk19771e536952007-08-16 10:09:01 +0000174
danielk197762c14b32008-11-19 09:05:26 +0000175 UNUSED_PARAMETER(NotUsed);
176
drh1f01ec12005-02-15 21:36:18 +0000177 /* The principle used to locate the table name in the CREATE TRIGGER
peter.d.reid60ec9142014-09-06 16:39:46 +0000178 ** statement is that the table name is the first token that is immediately
179 ** preceded by either TK_ON or TK_DOT and immediately followed by one
drh1f01ec12005-02-15 21:36:18 +0000180 ** of TK_WHEN, TK_BEGIN or TK_FOR.
181 */
182 if( zSql ){
183 do {
danielk1977dce872b2007-05-08 12:37:45 +0000184
185 if( !*zCsr ){
186 /* Ran out of input before finding the table name. Return NULL. */
187 return;
188 }
189
drh1f01ec12005-02-15 21:36:18 +0000190 /* Store the token that zCsr points to in tname. */
drhb7916a72009-05-27 10:31:29 +0000191 tname.z = (char*)zCsr;
drh1f01ec12005-02-15 21:36:18 +0000192 tname.n = len;
193
194 /* Advance zCsr to the next token. Store that token type in 'token',
drh85b623f2007-12-13 21:54:09 +0000195 ** and its length in 'len' (to be used next iteration of this loop).
drh1f01ec12005-02-15 21:36:18 +0000196 */
197 do {
198 zCsr += len;
199 len = sqlite3GetToken(zCsr, &token);
200 }while( token==TK_SPACE );
dan2b5f1522018-06-30 20:00:35 +0000201 assert( len>0 || !*zCsr );
drh1f01ec12005-02-15 21:36:18 +0000202
203 /* Variable 'dist' stores the number of tokens read since the most
204 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
205 ** token is read and 'dist' equals 2, the condition stated above
206 ** to be met.
207 **
208 ** Note that ON cannot be a database, table or column name, so
209 ** there is no need to worry about syntax like
210 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
211 */
212 dist++;
213 if( token==TK_DOT || token==TK_ON ){
214 dist = 0;
215 }
216 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
217
218 /* Variable tname now contains the token that is the old table-name
219 ** in the CREATE TRIGGER statement.
220 */
drh4300c1a2014-02-20 19:23:15 +0000221 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
222 zSql, zTableName, tname.z+tname.n);
drh633e6d52008-07-28 19:34:53 +0000223 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
drh1f01ec12005-02-15 21:36:18 +0000224 }
225}
226#endif /* !SQLITE_OMIT_TRIGGER */
227
228/*
dan432cc5b2009-09-26 17:51:48 +0000229** This function is used to create the text of expressions of the form:
230**
231** name=<constant1> OR name=<constant2> OR ...
232**
233** If argument zWhere is NULL, then a pointer string containing the text
234** "name=<constant>" is returned, where <constant> is the quoted version
235** of the string passed as argument zConstant. The returned buffer is
236** allocated using sqlite3DbMalloc(). It is the responsibility of the
237** caller to ensure that it is eventually freed.
238**
239** If argument zWhere is not NULL, then the string returned is
240** "<where> OR name=<constant>", where <where> is the contents of zWhere.
241** In this case zWhere is passed to sqlite3DbFree() before returning.
242**
243*/
244static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
245 char *zNew;
246 if( !zWhere ){
247 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
248 }else{
249 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
250 sqlite3DbFree(db, zWhere);
251 }
252 return zNew;
253}
254
dan856ef1a2009-09-29 06:33:23 +0000255#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000256/*
257** Generate the text of a WHERE expression which can be used to select all
258** tables that have foreign key constraints that refer to table pTab (i.e.
259** constraints for which pTab is the parent table) from the sqlite_master
260** table.
261*/
262static char *whereForeignKeys(Parse *pParse, Table *pTab){
263 FKey *p;
264 char *zWhere = 0;
265 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
266 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
267 }
268 return zWhere;
drh1f01ec12005-02-15 21:36:18 +0000269}
dan856ef1a2009-09-29 06:33:23 +0000270#endif
drh1f01ec12005-02-15 21:36:18 +0000271
drhd0e4a6c2005-02-15 20:47:57 +0000272/*
danielk197719a8e7e2005-03-17 05:03:38 +0000273** Generate the text of a WHERE expression which can be used to select all
274** temporary triggers on table pTab from the sqlite_temp_master table. If
275** table pTab has no temporary triggers, or is itself stored in the
276** temporary database, NULL is returned.
277*/
278static char *whereTempTriggers(Parse *pParse, Table *pTab){
279 Trigger *pTrig;
280 char *zWhere = 0;
danielk1977e501b892006-01-09 06:29:47 +0000281 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
danielk1977da184232006-01-05 11:34:32 +0000282
283 /* If the table is not located in the temp-db (in which case NULL is
284 ** returned, loop through the tables list of triggers. For each trigger
285 ** that is not part of the temp-db schema, add a clause to the WHERE
286 ** expression being built up in zWhere.
287 */
288 if( pTab->pSchema!=pTempSchema ){
danielk19771e536952007-08-16 10:09:01 +0000289 sqlite3 *db = pParse->db;
danielk19772f886d12009-02-28 10:47:41 +0000290 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000291 if( pTrig->pSchema==pTempSchema ){
dan432cc5b2009-09-26 17:51:48 +0000292 zWhere = whereOrName(db, zWhere, pTrig->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000293 }
294 }
295 }
dan39f1bcb2010-09-29 07:16:46 +0000296 if( zWhere ){
297 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
298 sqlite3DbFree(pParse->db, zWhere);
299 zWhere = zNew;
300 }
danielk197719a8e7e2005-03-17 05:03:38 +0000301 return zWhere;
302}
303
304/*
305** Generate code to drop and reload the internal representation of table
306** pTab from the database, including triggers and temporary triggers.
307** Argument zName is the name of the table in the database schema at
308** the time the generated code is executed. This can be different from
309** pTab->zName if this function is being called to code part of an
310** "ALTER TABLE RENAME TO" statement.
311*/
312static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
313 Vdbe *v;
314 char *zWhere;
danielk1977da184232006-01-05 11:34:32 +0000315 int iDb; /* Index of database containing pTab */
danielk197719a8e7e2005-03-17 05:03:38 +0000316#ifndef SQLITE_OMIT_TRIGGER
317 Trigger *pTrig;
318#endif
319
320 v = sqlite3GetVdbe(pParse);
drhd3264c72009-04-15 13:39:47 +0000321 if( NEVER(v==0) ) return;
drh1fee73e2007-08-29 04:00:57 +0000322 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +0000323 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
324 assert( iDb>=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000325
326#ifndef SQLITE_OMIT_TRIGGER
327 /* Drop any table triggers from the internal schema. */
danielk19772f886d12009-02-28 10:47:41 +0000328 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000329 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
330 assert( iTrigDb==iDb || iTrigDb==1 );
dan165921a2009-08-28 18:53:45 +0000331 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000332 }
333#endif
334
dan432cc5b2009-09-26 17:51:48 +0000335 /* Drop the table and index from the internal schema. */
drh66a51672008-01-03 00:01:23 +0000336 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000337
338 /* Reload the table, index and permanent trigger schemas. */
danielk19771e536952007-08-16 10:09:01 +0000339 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000340 if( !zWhere ) return;
drh5d9c9da2011-06-03 20:11:17 +0000341 sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
danielk197719a8e7e2005-03-17 05:03:38 +0000342
343#ifndef SQLITE_OMIT_TRIGGER
344 /* Now, if the table is not stored in the temp database, reload any temp
345 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
346 */
drhd9cb6ac2005-10-20 07:28:17 +0000347 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
drh5d9c9da2011-06-03 20:11:17 +0000348 sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
danielk197719a8e7e2005-03-17 05:03:38 +0000349 }
350#endif
351}
352
353/*
danbe535002011-04-01 15:15:58 +0000354** Parameter zName is the name of a table that is about to be altered
355** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
356** If the table is a system table, this function leaves an error message
357** in pParse->zErr (system tables may not be altered) and returns non-zero.
358**
359** Or, if zName is not a system table, zero is returned.
360*/
361static int isSystemTable(Parse *pParse, const char *zName){
drh59a386e2017-06-28 01:12:53 +0000362 if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danbe535002011-04-01 15:15:58 +0000363 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
364 return 1;
365 }
366 return 0;
367}
368
369/*
drhd0e4a6c2005-02-15 20:47:57 +0000370** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
371** command.
372*/
373void sqlite3AlterRenameTable(
374 Parse *pParse, /* Parser context. */
375 SrcList *pSrc, /* The table to rename. */
376 Token *pName /* The new table name. */
377){
378 int iDb; /* Database that contains the table */
379 char *zDb; /* Name of database iDb */
380 Table *pTab; /* Table being renamed */
381 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000382 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000383 int nTabName; /* Number of UTF-8 characters in zTabName */
384 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000385 Vdbe *v;
386#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000387 char *zWhere = 0; /* Where clause to locate temp triggers */
drhd0e4a6c2005-02-15 20:47:57 +0000388#endif
danielk1977595a5232009-07-24 17:58:53 +0000389 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000390 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000391
drh8257aa82017-07-26 19:59:13 +0000392 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000393 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000394 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000395 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000396
dan41fb5cd2012-10-04 19:33:00 +0000397 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000398 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000399 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000400 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000401 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000402
403 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000404 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000405 if( !zName ) goto exit_rename_table;
406
407 /* Check that a table or index named 'zName' does not already exist
408 ** in database iDb. If so, this is an error.
409 */
410 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
411 sqlite3ErrorMsg(pParse,
412 "there is already another table or index with this name: %s", zName);
413 goto exit_rename_table;
414 }
415
416 /* Make sure it is not a system table being altered, or a reserved name
417 ** that the table is being renamed to.
418 */
danbe535002011-04-01 15:15:58 +0000419 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
drhd0e4a6c2005-02-15 20:47:57 +0000420 goto exit_rename_table;
421 }
danbe535002011-04-01 15:15:58 +0000422 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
423 exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000424 }
425
danielk197761116ae2007-12-13 08:15:30 +0000426#ifndef SQLITE_OMIT_VIEW
427 if( pTab->pSelect ){
428 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
429 goto exit_rename_table;
430 }
431#endif
432
drhd0e4a6c2005-02-15 20:47:57 +0000433#ifndef SQLITE_OMIT_AUTHORIZATION
434 /* Invoke the authorization callback. */
435 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
436 goto exit_rename_table;
437 }
438#endif
439
danielk1977182c4ba2007-06-27 15:53:34 +0000440#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000441 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
442 goto exit_rename_table;
443 }
danielk1977595a5232009-07-24 17:58:53 +0000444 if( IsVirtual(pTab) ){
445 pVTab = sqlite3GetVTable(db, pTab);
446 if( pVTab->pVtab->pModule->xRename==0 ){
447 pVTab = 0;
448 }
danielk1977182c4ba2007-06-27 15:53:34 +0000449 }
450#endif
451
drhb22f7c82014-02-06 23:56:27 +0000452 /* Begin a transaction for database iDb.
drhd0e4a6c2005-02-15 20:47:57 +0000453 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000454 ** schema). Open a statement transaction if the table is a virtual
455 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000456 */
457 v = sqlite3GetVdbe(pParse);
458 if( v==0 ){
459 goto exit_rename_table;
460 }
danielk1977595a5232009-07-24 17:58:53 +0000461 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
drh9cbf3422008-01-17 16:22:13 +0000462 sqlite3ChangeCookie(pParse, iDb);
drhd0e4a6c2005-02-15 20:47:57 +0000463
danielk1977182c4ba2007-06-27 15:53:34 +0000464 /* If this is a virtual table, invoke the xRename() function if
465 ** one is defined. The xRename() callback will modify the names
466 ** of any resources used by the v-table implementation (including other
467 ** SQLite tables) that are identified by the name of the virtual table.
468 */
469#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000470 if( pVTab ){
danielk1977a29f18c2008-01-04 11:01:03 +0000471 int i = ++pParse->nMem;
drh076e85f2015-09-03 13:46:12 +0000472 sqlite3VdbeLoadString(v, i, zName);
danielk1977595a5232009-07-24 17:58:53 +0000473 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dane0af83a2009-09-08 19:15:01 +0000474 sqlite3MayAbort(pParse);
danielk1977182c4ba2007-06-27 15:53:34 +0000475 }
476#endif
477
drh4e5dd852007-05-15 03:56:49 +0000478 /* figure out how many UTF-8 characters are in zName */
479 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000480 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000481
dan856ef1a2009-09-29 06:33:23 +0000482#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000483 if( db->flags&SQLITE_ForeignKeys ){
484 /* If foreign-key support is enabled, rewrite the CREATE TABLE
485 ** statements corresponding to all child tables of foreign key constraints
486 ** for which the renamed table is the parent table. */
487 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
488 sqlite3NestedParse(pParse,
drh9a6ffc82010-02-15 18:03:20 +0000489 "UPDATE \"%w\".%s SET "
dan432cc5b2009-09-26 17:51:48 +0000490 "sql = sqlite_rename_parent(sql, %Q, %Q) "
drhe0a04a32016-12-16 01:00:21 +0000491 "WHERE %s;", zDb, MASTER_NAME, zTabName, zName, zWhere);
dan432cc5b2009-09-26 17:51:48 +0000492 sqlite3DbFree(db, zWhere);
493 }
494 }
495#endif
496
drhd0e4a6c2005-02-15 20:47:57 +0000497 /* Modify the sqlite_master table to use the new table name. */
498 sqlite3NestedParse(pParse,
499 "UPDATE %Q.%s SET "
500#ifdef SQLITE_OMIT_TRIGGER
501 "sql = sqlite_rename_table(sql, %Q), "
502#else
503 "sql = CASE "
504 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
505 "ELSE sqlite_rename_table(sql, %Q) END, "
506#endif
507 "tbl_name = %Q, "
508 "name = CASE "
509 "WHEN type='table' THEN %Q "
510 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000511 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000512 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000513 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000514 "(type='table' OR type='index' OR type='trigger');",
drhe0a04a32016-12-16 01:00:21 +0000515 zDb, MASTER_NAME, zName, zName, zName,
drhd0e4a6c2005-02-15 20:47:57 +0000516#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000517 zName,
drhd0e4a6c2005-02-15 20:47:57 +0000518#endif
drh4e5dd852007-05-15 03:56:49 +0000519 zName, nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000520 );
521
522#ifndef SQLITE_OMIT_AUTOINCREMENT
523 /* If the sqlite_sequence table exists in this database, then update
524 ** it with the new table name.
525 */
526 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
527 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000528 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000529 zDb, zName, pTab->zName);
530 }
531#endif
532
533#ifndef SQLITE_OMIT_TRIGGER
534 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
535 ** table. Don't do this if the table being ALTERed is itself located in
536 ** the temp database.
537 */
drhd9cb6ac2005-10-20 07:28:17 +0000538 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000539 sqlite3NestedParse(pParse,
540 "UPDATE sqlite_temp_master SET "
541 "sql = sqlite_rename_trigger(sql, %Q), "
542 "tbl_name = %Q "
543 "WHERE %s;", zName, zName, zWhere);
drh633e6d52008-07-28 19:34:53 +0000544 sqlite3DbFree(db, zWhere);
drhd0e4a6c2005-02-15 20:47:57 +0000545 }
546#endif
547
dan856ef1a2009-09-29 06:33:23 +0000548#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000549 if( db->flags&SQLITE_ForeignKeys ){
550 FKey *p;
551 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
552 Table *pFrom = p->pFrom;
553 if( pFrom!=pTab ){
554 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
555 }
556 }
557 }
558#endif
559
danielk197719a8e7e2005-03-17 05:03:38 +0000560 /* Drop and reload the internal table schema. */
561 reloadTableSchema(pParse, pTab, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000562
563exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000564 sqlite3SrcListDelete(db, pSrc);
565 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000566 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000567}
danielk197719a8e7e2005-03-17 05:03:38 +0000568
drhd3001712009-05-12 17:46:53 +0000569/*
danielk197719a8e7e2005-03-17 05:03:38 +0000570** This function is called after an "ALTER TABLE ... ADD" statement
571** has been parsed. Argument pColDef contains the text of the new
572** column definition.
573**
574** The Table structure pParse->pNewTable was extended to include
575** the new column during parsing.
576*/
577void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
578 Table *pNew; /* Copy of pParse->pNewTable */
579 Table *pTab; /* Table being altered */
580 int iDb; /* Database number */
581 const char *zDb; /* Database name */
582 const char *zTab; /* Table name */
583 char *zCol; /* Null-terminated column definition */
584 Column *pCol; /* The new column */
585 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000586 sqlite3 *db; /* The database connection; */
drhbbde0182016-02-09 16:09:22 +0000587 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000588 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000589
danielk1977f150c9d2008-10-30 17:21:12 +0000590 db = pParse->db;
591 if( pParse->nErr || db->mallocFailed ) return;
drhbbde0182016-02-09 16:09:22 +0000592 assert( v!=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000593 pNew = pParse->pNewTable;
594 assert( pNew );
595
drh1fee73e2007-08-29 04:00:57 +0000596 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000597 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000598 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000599 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000600 pCol = &pNew->aCol[pNew->nCol-1];
601 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000602 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000603 assert( pTab );
604
drh81f2ccd2006-01-31 14:28:44 +0000605#ifndef SQLITE_OMIT_AUTHORIZATION
606 /* Invoke the authorization callback. */
607 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
608 return;
609 }
610#endif
611
danielk197719a8e7e2005-03-17 05:03:38 +0000612 /* If the default value for the new column was specified with a
613 ** literal NULL, then set pDflt to 0. This simplifies checking
614 ** for an SQL NULL default below.
615 */
drh94fa9c42016-02-27 21:16:04 +0000616 assert( pDflt==0 || pDflt->op==TK_SPAN );
617 if( pDflt && pDflt->pLeft->op==TK_NULL ){
danielk197719a8e7e2005-03-17 05:03:38 +0000618 pDflt = 0;
619 }
620
621 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
622 ** If there is a NOT NULL constraint, then the default value for the
623 ** column must not be NULL.
624 */
drha371ace2012-09-13 14:22:47 +0000625 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000626 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
627 return;
628 }
629 if( pNew->pIndex ){
630 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
631 return;
632 }
dan53c3fa82009-09-25 11:26:54 +0000633 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
634 sqlite3ErrorMsg(pParse,
635 "Cannot add a REFERENCES column with non-NULL default value");
636 return;
637 }
danielk197719a8e7e2005-03-17 05:03:38 +0000638 if( pCol->notNull && !pDflt ){
639 sqlite3ErrorMsg(pParse,
640 "Cannot add a NOT NULL column with default value NULL");
641 return;
642 }
643
644 /* Ensure the default expression is something that sqlite3ValueFromExpr()
645 ** can handle (i.e. not CURRENT_TIME etc.)
646 */
647 if( pDflt ){
dan7a419232013-08-06 20:01:43 +0000648 sqlite3_value *pVal = 0;
drh96f4ad22015-03-12 21:02:36 +0000649 int rc;
drh05883a32015-06-02 15:32:08 +0000650 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
drh96f4ad22015-03-12 21:02:36 +0000651 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
652 if( rc!=SQLITE_OK ){
pdrbb3da062016-02-06 14:14:43 +0000653 assert( db->mallocFailed == 1 );
danielk197719a8e7e2005-03-17 05:03:38 +0000654 return;
655 }
656 if( !pVal ){
657 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
658 return;
659 }
660 sqlite3ValueFree(pVal);
661 }
662
663 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000664 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000665 if( zCol ){
666 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000667 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000668 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000669 *zEnd-- = '\0';
670 }
drh8257aa82017-07-26 19:59:13 +0000671 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000672 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000673 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000674 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000675 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000676 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000677 zTab
678 );
drh633e6d52008-07-28 19:34:53 +0000679 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000680 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000681 }
682
drh86396212016-07-14 19:13:11 +0000683 /* Make sure the schema version is at least 3. But do not upgrade
684 ** from less than 3 to 4, as that will corrupt any preexisting DESC
685 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000686 */
drh86396212016-07-14 19:13:11 +0000687 r1 = sqlite3GetTempReg(pParse);
688 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
689 sqlite3VdbeUsesBtree(v, iDb);
690 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
691 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
692 VdbeCoverage(v);
693 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
694 sqlite3ReleaseTempReg(pParse, r1);
danielk197719a8e7e2005-03-17 05:03:38 +0000695
696 /* Reload the schema of the modified table. */
697 reloadTableSchema(pParse, pTab, pTab->zName);
698}
699
drhfdd6e852005-12-16 01:06:16 +0000700/*
danielk197719a8e7e2005-03-17 05:03:38 +0000701** This function is called by the parser after the table-name in
702** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
703** pSrc is the full-name of the table being altered.
704**
705** This routine makes a (partial) copy of the Table structure
706** for the table being altered and sets Parse.pNewTable to point
707** to it. Routines called by the parser as the column definition
708** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
709** the copy. The copy of the Table structure is deleted by tokenize.c
710** after parsing is finished.
711**
712** Routine sqlite3AlterFinishAddColumn() will be called to complete
713** coding the "ALTER TABLE ... ADD" statement.
714*/
715void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
716 Table *pNew;
717 Table *pTab;
718 Vdbe *v;
719 int iDb;
720 int i;
721 int nAlloc;
drh17435752007-08-16 04:30:38 +0000722 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000723
724 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000725 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000726 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000727 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000728 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000729 if( !pTab ) goto exit_begin_add_column;
730
danielk19775ee9d692006-06-21 12:36:25 +0000731#ifndef SQLITE_OMIT_VIRTUALTABLE
732 if( IsVirtual(pTab) ){
733 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
734 goto exit_begin_add_column;
735 }
736#endif
737
danielk197719a8e7e2005-03-17 05:03:38 +0000738 /* Make sure this is not an attempt to ALTER a view. */
739 if( pTab->pSelect ){
740 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
741 goto exit_begin_add_column;
742 }
danbe535002011-04-01 15:15:58 +0000743 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
744 goto exit_begin_add_column;
745 }
danielk197719a8e7e2005-03-17 05:03:38 +0000746
747 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000748 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000749
750 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000751 ** sqlite3AddColumn() function and friends to modify. But modify
752 ** the name by adding an "sqlite_altertab_" prefix. By adding this
753 ** prefix, we insure that the name will not collide with an existing
754 ** table because user table are not allowed to have the "sqlite_"
755 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000756 */
drh17435752007-08-16 04:30:38 +0000757 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000758 if( !pNew ) goto exit_begin_add_column;
759 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000760 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000761 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000762 assert( pNew->nCol>0 );
763 nAlloc = (((pNew->nCol-1)/8)*8)+8;
764 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000765 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000766 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000767 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000768 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000769 goto exit_begin_add_column;
770 }
771 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
772 for(i=0; i<pNew->nCol; i++){
773 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000774 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000775 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000776 pCol->pDflt = 0;
777 }
drh17435752007-08-16 04:30:38 +0000778 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000779 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000780 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000781
782 /* Begin a transaction and increment the schema cookie. */
783 sqlite3BeginWriteOperation(pParse, 0, iDb);
784 v = sqlite3GetVdbe(pParse);
785 if( !v ) goto exit_begin_add_column;
drh9cbf3422008-01-17 16:22:13 +0000786 sqlite3ChangeCookie(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000787
788exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000789 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000790 return;
791}
dancf8f2892018-08-09 20:47:01 +0000792
drh4a2c7472018-08-13 15:09:48 +0000793/*
794** Handles the following parser reduction:
795**
796** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
797*/
dancf8f2892018-08-09 20:47:01 +0000798void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000799 Parse *pParse, /* Parsing context */
800 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
801 Token *pOld, /* Name of column being changed */
802 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000803){
drh4a2c7472018-08-13 15:09:48 +0000804 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000805 Table *pTab; /* Table being updated */
806 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000807 char *zOld = 0; /* Old column name */
808 char *zNew = 0; /* New column name */
809 const char *zDb; /* Name of schema containing the table */
810 int iSchema; /* Index of the schema */
811 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000812
drh4a2c7472018-08-13 15:09:48 +0000813 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000814 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
815 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000816
817 /* Cannot alter a system table */
dan872165f2018-08-11 17:34:38 +0000818 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000819
820 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000821 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
822 assert( iSchema>=0 );
823 zDb = db->aDb[iSchema].zDbSName;
824
drh4a2c7472018-08-13 15:09:48 +0000825 /* Make sure the old name really is a column name in the table to be
826 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000827 zOld = sqlite3NameFromToken(db, pOld);
828 if( !zOld ) goto exit_rename_column;
829 for(iCol=0; iCol<pTab->nCol; iCol++){
830 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
831 }
832 if( iCol==pTab->nCol ){
833 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
834 goto exit_rename_column;
835 }
836
drh4a2c7472018-08-13 15:09:48 +0000837 /* Do the rename operation using a recursive UPDATE statement that
838 ** uses the sqlite_rename_column() SQL function to compute the new
839 ** CREATE statement text for the sqlite_master table.
840 */
dancf8f2892018-08-09 20:47:01 +0000841 zNew = sqlite3NameFromToken(db, pNew);
842 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000843 assert( pNew->n>0 );
844 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000845 sqlite3NestedParse(pParse,
846 "UPDATE \"%w\".%s SET "
dan987db762018-08-14 20:18:50 +0000847 "sql = sqlite_rename_column(sql, %Q, %Q, %d, %Q, %d) "
dan499b8252018-08-17 18:08:28 +0000848 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
849 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000850 zDb, MASTER_NAME,
851 zDb, pTab->zName, iCol, zNew, bQuote,
852 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000853 );
854
dane325ffe2018-08-11 13:40:20 +0000855 /* Drop and reload the database schema. */
dan872165f2018-08-11 17:34:38 +0000856 if( pParse->pVdbe ){
dane325ffe2018-08-11 13:40:20 +0000857 sqlite3ChangeCookie(pParse, iSchema);
858 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iSchema, 0);
859 }
dancf8f2892018-08-09 20:47:01 +0000860
861 exit_rename_column:
862 sqlite3SrcListDelete(db, pSrc);
863 sqlite3DbFree(db, zOld);
864 sqlite3DbFree(db, zNew);
865 return;
866}
867
drh4a2c7472018-08-13 15:09:48 +0000868/*
869** Each RenameToken object maps an element of the parse tree into
870** the token that generated that element. The parse tree element
871** might be one of:
872**
873** * A pointer to an Expr that represents an ID
874** * The name of a table column in Column.zName
875**
876** A list of RenameToken objects can be constructed during parsing.
877** Each new object is created by sqlite3RenameToken().
878** As the parse tree is transformed, the sqlite3MoveRenameToken()
879** routine is used to keep the mapping current.
880**
881** After the parse finishes, renameTokenFind() routine can be used
882** to look up the actual token value that created some element in
883** the parse tree.
884*/
dancf8f2892018-08-09 20:47:01 +0000885struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000886 void *p; /* Parse tree element created by token t */
887 Token t; /* The token that created parse tree element p */
888 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000889};
890
drh4a2c7472018-08-13 15:09:48 +0000891/*
892** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
893** down into the Walker.
894*/
dan5496d6a2018-08-13 17:14:26 +0000895typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000896struct RenameCtx {
897 RenameToken *pList; /* List of tokens to overwrite */
898 int nList; /* Number of tokens in pList */
899 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000900 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000901 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000902};
903
drh4a2c7472018-08-13 15:09:48 +0000904/*
905** Add a new RenameToken object mapping parse tree element pPtr into
906** token *pToken to the Parse object currently under construction.
907*/
dancf8f2892018-08-09 20:47:01 +0000908void sqlite3RenameToken(Parse *pParse, void *pPtr, Token *pToken){
909 RenameToken *pNew;
910 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
911 if( pNew ){
912 pNew->p = pPtr;
913 pNew->t = *pToken;
914 pNew->pNext = pParse->pRename;
915 pParse->pRename = pNew;
916 }
917}
918
drh4a2c7472018-08-13 15:09:48 +0000919/*
920** If there is a RenameToken object associated with parse tree element
921** pFrom, then remap that object over to pTo due to a transformation
922** in the parse tree.
923*/
dancf8f2892018-08-09 20:47:01 +0000924void sqlite3MoveRenameToken(Parse *pParse, void *pTo, void *pFrom){
925 RenameToken *p;
926 for(p=pParse->pRename; p; p=p->pNext){
927 if( p->p==pFrom ){
928 p->p = pTo;
929 break;
930 }
931 }
932 assert( p );
933}
934
drh4a2c7472018-08-13 15:09:48 +0000935/*
936** Free the list of RenameToken objects given in the second argument
937*/
dancf8f2892018-08-09 20:47:01 +0000938static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
939 RenameToken *pNext;
940 RenameToken *p;
941 for(p=pToken; p; p=pNext){
942 pNext = p->pNext;
943 sqlite3DbFree(db, p);
944 }
945}
946
dan987db762018-08-14 20:18:50 +0000947/*
948** Search the Parse object passed as the first argument for a RenameToken
949** object associated with parse tree element pPtr. If found, remove it
950** from the Parse object and add it to the list maintained by the
951** RenameCtx object passed as the second argument.
952*/
953static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000954 RenameToken **pp;
955 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
956 if( (*pp)->p==pPtr ){
957 RenameToken *pToken = *pp;
958 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000959 pToken->pNext = pCtx->pList;
960 pCtx->pList = pToken;
961 pCtx->nList++;
962 break;
dancf8f2892018-08-09 20:47:01 +0000963 }
964 }
dancf8f2892018-08-09 20:47:01 +0000965}
966
dan24fedb92018-08-18 17:35:38 +0000967/*
968** This is a Walker select callback. It does nothing. It is only required
969** because without a dummy callback, sqlite3WalkExpr() and similar do not
970** descend into sub-select statements.
971*/
dan987db762018-08-14 20:18:50 +0000972static int renameColumnSelectCb(Walker *pWalker, Select *p){
drh38d99642018-08-18 18:27:18 +0000973 UNUSED_PARAMETER(pWalker);
974 UNUSED_PARAMETER(p);
dan987db762018-08-14 20:18:50 +0000975 return WRC_Continue;
976}
977
dan987db762018-08-14 20:18:50 +0000978/*
979** This is a Walker expression callback.
980**
981** For every TK_COLUMN node in the expression tree, search to see
982** if the column being references is the column being renamed by an
983** ALTER TABLE statement. If it is, then attach its associated
984** RenameToken object to the list of RenameToken objects being
985** constructed in RenameCtx object at pWalker->u.pRename.
986*/
dancf8f2892018-08-09 20:47:01 +0000987static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000988 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000989 if( pExpr->op==TK_TRIGGER
990 && pExpr->iColumn==p->iCol
991 && pWalker->pParse->pTriggerTab==p->pTab
992 ){
dan5be60c52018-08-15 20:28:39 +0000993 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000994 }else if( pExpr->op==TK_COLUMN
995 && pExpr->iColumn==p->iCol
996 && p->pTab==pExpr->pTab
dan987db762018-08-14 20:18:50 +0000997 ){
dan5496d6a2018-08-13 17:14:26 +0000998 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000999 }
1000 return WRC_Continue;
1001}
1002
dan987db762018-08-14 20:18:50 +00001003/*
1004** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +00001005** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +00001006** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +00001007** RenameContext. "Last" means the last RenameToken encountered when
1008** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +00001009** return all column name tokens in the order that they are encountered
1010** in the SQL statement.
1011*/
dan5496d6a2018-08-13 17:14:26 +00001012static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +00001013 RenameToken *pBest = pCtx->pList;
1014 RenameToken *pToken;
1015 RenameToken **pp;
1016
1017 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
1018 if( pToken->t.z>pBest->t.z ) pBest = pToken;
1019 }
1020 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
1021 *pp = pBest->pNext;
1022
1023 return pBest;
1024}
1025
dan6fe7f232018-08-10 19:19:33 +00001026/*
dan24fedb92018-08-18 17:35:38 +00001027** An error occured while parsing or otherwise processing a database
1028** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
1029** ALTER TABLE RENAME COLUMN program. The error message emitted by the
1030** sub-routine is currently stored in pParse->zErrMsg. This function
1031** adds context to the error message and then stores it in pCtx.
1032*/
1033static void renameColumnParseError(sqlite3_context *pCtx, Parse *pParse){
1034 const char *zT;
1035 const char *zN;
1036 char *zErr;
1037 if( pParse->pNewTable ){
1038 zT = pParse->pNewTable->pSelect ? "view" : "table";
1039 zN = pParse->pNewTable->zName;
1040 }else if( pParse->pNewIndex ){
1041 zT = "index";
1042 zN = pParse->pNewIndex->zName;
1043 }else{
1044 assert( pParse->pNewTrigger );
1045 zT = "trigger";
1046 zN = pParse->pNewTrigger->zName;
1047 }
1048 zErr = sqlite3_mprintf("error processing %s %s: %s", zT, zN, pParse->zErrMsg);
1049 sqlite3_result_error(pCtx, zErr, -1);
1050 sqlite3_free(zErr);
1051}
1052
1053/*
dan987db762018-08-14 20:18:50 +00001054** SQL function:
1055**
1056** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1057**
1058** 0. zSql: SQL statement to rewrite
1059** 1. Database: Database name (e.g. "main")
1060** 2. Table: Table name
1061** 3. iCol: Index of column to rename
1062** 4. zNew: New column name
1063** 5. bQuote: True if the new column name should be quoted
1064**
1065** Do a column rename operation on the CREATE statement given in zSql.
1066** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1067** into zNew. The name should be quoted if bQuote is true.
1068**
1069** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1070** Though accessible to application code, it is not intended for use by
1071** applications. The existance of this function, and the way it works,
1072** is subject to change without notice.
1073**
1074** If any of the parameters are out-of-bounds, then simply return NULL.
1075** An out-of-bounds parameter can only occur when the application calls
1076** this function directly. The parameters will always be well-formed when
1077** this routine is invoked by the bytecode for a legitimate ALTER TABLE
1078** statement.
dan6fe7f232018-08-10 19:19:33 +00001079*/
dancf8f2892018-08-09 20:47:01 +00001080static void renameColumnFunc(
1081 sqlite3_context *context,
1082 int NotUsed,
1083 sqlite3_value **argv
1084){
1085 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001086 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001087 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
dancf8f2892018-08-09 20:47:01 +00001088 int nSql = sqlite3_value_bytes(argv[0]);
dan987db762018-08-14 20:18:50 +00001089 const char *zDb = (const char*)sqlite3_value_text(argv[1]);
1090 const char *zTable = (const char*)sqlite3_value_text(argv[2]);
1091 int iCol = sqlite3_value_int(argv[3]);
1092 const char *zNew = (const char*)sqlite3_value_text(argv[4]);
1093 int nNew = sqlite3_value_bytes(argv[4]);
1094 int bQuote = sqlite3_value_int(argv[5]);
1095 const char *zOld;
dan6fe7f232018-08-10 19:19:33 +00001096
dancf8f2892018-08-09 20:47:01 +00001097 int rc;
1098 char *zErr = 0;
1099 Parse sParse;
1100 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001101 Index *pIdx;
1102 char *zOut = 0;
1103
1104 char *zQuot = 0; /* Quoted version of zNew */
1105 int nQuot = 0; /* Length of zQuot in bytes */
1106 int i;
dan987db762018-08-14 20:18:50 +00001107 Table *pTab;
dancf8f2892018-08-09 20:47:01 +00001108
drh38d99642018-08-18 18:27:18 +00001109 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001110 if( zSql==0 ) return;
1111 if( zNew==0 ) return;
1112 if( zTable==0 ) return;
1113 if( iCol<0 ) return;
1114 pTab = sqlite3FindTable(db, zTable, zDb);
1115 if( pTab==0 || iCol>=pTab->nCol ) return;
1116 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001117 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001118 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001119
dan24fedb92018-08-18 17:35:38 +00001120 /* Parse the SQL statement passed as the first argument. If no error
1121 ** occurs and the parse does not result in a new table, index or
1122 ** trigger object, the database must be corrupt. */
dancf8f2892018-08-09 20:47:01 +00001123 memset(&sParse, 0, sizeof(sParse));
1124 sParse.eParseMode = PARSE_MODE_RENAME_COLUMN;
1125 sParse.db = db;
1126 sParse.nQueryLoop = 1;
1127 rc = sqlite3RunParser(&sParse, zSql, &zErr);
dan24fedb92018-08-18 17:35:38 +00001128 assert( sParse.zErrMsg==0 );
1129 assert( rc!=SQLITE_OK || zErr==0 );
1130 assert( (!!sParse.pNewTable)+(!!sParse.pNewIndex)+(!!sParse.pNewTrigger)<2 );
1131 sParse.zErrMsg = zErr;
drh5fc22cd2018-08-13 13:43:11 +00001132 if( db->mallocFailed ) rc = SQLITE_NOMEM;
dan5496d6a2018-08-13 17:14:26 +00001133 if( rc==SQLITE_OK
1134 && sParse.pNewTable==0 && sParse.pNewIndex==0 && sParse.pNewTrigger==0
1135 ){
dancf8f2892018-08-09 20:47:01 +00001136 rc = SQLITE_CORRUPT_BKPT;
1137 }
1138
dancf8f2892018-08-09 20:47:01 +00001139#ifdef SQLITE_DEBUG
dan24fedb92018-08-18 17:35:38 +00001140 /* Ensure that all mappings in the Parse.pRename list really do map to
1141 ** a part of the input string. */
dancf8f2892018-08-09 20:47:01 +00001142 assert( sqlite3Strlen30(zSql)==nSql );
dan987db762018-08-14 20:18:50 +00001143 if( rc==SQLITE_OK ){
dancf8f2892018-08-09 20:47:01 +00001144 RenameToken *pToken;
1145 for(pToken=sParse.pRename; pToken; pToken=pToken->pNext){
1146 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
1147 }
1148 }
1149#endif
1150
dan24fedb92018-08-18 17:35:38 +00001151 /* Set zQuot to point to a buffer containing a quoted copy of the
1152 ** identifier zNew. If the corresponding identifier in the original
1153 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
1154 ** point to zQuot so that all substitutions are made using the
1155 ** quoted version of the new column name. */
1156 if( rc==SQLITE_OK ){
1157 zQuot = sqlite3_mprintf("\"%w\"", zNew);
1158 if( zQuot==0 ){
1159 rc = SQLITE_NOMEM;
1160 }else{
1161 nQuot = sqlite3Strlen30(zQuot);
1162 }
1163 }
1164 if( bQuote ){
1165 zNew = zQuot;
1166 nNew = nQuot;
1167 }
1168
dancf8f2892018-08-09 20:47:01 +00001169 /* Find tokens that need to be replaced. */
1170 memset(&sWalker, 0, sizeof(Walker));
1171 sWalker.pParse = &sParse;
1172 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001173 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001174 sWalker.u.pRename = &sCtx;
1175
dan0cbb0b12018-08-16 19:49:16 +00001176 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001177 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001178 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001179 Select *pSelect = sParse.pNewTable->pSelect;
1180 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001181 sParse.rc = SQLITE_OK;
1182 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1183 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1184 if( rc==SQLITE_OK ){
1185 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001186 }
dan987db762018-08-14 20:18:50 +00001187 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1188 }else{
1189 /* A regular table */
1190 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1191 FKey *pFKey;
1192 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001193 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001194 if( bFKOnly==0 ){
1195 renameTokenFind(
1196 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1197 );
1198 if( sCtx.iCol<0 ){
1199 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001200 }
dan987db762018-08-14 20:18:50 +00001201 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1202 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1203 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1204 }
1205 }
1206
1207 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1208 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001209 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001210 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1211 }
1212 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1213 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1214 ){
1215 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1216 }
dan6fe7f232018-08-10 19:19:33 +00001217 }
dancf8f2892018-08-09 20:47:01 +00001218 }
1219 }
dan5496d6a2018-08-13 17:14:26 +00001220 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001221 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1222 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001223 }else{
dan5be60c52018-08-15 20:28:39 +00001224 /* A trigger */
1225 TriggerStep *pStep;
1226 NameContext sNC;
1227 memset(&sNC, 0, sizeof(sNC));
1228 sNC.pParse = &sParse;
dan0cbb0b12018-08-16 19:49:16 +00001229 sParse.pTriggerTab = sqlite3FindTable(db, sParse.pNewTrigger->table, zDb);
dan5be60c52018-08-15 20:28:39 +00001230 sParse.eTriggerOp = sParse.pNewTrigger->op;
1231
dan0cbb0b12018-08-16 19:49:16 +00001232 /* Resolve symbols in WHEN clause */
1233 if( sParse.pNewTrigger->pWhen ){
dan5be60c52018-08-15 20:28:39 +00001234 rc = sqlite3ResolveExprNames(&sNC, sParse.pNewTrigger->pWhen);
1235 }
1236
1237 for(pStep=sParse.pNewTrigger->step_list;
1238 rc==SQLITE_OK && pStep;
1239 pStep=pStep->pNext
1240 ){
1241 if( pStep->pSelect ) sqlite3SelectPrep(&sParse, pStep->pSelect, &sNC);
1242 if( pStep->zTarget ){
1243 Table *pTarget = sqlite3FindTable(db, pStep->zTarget, zDb);
1244 if( pTarget==0 ){
1245 rc = SQLITE_ERROR;
1246 }else{
1247 SrcList sSrc;
1248 memset(&sSrc, 0, sizeof(sSrc));
1249 sSrc.nSrc = 1;
1250 sSrc.a[0].zName = pStep->zTarget;
1251 sSrc.a[0].pTab = pTarget;
1252 sNC.pSrcList = &sSrc;
1253 if( pStep->pWhere ){
1254 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
1255 }
1256 if( rc==SQLITE_OK ){
1257 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
1258 }
dan0cbb0b12018-08-16 19:49:16 +00001259 if( pStep->pUpsert ){
1260 Upsert *pUpsert = pStep->pUpsert;
1261 if( rc==SQLITE_OK ){
1262 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
1263 }
1264 if( rc==SQLITE_OK && pUpsert->pUpsertSet){
1265 ExprList *pUpsertSet = pUpsert->pUpsertSet;
1266 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet);
1267 if( rc==SQLITE_OK && pTarget==pTab ){
1268 for(i=0; i<pUpsertSet->nExpr; i++){
1269 char *zName = pUpsertSet->a[i].zName;
1270 if( 0==sqlite3_stricmp(zName, zOld) ){
1271 renameTokenFind(&sParse, &sCtx, (void*)zName);
1272 }
1273 }
1274 }
1275 }
1276 if( rc==SQLITE_OK ){
1277 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
1278 }
1279 if( rc==SQLITE_OK ){
1280 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
1281 }
1282 }
dan5be60c52018-08-15 20:28:39 +00001283
1284 if( rc==SQLITE_OK && pTarget==pTab ){
1285 if( pStep->pIdList ){
1286 for(i=0; i<pStep->pIdList->nId; i++){
1287 char *zName = pStep->pIdList->a[i].zName;
1288 if( 0==sqlite3_stricmp(zName, zOld) ){
1289 renameTokenFind(&sParse, &sCtx, (void*)zName);
1290 }
1291 }
1292 }
1293 if( pStep->op==TK_UPDATE ){
1294 assert( pStep->pExprList );
1295 for(i=0; i<pStep->pExprList->nExpr; i++){
1296 char *zName = pStep->pExprList->a[i].zName;
1297 if( 0==sqlite3_stricmp(zName, zOld) ){
1298 renameTokenFind(&sParse, &sCtx, (void*)zName);
1299 }
1300 }
1301 }
1302 }
1303 }
1304 }
1305 }
1306
1307 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1308
1309 /* Find tokens to edit in UPDATE OF clause */
1310 if( sParse.pTriggerTab==pTab && sParse.pNewTrigger->pColumns ){
dan5496d6a2018-08-13 17:14:26 +00001311 for(i=0; i<sParse.pNewTrigger->pColumns->nId; i++){
1312 char *zName = sParse.pNewTrigger->pColumns->a[i].zName;
1313 if( 0==sqlite3_stricmp(zName, zOld) ){
1314 renameTokenFind(&sParse, &sCtx, (void*)zName);
1315 }
1316 }
1317 }
dan5be60c52018-08-15 20:28:39 +00001318
1319 /* Find tokens to edit in WHEN clause */
1320 sqlite3WalkExpr(&sWalker, sParse.pNewTrigger->pWhen);
1321
1322 /* Find tokens to edit in trigger steps */
1323 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1324 sqlite3WalkSelect(&sWalker, pStep->pSelect);
1325 sqlite3WalkExpr(&sWalker, pStep->pWhere);
1326 sqlite3WalkExprList(&sWalker, pStep->pExprList);
dan0cbb0b12018-08-16 19:49:16 +00001327 if( pStep->pUpsert ){
1328 Upsert *pUpsert = pStep->pUpsert;
1329 sqlite3WalkExprList(&sWalker, pUpsert->pUpsertTarget);
1330 sqlite3WalkExprList(&sWalker, pUpsert->pUpsertSet);
1331 sqlite3WalkExpr(&sWalker, pUpsert->pUpsertWhere);
1332 sqlite3WalkExpr(&sWalker, pUpsert->pUpsertTargetWhere);
1333 }
dan5be60c52018-08-15 20:28:39 +00001334 }
dancf8f2892018-08-09 20:47:01 +00001335 }
1336
dan24fedb92018-08-18 17:35:38 +00001337 /* At this point sCtx.pList contains a list of RenameToken objects
1338 ** corresponding to all tokens in the input SQL that must be replaced
1339 ** with the new column name. All that remains is to construct and
1340 ** return the edited SQL string. */
dan987db762018-08-14 20:18:50 +00001341 assert( rc==SQLITE_OK );
dan404c3ba2018-08-11 20:38:33 +00001342 assert( nQuot>=nNew );
1343 zOut = sqlite3DbMallocZero(db, nSql + sCtx.nList*nQuot + 1);
dancf8f2892018-08-09 20:47:01 +00001344 if( zOut ){
1345 int nOut = nSql;
1346 memcpy(zOut, zSql, nSql);
1347 while( sCtx.pList ){
1348 int iOff; /* Offset of token to replace in zOut */
1349 RenameToken *pBest = renameColumnTokenNext(&sCtx);
1350
drh38d99642018-08-18 18:27:18 +00001351 u32 nReplace;
dancf8f2892018-08-09 20:47:01 +00001352 const char *zReplace;
1353 if( sqlite3IsIdChar(*pBest->t.z) ){
1354 nReplace = nNew;
1355 zReplace = zNew;
1356 }else{
1357 nReplace = nQuot;
1358 zReplace = zQuot;
1359 }
1360
1361 iOff = pBest->t.z - zSql;
1362 if( pBest->t.n!=nReplace ){
1363 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1364 nOut - (iOff + pBest->t.n)
1365 );
1366 nOut += nReplace - pBest->t.n;
1367 zOut[nOut] = '\0';
1368 }
1369 memcpy(&zOut[iOff], zReplace, nReplace);
1370 sqlite3DbFree(db, pBest);
1371 }
1372
1373 sqlite3_result_text(context, zOut, -1, SQLITE_TRANSIENT);
1374 sqlite3DbFree(db, zOut);
dan987db762018-08-14 20:18:50 +00001375 }else{
1376 rc = SQLITE_NOMEM;
dancf8f2892018-08-09 20:47:01 +00001377 }
1378
drh5fc22cd2018-08-13 13:43:11 +00001379renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001380 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001381 if( sParse.zErrMsg ){
1382 renameColumnParseError(context, &sParse);
dan987db762018-08-14 20:18:50 +00001383 }else{
1384 sqlite3_result_error_code(context, rc);
1385 }
1386 }
1387
dancf8f2892018-08-09 20:47:01 +00001388 if( sParse.pVdbe ){
1389 sqlite3VdbeFinalize(sParse.pVdbe);
1390 }
1391 sqlite3DeleteTable(db, sParse.pNewTable);
1392 if( sParse.pNewIndex ) sqlite3FreeIndex(db, sParse.pNewIndex);
dan5496d6a2018-08-13 17:14:26 +00001393 sqlite3DeleteTrigger(db, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001394 renameTokenFree(db, sParse.pRename);
drh4a2c7472018-08-13 15:09:48 +00001395 renameTokenFree(db, sCtx.pList);
dan24fedb92018-08-18 17:35:38 +00001396 sqlite3DbFree(db, sParse.zErrMsg);
dancf8f2892018-08-09 20:47:01 +00001397 sqlite3ParserReset(&sParse);
1398 sqlite3_free(zQuot);
1399}
1400
1401/*
1402** Register built-in functions used to help implement ALTER TABLE
1403*/
1404void sqlite3AlterFunctions(void){
1405 static FuncDef aAlterTableFuncs[] = {
1406 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
dan404c3ba2018-08-11 20:38:33 +00001407 FUNCTION(sqlite_rename_column, 6, 0, 0, renameColumnFunc),
dancf8f2892018-08-09 20:47:01 +00001408#ifndef SQLITE_OMIT_TRIGGER
1409 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
1410#endif
1411#ifndef SQLITE_OMIT_FOREIGN_KEY
1412 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
1413#endif
1414 };
1415 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1416}
drhd0e4a6c2005-02-15 20:47:57 +00001417#endif /* SQLITE_ALTER_TABLE */