blob: e0e9ae85078f4229b497ae53bd33df16bf801cdf [file] [log] [blame]
drhd0e4a6c2005-02-15 20:47:57 +00001/*
2** 2005 February 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12** This file contains C code routines that used to generate VDBE code
13** that implements the ALTER TABLE command.
drhd0e4a6c2005-02-15 20:47:57 +000014*/
15#include "sqliteInt.h"
16
drh1f01ec12005-02-15 21:36:18 +000017/*
18** The code in this file only exists if we are not omitting the
19** ALTER TABLE logic from the build.
20*/
drhd0e4a6c2005-02-15 20:47:57 +000021#ifndef SQLITE_OMIT_ALTERTABLE
drh1f01ec12005-02-15 21:36:18 +000022
drh1f01ec12005-02-15 21:36:18 +000023/*
danbe535002011-04-01 15:15:58 +000024** Parameter zName is the name of a table that is about to be altered
25** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
26** If the table is a system table, this function leaves an error message
27** in pParse->zErr (system tables may not be altered) and returns non-zero.
28**
29** Or, if zName is not a system table, zero is returned.
30*/
31static int isSystemTable(Parse *pParse, const char *zName){
drh59a386e2017-06-28 01:12:53 +000032 if( 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
danbe535002011-04-01 15:15:58 +000033 sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
34 return 1;
35 }
36 return 0;
37}
38
dan09236502018-09-01 16:05:50 +000039/*
40** Generate code to verify that the schemas of database zDb and, if
41** bTemp is not true, database "temp", can still be parsed. This is
42** called at the end of the generation of an ALTER TABLE ... RENAME ...
43** statement to ensure that the operation has not rendered any schema
44** objects unusable.
45*/
drh16b870d2018-09-12 15:51:56 +000046static void renameTestSchema(Parse *pParse, const char *zDb, int bTemp){
dan9d324822018-08-30 20:03:44 +000047 sqlite3NestedParse(pParse,
48 "SELECT 1 "
49 "FROM \"%w\".%s "
50 "WHERE name NOT LIKE 'sqlite_%%'"
51 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000052 " AND sqlite_rename_test(%Q, sql, type, name, %d)=NULL ",
dan9d324822018-08-30 20:03:44 +000053 zDb, MASTER_NAME,
54 zDb, bTemp
55 );
56
57 if( bTemp==0 ){
58 sqlite3NestedParse(pParse,
59 "SELECT 1 "
60 "FROM temp.%s "
61 "WHERE name NOT LIKE 'sqlite_%%'"
62 " AND sql NOT LIKE 'create virtual%%'"
dan1d85c6b2018-09-06 16:01:37 +000063 " AND sqlite_rename_test(%Q, sql, type, name, 1)=NULL ",
dan9d324822018-08-30 20:03:44 +000064 MASTER_NAME, zDb
65 );
66 }
67}
68
danbe535002011-04-01 15:15:58 +000069/*
dan09236502018-09-01 16:05:50 +000070** Generate code to reload the schema for database iDb. And, if iDb!=1, for
71** the temp database as well.
72*/
drh16b870d2018-09-12 15:51:56 +000073static void renameReloadSchema(Parse *pParse, int iDb){
dan09236502018-09-01 16:05:50 +000074 Vdbe *v = pParse->pVdbe;
75 if( v ){
76 sqlite3ChangeCookie(pParse, iDb);
77 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0);
78 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0);
79 }
80}
81
82/*
drhd0e4a6c2005-02-15 20:47:57 +000083** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
84** command.
85*/
86void sqlite3AlterRenameTable(
87 Parse *pParse, /* Parser context. */
88 SrcList *pSrc, /* The table to rename. */
89 Token *pName /* The new table name. */
90){
91 int iDb; /* Database that contains the table */
92 char *zDb; /* Name of database iDb */
93 Table *pTab; /* Table being renamed */
94 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +000095 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +000096 int nTabName; /* Number of UTF-8 characters in zTabName */
97 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +000098 Vdbe *v;
danielk1977595a5232009-07-24 17:58:53 +000099 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh8257aa82017-07-26 19:59:13 +0000100 u32 savedDbFlags; /* Saved value of db->mDbFlags */
drh545f5872010-04-24 14:02:59 +0000101
drh8257aa82017-07-26 19:59:13 +0000102 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000103 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000104 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000105 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000106
dan41fb5cd2012-10-04 19:33:00 +0000107 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
drhd0e4a6c2005-02-15 20:47:57 +0000108 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000109 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drh69c33822016-08-18 14:33:11 +0000110 zDb = db->aDb[iDb].zDbSName;
drh8257aa82017-07-26 19:59:13 +0000111 db->mDbFlags |= DBFLAG_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000112
113 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000114 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000115 if( !zName ) goto exit_rename_table;
116
117 /* Check that a table or index named 'zName' does not already exist
118 ** in database iDb. If so, this is an error.
119 */
120 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
121 sqlite3ErrorMsg(pParse,
122 "there is already another table or index with this name: %s", zName);
123 goto exit_rename_table;
124 }
125
126 /* Make sure it is not a system table being altered, or a reserved name
127 ** that the table is being renamed to.
128 */
danbe535002011-04-01 15:15:58 +0000129 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
drhd0e4a6c2005-02-15 20:47:57 +0000130 goto exit_rename_table;
131 }
danbe535002011-04-01 15:15:58 +0000132 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
133 exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000134 }
135
danielk197761116ae2007-12-13 08:15:30 +0000136#ifndef SQLITE_OMIT_VIEW
137 if( pTab->pSelect ){
138 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
139 goto exit_rename_table;
140 }
141#endif
142
drhd0e4a6c2005-02-15 20:47:57 +0000143#ifndef SQLITE_OMIT_AUTHORIZATION
144 /* Invoke the authorization callback. */
145 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
146 goto exit_rename_table;
147 }
148#endif
149
danielk1977182c4ba2007-06-27 15:53:34 +0000150#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000151 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
152 goto exit_rename_table;
153 }
danielk1977595a5232009-07-24 17:58:53 +0000154 if( IsVirtual(pTab) ){
155 pVTab = sqlite3GetVTable(db, pTab);
156 if( pVTab->pVtab->pModule->xRename==0 ){
157 pVTab = 0;
158 }
danielk1977182c4ba2007-06-27 15:53:34 +0000159 }
160#endif
161
drhb22f7c82014-02-06 23:56:27 +0000162 /* Begin a transaction for database iDb.
drhd0e4a6c2005-02-15 20:47:57 +0000163 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000164 ** schema). Open a statement transaction if the table is a virtual
165 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000166 */
167 v = sqlite3GetVdbe(pParse);
168 if( v==0 ){
169 goto exit_rename_table;
170 }
drhd0e4a6c2005-02-15 20:47:57 +0000171
danielk1977182c4ba2007-06-27 15:53:34 +0000172 /* If this is a virtual table, invoke the xRename() function if
173 ** one is defined. The xRename() callback will modify the names
174 ** of any resources used by the v-table implementation (including other
175 ** SQLite tables) that are identified by the name of the virtual table.
176 */
177#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000178 if( pVTab ){
danielk1977a29f18c2008-01-04 11:01:03 +0000179 int i = ++pParse->nMem;
drh076e85f2015-09-03 13:46:12 +0000180 sqlite3VdbeLoadString(v, i, zName);
danielk1977595a5232009-07-24 17:58:53 +0000181 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dane0af83a2009-09-08 19:15:01 +0000182 sqlite3MayAbort(pParse);
danielk1977182c4ba2007-06-27 15:53:34 +0000183 }
184#endif
185
drh4e5dd852007-05-15 03:56:49 +0000186 /* figure out how many UTF-8 characters are in zName */
187 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000188 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000189
danc9461ec2018-08-29 21:00:16 +0000190 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in
191 ** the schema to use the new table name. */
192 sqlite3NestedParse(pParse,
193 "UPDATE \"%w\".%s SET "
dan65372fa2018-09-03 20:05:15 +0000194 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) "
danc9461ec2018-08-29 21:00:16 +0000195 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)"
196 "AND name NOT LIKE 'sqlite_%%'"
dan0ccda962018-08-30 16:26:48 +0000197 , zDb, MASTER_NAME, zDb, zTabName, zName, (iDb==1), zTabName
danc9461ec2018-08-29 21:00:16 +0000198 );
dan432cc5b2009-09-26 17:51:48 +0000199
danc9461ec2018-08-29 21:00:16 +0000200 /* Update the tbl_name and name columns of the sqlite_master table
201 ** as required. */
drhd0e4a6c2005-02-15 20:47:57 +0000202 sqlite3NestedParse(pParse,
203 "UPDATE %Q.%s SET "
drhd0e4a6c2005-02-15 20:47:57 +0000204 "tbl_name = %Q, "
205 "name = CASE "
206 "WHEN type='table' THEN %Q "
207 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000208 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000209 "ELSE name END "
drh01522682012-02-01 01:13:10 +0000210 "WHERE tbl_name=%Q COLLATE nocase AND "
drhd0e4a6c2005-02-15 20:47:57 +0000211 "(type='table' OR type='index' OR type='trigger');",
danc9461ec2018-08-29 21:00:16 +0000212 zDb, MASTER_NAME,
213 zName, zName, zName,
214 nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000215 );
216
217#ifndef SQLITE_OMIT_AUTOINCREMENT
218 /* If the sqlite_sequence table exists in this database, then update
219 ** it with the new table name.
220 */
221 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
222 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000223 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000224 zDb, zName, pTab->zName);
225 }
226#endif
227
danc9461ec2018-08-29 21:00:16 +0000228 /* If the table being renamed is not itself part of the temp database,
229 ** edit view and trigger definitions within the temp database
230 ** as required. */
231 if( iDb!=1 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000232 sqlite3NestedParse(pParse,
233 "UPDATE sqlite_temp_master SET "
dan65372fa2018-09-03 20:05:15 +0000234 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), "
danc9461ec2018-08-29 21:00:16 +0000235 "tbl_name = "
dan1d85c6b2018-09-06 16:01:37 +0000236 "CASE WHEN tbl_name=%Q COLLATE nocase AND "
237 " sqlite_rename_test(%Q, sql, type, name, 1) "
238 "THEN %Q ELSE tbl_name END "
danc9461ec2018-08-29 21:00:16 +0000239 "WHERE type IN ('view', 'trigger')"
dan1d85c6b2018-09-06 16:01:37 +0000240 , zDb, zTabName, zName, zTabName, zDb, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000241 }
drhd0e4a6c2005-02-15 20:47:57 +0000242
dan09236502018-09-01 16:05:50 +0000243 renameReloadSchema(pParse, iDb);
dan9d324822018-08-30 20:03:44 +0000244 renameTestSchema(pParse, zDb, iDb==1);
245
drhd0e4a6c2005-02-15 20:47:57 +0000246exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000247 sqlite3SrcListDelete(db, pSrc);
248 sqlite3DbFree(db, zName);
drh8257aa82017-07-26 19:59:13 +0000249 db->mDbFlags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000250}
danielk197719a8e7e2005-03-17 05:03:38 +0000251
drhd3001712009-05-12 17:46:53 +0000252/*
danielk197719a8e7e2005-03-17 05:03:38 +0000253** This function is called after an "ALTER TABLE ... ADD" statement
254** has been parsed. Argument pColDef contains the text of the new
255** column definition.
256**
257** The Table structure pParse->pNewTable was extended to include
258** the new column during parsing.
259*/
260void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
261 Table *pNew; /* Copy of pParse->pNewTable */
262 Table *pTab; /* Table being altered */
263 int iDb; /* Database number */
264 const char *zDb; /* Database name */
265 const char *zTab; /* Table name */
266 char *zCol; /* Null-terminated column definition */
267 Column *pCol; /* The new column */
268 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000269 sqlite3 *db; /* The database connection; */
dan09236502018-09-01 16:05:50 +0000270 Vdbe *v; /* The prepared statement under construction */
drh86396212016-07-14 19:13:11 +0000271 int r1; /* Temporary registers */
danielk197719a8e7e2005-03-17 05:03:38 +0000272
danielk1977f150c9d2008-10-30 17:21:12 +0000273 db = pParse->db;
274 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000275 pNew = pParse->pNewTable;
276 assert( pNew );
277
drh1fee73e2007-08-29 04:00:57 +0000278 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000279 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
drh69c33822016-08-18 14:33:11 +0000280 zDb = db->aDb[iDb].zDbSName;
drh03881232009-02-13 03:43:31 +0000281 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000282 pCol = &pNew->aCol[pNew->nCol-1];
283 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000284 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000285 assert( pTab );
286
drh81f2ccd2006-01-31 14:28:44 +0000287#ifndef SQLITE_OMIT_AUTHORIZATION
288 /* Invoke the authorization callback. */
289 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
290 return;
291 }
292#endif
293
danielk197719a8e7e2005-03-17 05:03:38 +0000294 /* If the default value for the new column was specified with a
295 ** literal NULL, then set pDflt to 0. This simplifies checking
296 ** for an SQL NULL default below.
297 */
drh94fa9c42016-02-27 21:16:04 +0000298 assert( pDflt==0 || pDflt->op==TK_SPAN );
299 if( pDflt && pDflt->pLeft->op==TK_NULL ){
danielk197719a8e7e2005-03-17 05:03:38 +0000300 pDflt = 0;
301 }
302
303 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
304 ** If there is a NOT NULL constraint, then the default value for the
305 ** column must not be NULL.
306 */
drha371ace2012-09-13 14:22:47 +0000307 if( pCol->colFlags & COLFLAG_PRIMKEY ){
danielk197719a8e7e2005-03-17 05:03:38 +0000308 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
309 return;
310 }
311 if( pNew->pIndex ){
312 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
313 return;
314 }
dan53c3fa82009-09-25 11:26:54 +0000315 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
316 sqlite3ErrorMsg(pParse,
317 "Cannot add a REFERENCES column with non-NULL default value");
318 return;
319 }
danielk197719a8e7e2005-03-17 05:03:38 +0000320 if( pCol->notNull && !pDflt ){
321 sqlite3ErrorMsg(pParse,
322 "Cannot add a NOT NULL column with default value NULL");
323 return;
324 }
325
326 /* Ensure the default expression is something that sqlite3ValueFromExpr()
327 ** can handle (i.e. not CURRENT_TIME etc.)
328 */
329 if( pDflt ){
dan7a419232013-08-06 20:01:43 +0000330 sqlite3_value *pVal = 0;
drh96f4ad22015-03-12 21:02:36 +0000331 int rc;
drh05883a32015-06-02 15:32:08 +0000332 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
drh96f4ad22015-03-12 21:02:36 +0000333 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
334 if( rc!=SQLITE_OK ){
pdrbb3da062016-02-06 14:14:43 +0000335 assert( db->mallocFailed == 1 );
danielk197719a8e7e2005-03-17 05:03:38 +0000336 return;
337 }
338 if( !pVal ){
339 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
340 return;
341 }
342 sqlite3ValueFree(pVal);
343 }
344
345 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000346 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000347 if( zCol ){
348 char *zEnd = &zCol[pColDef->n-1];
drh8257aa82017-07-26 19:59:13 +0000349 u32 savedDbFlags = db->mDbFlags;
drh56d56f72009-04-16 16:30:17 +0000350 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000351 *zEnd-- = '\0';
352 }
drh8257aa82017-07-26 19:59:13 +0000353 db->mDbFlags |= DBFLAG_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000354 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000355 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000356 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000357 "WHERE type = 'table' AND name = %Q",
drhe0a04a32016-12-16 01:00:21 +0000358 zDb, MASTER_NAME, pNew->addColOffset, zCol, pNew->addColOffset+1,
danielk197719a8e7e2005-03-17 05:03:38 +0000359 zTab
360 );
drh633e6d52008-07-28 19:34:53 +0000361 sqlite3DbFree(db, zCol);
drh8257aa82017-07-26 19:59:13 +0000362 db->mDbFlags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000363 }
364
drh86396212016-07-14 19:13:11 +0000365 /* Make sure the schema version is at least 3. But do not upgrade
366 ** from less than 3 to 4, as that will corrupt any preexisting DESC
367 ** index.
danielk197719a8e7e2005-03-17 05:03:38 +0000368 */
dan09236502018-09-01 16:05:50 +0000369 v = sqlite3GetVdbe(pParse);
370 if( v ){
371 r1 = sqlite3GetTempReg(pParse);
372 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
373 sqlite3VdbeUsesBtree(v, iDb);
374 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
375 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2);
376 VdbeCoverage(v);
377 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3);
378 sqlite3ReleaseTempReg(pParse, r1);
379 }
danielk197719a8e7e2005-03-17 05:03:38 +0000380
dan09236502018-09-01 16:05:50 +0000381 /* Reload the table definition */
382 renameReloadSchema(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000383}
384
drhfdd6e852005-12-16 01:06:16 +0000385/*
danielk197719a8e7e2005-03-17 05:03:38 +0000386** This function is called by the parser after the table-name in
387** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
388** pSrc is the full-name of the table being altered.
389**
390** This routine makes a (partial) copy of the Table structure
391** for the table being altered and sets Parse.pNewTable to point
392** to it. Routines called by the parser as the column definition
393** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
394** the copy. The copy of the Table structure is deleted by tokenize.c
395** after parsing is finished.
396**
397** Routine sqlite3AlterFinishAddColumn() will be called to complete
398** coding the "ALTER TABLE ... ADD" statement.
399*/
400void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
401 Table *pNew;
402 Table *pTab;
danielk197719a8e7e2005-03-17 05:03:38 +0000403 int iDb;
404 int i;
405 int nAlloc;
drh17435752007-08-16 04:30:38 +0000406 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000407
408 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000409 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000410 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000411 if( db->mallocFailed ) goto exit_begin_add_column;
dan41fb5cd2012-10-04 19:33:00 +0000412 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
danielk197719a8e7e2005-03-17 05:03:38 +0000413 if( !pTab ) goto exit_begin_add_column;
414
danielk19775ee9d692006-06-21 12:36:25 +0000415#ifndef SQLITE_OMIT_VIRTUALTABLE
416 if( IsVirtual(pTab) ){
417 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
418 goto exit_begin_add_column;
419 }
420#endif
421
danielk197719a8e7e2005-03-17 05:03:38 +0000422 /* Make sure this is not an attempt to ALTER a view. */
423 if( pTab->pSelect ){
424 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
425 goto exit_begin_add_column;
426 }
danbe535002011-04-01 15:15:58 +0000427 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
428 goto exit_begin_add_column;
429 }
danielk197719a8e7e2005-03-17 05:03:38 +0000430
431 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000432 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000433
434 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000435 ** sqlite3AddColumn() function and friends to modify. But modify
436 ** the name by adding an "sqlite_altertab_" prefix. By adding this
437 ** prefix, we insure that the name will not collide with an existing
438 ** table because user table are not allowed to have the "sqlite_"
439 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000440 */
drh17435752007-08-16 04:30:38 +0000441 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000442 if( !pNew ) goto exit_begin_add_column;
443 pParse->pNewTable = pNew;
drh79df7782016-12-14 14:07:35 +0000444 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000445 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000446 assert( pNew->nCol>0 );
447 nAlloc = (((pNew->nCol-1)/8)*8)+8;
448 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000449 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000450 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000451 if( !pNew->aCol || !pNew->zName ){
drh4df86af2016-02-04 11:48:00 +0000452 assert( db->mallocFailed );
danielk197719a8e7e2005-03-17 05:03:38 +0000453 goto exit_begin_add_column;
454 }
455 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
456 for(i=0; i<pNew->nCol; i++){
457 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000458 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000459 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000460 pCol->pDflt = 0;
461 }
drh17435752007-08-16 04:30:38 +0000462 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000463 pNew->addColOffset = pTab->addColOffset;
drh79df7782016-12-14 14:07:35 +0000464 pNew->nTabRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000465
danielk197719a8e7e2005-03-17 05:03:38 +0000466exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000467 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000468 return;
469}
dancf8f2892018-08-09 20:47:01 +0000470
drh4a2c7472018-08-13 15:09:48 +0000471/*
dan9d705572018-08-20 16:16:05 +0000472** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
473** command. This function checks if the table is a view or virtual
474** table (columns of views or virtual tables may not be renamed). If so,
475** it loads an error message into pParse and returns non-zero.
476**
477** Or, if pTab is not a view or virtual table, zero is returned.
478*/
479#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
480static int isRealTable(Parse *pParse, Table *pTab){
481 const char *zType = 0;
482#ifndef SQLITE_OMIT_VIEW
483 if( pTab->pSelect ){
484 zType = "view";
dan1041a6a2018-09-06 17:47:09 +0000485 }
dan9d705572018-08-20 16:16:05 +0000486#endif
487#ifndef SQLITE_OMIT_VIRTUALTABLE
488 if( IsVirtual(pTab) ){
489 zType = "virtual table";
490 }
491#endif
492 if( zType ){
493 sqlite3ErrorMsg(
drh79a5ee92018-08-23 19:32:04 +0000494 pParse, "cannot rename columns of %s \"%s\"", zType, pTab->zName
dan9d705572018-08-20 16:16:05 +0000495 );
496 return 1;
497 }
498 return 0;
499}
500#else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
501# define isRealTable(x,y) (0)
502#endif
503
504/*
drh4a2c7472018-08-13 15:09:48 +0000505** Handles the following parser reduction:
506**
507** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew
508*/
dancf8f2892018-08-09 20:47:01 +0000509void sqlite3AlterRenameColumn(
drh4a2c7472018-08-13 15:09:48 +0000510 Parse *pParse, /* Parsing context */
511 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
512 Token *pOld, /* Name of column being changed */
513 Token *pNew /* New column name */
dancf8f2892018-08-09 20:47:01 +0000514){
drh4a2c7472018-08-13 15:09:48 +0000515 sqlite3 *db = pParse->db; /* Database connection */
dancf8f2892018-08-09 20:47:01 +0000516 Table *pTab; /* Table being updated */
517 int iCol; /* Index of column being renamed */
drh4a2c7472018-08-13 15:09:48 +0000518 char *zOld = 0; /* Old column name */
519 char *zNew = 0; /* New column name */
520 const char *zDb; /* Name of schema containing the table */
521 int iSchema; /* Index of the schema */
522 int bQuote; /* True to quote the new name */
dancf8f2892018-08-09 20:47:01 +0000523
drh4a2c7472018-08-13 15:09:48 +0000524 /* Locate the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000525 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
526 if( !pTab ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000527
528 /* Cannot alter a system table */
dan872165f2018-08-11 17:34:38 +0000529 if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ) goto exit_rename_column;
dan9d705572018-08-20 16:16:05 +0000530 if( SQLITE_OK!=isRealTable(pParse, pTab) ) goto exit_rename_column;
drh4a2c7472018-08-13 15:09:48 +0000531
532 /* Which schema holds the table to be altered */
dancf8f2892018-08-09 20:47:01 +0000533 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
534 assert( iSchema>=0 );
535 zDb = db->aDb[iSchema].zDbSName;
536
drh0d019b92018-08-25 16:14:46 +0000537#ifndef SQLITE_OMIT_AUTHORIZATION
538 /* Invoke the authorization callback. */
539 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
540 goto exit_rename_column;
541 }
542#endif
543
drh4a2c7472018-08-13 15:09:48 +0000544 /* Make sure the old name really is a column name in the table to be
545 ** altered. Set iCol to be the index of the column being renamed */
dancf8f2892018-08-09 20:47:01 +0000546 zOld = sqlite3NameFromToken(db, pOld);
547 if( !zOld ) goto exit_rename_column;
548 for(iCol=0; iCol<pTab->nCol; iCol++){
549 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break;
550 }
551 if( iCol==pTab->nCol ){
552 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld);
553 goto exit_rename_column;
554 }
555
drh4a2c7472018-08-13 15:09:48 +0000556 /* Do the rename operation using a recursive UPDATE statement that
557 ** uses the sqlite_rename_column() SQL function to compute the new
558 ** CREATE statement text for the sqlite_master table.
559 */
dancf8f2892018-08-09 20:47:01 +0000560 zNew = sqlite3NameFromToken(db, pNew);
561 if( !zNew ) goto exit_rename_column;
dan404c3ba2018-08-11 20:38:33 +0000562 assert( pNew->n>0 );
563 bQuote = sqlite3Isquote(pNew->z[0]);
dancf8f2892018-08-09 20:47:01 +0000564 sqlite3NestedParse(pParse,
565 "UPDATE \"%w\".%s SET "
danb87a9a82018-09-01 20:23:28 +0000566 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) "
dan499b8252018-08-17 18:08:28 +0000567 "WHERE name NOT LIKE 'sqlite_%%' AND (type != 'index' OR tbl_name = %Q)"
568 " AND sql NOT LIKE 'create virtual%%'",
dan987db762018-08-14 20:18:50 +0000569 zDb, MASTER_NAME,
danb87a9a82018-09-01 20:23:28 +0000570 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
dan987db762018-08-14 20:18:50 +0000571 pTab->zName
dancf8f2892018-08-09 20:47:01 +0000572 );
573
dan9d324822018-08-30 20:03:44 +0000574 sqlite3NestedParse(pParse,
575 "UPDATE temp.%s SET "
danb87a9a82018-09-01 20:23:28 +0000576 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) "
dan9d324822018-08-30 20:03:44 +0000577 "WHERE type IN ('trigger', 'view')",
578 MASTER_NAME,
579 zDb, pTab->zName, iCol, zNew, bQuote
580 );
581
dane325ffe2018-08-11 13:40:20 +0000582 /* Drop and reload the database schema. */
dan09236502018-09-01 16:05:50 +0000583 renameReloadSchema(pParse, iSchema);
dan9d324822018-08-30 20:03:44 +0000584 renameTestSchema(pParse, zDb, iSchema==1);
dan0d5fa6b2018-08-24 17:55:49 +0000585
dancf8f2892018-08-09 20:47:01 +0000586 exit_rename_column:
587 sqlite3SrcListDelete(db, pSrc);
588 sqlite3DbFree(db, zOld);
589 sqlite3DbFree(db, zNew);
590 return;
591}
592
drh4a2c7472018-08-13 15:09:48 +0000593/*
594** Each RenameToken object maps an element of the parse tree into
595** the token that generated that element. The parse tree element
596** might be one of:
597**
598** * A pointer to an Expr that represents an ID
599** * The name of a table column in Column.zName
600**
601** A list of RenameToken objects can be constructed during parsing.
dan07e95232018-08-21 16:32:53 +0000602** Each new object is created by sqlite3RenameTokenMap().
603** As the parse tree is transformed, the sqlite3RenameTokenRemap()
drh4a2c7472018-08-13 15:09:48 +0000604** routine is used to keep the mapping current.
605**
606** After the parse finishes, renameTokenFind() routine can be used
607** to look up the actual token value that created some element in
608** the parse tree.
609*/
dancf8f2892018-08-09 20:47:01 +0000610struct RenameToken {
drh4a2c7472018-08-13 15:09:48 +0000611 void *p; /* Parse tree element created by token t */
612 Token t; /* The token that created parse tree element p */
613 RenameToken *pNext; /* Next is a list of all RenameToken objects */
dancf8f2892018-08-09 20:47:01 +0000614};
615
drh4a2c7472018-08-13 15:09:48 +0000616/*
617** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
618** down into the Walker.
619*/
dan5496d6a2018-08-13 17:14:26 +0000620typedef struct RenameCtx RenameCtx;
dancf8f2892018-08-09 20:47:01 +0000621struct RenameCtx {
622 RenameToken *pList; /* List of tokens to overwrite */
623 int nList; /* Number of tokens in pList */
624 int iCol; /* Index of column being renamed */
dan987db762018-08-14 20:18:50 +0000625 Table *pTab; /* Table being ALTERed */
dan5496d6a2018-08-13 17:14:26 +0000626 const char *zOld; /* Old column name */
dancf8f2892018-08-09 20:47:01 +0000627};
628
dan8900a482018-09-05 14:36:05 +0000629#ifdef SQLITE_DEBUG
630/*
631** This function is only for debugging. It performs two tasks:
632**
633** 1. Checks that pointer pPtr does not already appear in the
634** rename-token list.
635**
636** 2. Dereferences each pointer in the rename-token list.
637**
638** The second is most effective when debugging under valgrind or
639** address-sanitizer or similar. If any of these pointers no longer
640** point to valid objects, an exception is raised by the memory-checking
641** tool.
642**
643** The point of this is to prevent comparisons of invalid pointer values.
644** Even though this always seems to work, it is undefined according to the
645** C standard. Example of undefined comparison:
646**
647** sqlite3_free(x);
648** if( x==y ) ...
649**
650** Technically, as x no longer points into a valid object or to the byte
651** following a valid object, it may not be used in comparison operations.
652*/
drh16b870d2018-09-12 15:51:56 +0000653static void renameTokenCheckAll(Parse *pParse, void *pPtr){
dan8900a482018-09-05 14:36:05 +0000654 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){
655 RenameToken *p;
656 u8 i = 0;
657 for(p=pParse->pRename; p; p=p->pNext){
658 if( p->p ){
659 assert( p->p!=pPtr );
660 i += *(u8*)(p->p);
661 }
danc9461ec2018-08-29 21:00:16 +0000662 }
663 }
664}
dan8900a482018-09-05 14:36:05 +0000665#else
666# define renameTokenCheckAll(x,y)
667#endif
danc9461ec2018-08-29 21:00:16 +0000668
drh4a2c7472018-08-13 15:09:48 +0000669/*
670** Add a new RenameToken object mapping parse tree element pPtr into
671** token *pToken to the Parse object currently under construction.
dan07e95232018-08-21 16:32:53 +0000672**
673** Return a copy of pPtr.
drh4a2c7472018-08-13 15:09:48 +0000674*/
dan07e95232018-08-21 16:32:53 +0000675void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){
dancf8f2892018-08-09 20:47:01 +0000676 RenameToken *pNew;
danc9461ec2018-08-29 21:00:16 +0000677 assert( pPtr || pParse->db->mallocFailed );
dan8900a482018-09-05 14:36:05 +0000678 renameTokenCheckAll(pParse, pPtr);
dancf8f2892018-08-09 20:47:01 +0000679 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
680 if( pNew ){
681 pNew->p = pPtr;
682 pNew->t = *pToken;
683 pNew->pNext = pParse->pRename;
684 pParse->pRename = pNew;
685 }
danc9461ec2018-08-29 21:00:16 +0000686
dand145e5f2018-08-21 08:29:48 +0000687 return pPtr;
dancf8f2892018-08-09 20:47:01 +0000688}
689
drh4a2c7472018-08-13 15:09:48 +0000690/*
dan07e95232018-08-21 16:32:53 +0000691** It is assumed that there is already a RenameToken object associated
692** with parse tree element pFrom. This function remaps the associated token
693** to parse tree element pTo.
drh4a2c7472018-08-13 15:09:48 +0000694*/
dan07e95232018-08-21 16:32:53 +0000695void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){
dancf8f2892018-08-09 20:47:01 +0000696 RenameToken *p;
dan8900a482018-09-05 14:36:05 +0000697 renameTokenCheckAll(pParse, pTo);
danc9461ec2018-08-29 21:00:16 +0000698 for(p=pParse->pRename; p; p=p->pNext){
dancf8f2892018-08-09 20:47:01 +0000699 if( p->p==pFrom ){
700 p->p = pTo;
701 break;
702 }
703 }
dancf8f2892018-08-09 20:47:01 +0000704}
705
drh4a2c7472018-08-13 15:09:48 +0000706/*
dan8900a482018-09-05 14:36:05 +0000707** Walker callback used by sqlite3RenameExprUnmap().
708*/
709static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){
710 Parse *pParse = pWalker->pParse;
711 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
712 return WRC_Continue;
713}
714
715/*
716** Remove all nodes that are part of expression pExpr from the rename list.
717*/
718void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){
719 Walker sWalker;
720 memset(&sWalker, 0, sizeof(Walker));
721 sWalker.pParse = pParse;
722 sWalker.xExprCallback = renameUnmapExprCb;
723 sqlite3WalkExpr(&sWalker, pExpr);
724}
725
726/*
dane8ab40d2018-09-12 08:51:48 +0000727** Remove all nodes that are part of expression-list pEList from the
728** rename list.
729*/
730void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){
731 if( pEList ){
732 int i;
733 Walker sWalker;
734 memset(&sWalker, 0, sizeof(Walker));
735 sWalker.pParse = pParse;
736 sWalker.xExprCallback = renameUnmapExprCb;
737 sqlite3WalkExprList(&sWalker, pEList);
738 for(i=0; i<pEList->nExpr; i++){
739 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zName);
740 }
741 }
742}
743
744/*
drh4a2c7472018-08-13 15:09:48 +0000745** Free the list of RenameToken objects given in the second argument
746*/
dancf8f2892018-08-09 20:47:01 +0000747static void renameTokenFree(sqlite3 *db, RenameToken *pToken){
748 RenameToken *pNext;
749 RenameToken *p;
750 for(p=pToken; p; p=pNext){
751 pNext = p->pNext;
752 sqlite3DbFree(db, p);
753 }
754}
755
dan987db762018-08-14 20:18:50 +0000756/*
757** Search the Parse object passed as the first argument for a RenameToken
758** object associated with parse tree element pPtr. If found, remove it
759** from the Parse object and add it to the list maintained by the
760** RenameCtx object passed as the second argument.
761*/
762static void renameTokenFind(Parse *pParse, struct RenameCtx *pCtx, void *pPtr){
dancf8f2892018-08-09 20:47:01 +0000763 RenameToken **pp;
dan1b0c5de2018-08-24 16:04:26 +0000764 assert( pPtr!=0 );
dancf8f2892018-08-09 20:47:01 +0000765 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
766 if( (*pp)->p==pPtr ){
767 RenameToken *pToken = *pp;
768 *pp = pToken->pNext;
dan5496d6a2018-08-13 17:14:26 +0000769 pToken->pNext = pCtx->pList;
770 pCtx->pList = pToken;
771 pCtx->nList++;
772 break;
dancf8f2892018-08-09 20:47:01 +0000773 }
774 }
dancf8f2892018-08-09 20:47:01 +0000775}
776
dan24fedb92018-08-18 17:35:38 +0000777/*
778** This is a Walker select callback. It does nothing. It is only required
779** because without a dummy callback, sqlite3WalkExpr() and similar do not
780** descend into sub-select statements.
781*/
dan987db762018-08-14 20:18:50 +0000782static int renameColumnSelectCb(Walker *pWalker, Select *p){
drh38d99642018-08-18 18:27:18 +0000783 UNUSED_PARAMETER(pWalker);
784 UNUSED_PARAMETER(p);
dan987db762018-08-14 20:18:50 +0000785 return WRC_Continue;
786}
787
dan987db762018-08-14 20:18:50 +0000788/*
789** This is a Walker expression callback.
790**
791** For every TK_COLUMN node in the expression tree, search to see
792** if the column being references is the column being renamed by an
793** ALTER TABLE statement. If it is, then attach its associated
794** RenameToken object to the list of RenameToken objects being
795** constructed in RenameCtx object at pWalker->u.pRename.
796*/
dancf8f2892018-08-09 20:47:01 +0000797static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){
dan5496d6a2018-08-13 17:14:26 +0000798 RenameCtx *p = pWalker->u.pRename;
dan0cbb0b12018-08-16 19:49:16 +0000799 if( pExpr->op==TK_TRIGGER
800 && pExpr->iColumn==p->iCol
801 && pWalker->pParse->pTriggerTab==p->pTab
802 ){
dan5be60c52018-08-15 20:28:39 +0000803 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dan0cbb0b12018-08-16 19:49:16 +0000804 }else if( pExpr->op==TK_COLUMN
805 && pExpr->iColumn==p->iCol
drh8477f7f2018-09-19 20:14:48 +0000806 && ALWAYS(pExpr->eX==EX_Tab)
807 && p->pTab==pExpr->x.pTab
dan987db762018-08-14 20:18:50 +0000808 ){
dan5496d6a2018-08-13 17:14:26 +0000809 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
dancf8f2892018-08-09 20:47:01 +0000810 }
811 return WRC_Continue;
812}
813
dan987db762018-08-14 20:18:50 +0000814/*
815** The RenameCtx contains a list of tokens that reference a column that
dan24fedb92018-08-18 17:35:38 +0000816** is being renamed by an ALTER TABLE statement. Return the "last"
dan987db762018-08-14 20:18:50 +0000817** RenameToken in the RenameCtx and remove that RenameToken from the
dan24fedb92018-08-18 17:35:38 +0000818** RenameContext. "Last" means the last RenameToken encountered when
819** the input SQL is parsed from left to right. Repeated calls to this routine
dan987db762018-08-14 20:18:50 +0000820** return all column name tokens in the order that they are encountered
821** in the SQL statement.
822*/
dan5496d6a2018-08-13 17:14:26 +0000823static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){
dancf8f2892018-08-09 20:47:01 +0000824 RenameToken *pBest = pCtx->pList;
825 RenameToken *pToken;
826 RenameToken **pp;
827
828 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
829 if( pToken->t.z>pBest->t.z ) pBest = pToken;
830 }
831 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
832 *pp = pBest->pNext;
833
834 return pBest;
835}
836
dan6fe7f232018-08-10 19:19:33 +0000837/*
dan24fedb92018-08-18 17:35:38 +0000838** An error occured while parsing or otherwise processing a database
839** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
840** ALTER TABLE RENAME COLUMN program. The error message emitted by the
841** sub-routine is currently stored in pParse->zErrMsg. This function
842** adds context to the error message and then stores it in pCtx.
843*/
danb0137382018-08-20 20:01:01 +0000844static void renameColumnParseError(
845 sqlite3_context *pCtx,
dan0d5fa6b2018-08-24 17:55:49 +0000846 int bPost,
danb0137382018-08-20 20:01:01 +0000847 sqlite3_value *pType,
848 sqlite3_value *pObject,
849 Parse *pParse
850){
drh79a5ee92018-08-23 19:32:04 +0000851 const char *zT = (const char*)sqlite3_value_text(pType);
852 const char *zN = (const char*)sqlite3_value_text(pObject);
dan24fedb92018-08-18 17:35:38 +0000853 char *zErr;
danb0137382018-08-20 20:01:01 +0000854
dan0d5fa6b2018-08-24 17:55:49 +0000855 zErr = sqlite3_mprintf("error in %s %s%s: %s",
856 zT, zN, (bPost ? " after rename" : ""),
857 pParse->zErrMsg
858 );
dan24fedb92018-08-18 17:35:38 +0000859 sqlite3_result_error(pCtx, zErr, -1);
860 sqlite3_free(zErr);
861}
862
863/*
dan06249392018-08-21 15:06:59 +0000864** For each name in the the expression-list pEList (i.e. each
865** pEList->a[i].zName) that matches the string in zOld, extract the
866** corresponding rename-token from Parse object pParse and add it
867** to the RenameCtx pCtx.
868*/
869static void renameColumnElistNames(
870 Parse *pParse,
871 RenameCtx *pCtx,
872 ExprList *pEList,
873 const char *zOld
874){
875 if( pEList ){
876 int i;
877 for(i=0; i<pEList->nExpr; i++){
878 char *zName = pEList->a[i].zName;
879 if( 0==sqlite3_stricmp(zName, zOld) ){
880 renameTokenFind(pParse, pCtx, (void*)zName);
881 }
882 }
883 }
884}
885
886/*
887** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
888** that matches the string in zOld, extract the corresponding rename-token
889** from Parse object pParse and add it to the RenameCtx pCtx.
890*/
891static void renameColumnIdlistNames(
892 Parse *pParse,
893 RenameCtx *pCtx,
894 IdList *pIdList,
895 const char *zOld
896){
897 if( pIdList ){
898 int i;
899 for(i=0; i<pIdList->nId; i++){
900 char *zName = pIdList->a[i].zName;
901 if( 0==sqlite3_stricmp(zName, zOld) ){
902 renameTokenFind(pParse, pCtx, (void*)zName);
903 }
904 }
905 }
906}
907
dandd1a9c82018-09-05 08:28:30 +0000908/*
909** Parse the SQL statement zSql using Parse object (*p). The Parse object
910** is initialized by this function before it is used.
911*/
danc9461ec2018-08-29 21:00:16 +0000912static int renameParseSql(
dandd1a9c82018-09-05 08:28:30 +0000913 Parse *p, /* Memory to use for Parse object */
914 const char *zDb, /* Name of schema SQL belongs to */
915 int bTable, /* 1 -> RENAME TABLE, 0 -> RENAME COLUMN */
916 sqlite3 *db, /* Database handle */
917 const char *zSql, /* SQL to parse */
918 int bTemp /* True if SQL is from temp schema */
danc9461ec2018-08-29 21:00:16 +0000919){
920 int rc;
921 char *zErr = 0;
922
923 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
924
925 /* Parse the SQL statement passed as the first argument. If no error
926 ** occurs and the parse does not result in a new table, index or
927 ** trigger object, the database must be corrupt. */
928 memset(p, 0, sizeof(Parse));
929 p->eParseMode = (bTable ? PARSE_MODE_RENAME_TABLE : PARSE_MODE_RENAME_COLUMN);
930 p->db = db;
931 p->nQueryLoop = 1;
932 rc = sqlite3RunParser(p, zSql, &zErr);
933 assert( p->zErrMsg==0 );
934 assert( rc!=SQLITE_OK || zErr==0 );
935 assert( (0!=p->pNewTable) + (0!=p->pNewIndex) + (0!=p->pNewTrigger)<2 );
936 p->zErrMsg = zErr;
937 if( db->mallocFailed ) rc = SQLITE_NOMEM;
938 if( rc==SQLITE_OK
939 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0
940 ){
941 rc = SQLITE_CORRUPT_BKPT;
942 }
943
944#ifdef SQLITE_DEBUG
945 /* Ensure that all mappings in the Parse.pRename list really do map to
946 ** a part of the input string. */
947 if( rc==SQLITE_OK ){
948 int nSql = sqlite3Strlen30(zSql);
949 RenameToken *pToken;
950 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
951 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
952 }
953 }
954#endif
955
956 db->init.iDb = 0;
957 return rc;
958}
959
dandd1a9c82018-09-05 08:28:30 +0000960/*
961** This function edits SQL statement zSql, replacing each token identified
962** by the linked list pRename with the text of zNew. If argument bQuote is
963** true, then zNew is always quoted first. If no error occurs, the result
964** is loaded into context object pCtx as the result.
965**
966** Or, if an error occurs (i.e. an OOM condition), an error is left in
967** pCtx and an SQLite error code returned.
968*/
danc9461ec2018-08-29 21:00:16 +0000969static int renameEditSql(
970 sqlite3_context *pCtx, /* Return result here */
971 RenameCtx *pRename, /* Rename context */
972 const char *zSql, /* SQL statement to edit */
973 const char *zNew, /* New token text */
974 int bQuote /* True to always quote token */
975){
976 int nNew = sqlite3Strlen30(zNew);
977 int nSql = sqlite3Strlen30(zSql);
978 sqlite3 *db = sqlite3_context_db_handle(pCtx);
979 int rc = SQLITE_OK;
980 char *zQuot;
981 char *zOut;
982 int nQuot;
983
984 /* Set zQuot to point to a buffer containing a quoted copy of the
985 ** identifier zNew. If the corresponding identifier in the original
986 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to
987 ** point to zQuot so that all substitutions are made using the
988 ** quoted version of the new column name. */
drhc753c212018-09-01 16:55:36 +0000989 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew);
danc9461ec2018-08-29 21:00:16 +0000990 if( zQuot==0 ){
991 return SQLITE_NOMEM;
992 }else{
993 nQuot = sqlite3Strlen30(zQuot);
994 }
995 if( bQuote ){
996 zNew = zQuot;
997 nNew = nQuot;
998 }
999
1000 /* At this point pRename->pList contains a list of RenameToken objects
1001 ** corresponding to all tokens in the input SQL that must be replaced
1002 ** with the new column name. All that remains is to construct and
1003 ** return the edited SQL string. */
1004 assert( nQuot>=nNew );
1005 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
1006 if( zOut ){
1007 int nOut = nSql;
1008 memcpy(zOut, zSql, nSql);
1009 while( pRename->pList ){
1010 int iOff; /* Offset of token to replace in zOut */
1011 RenameToken *pBest = renameColumnTokenNext(pRename);
1012
1013 u32 nReplace;
1014 const char *zReplace;
1015 if( sqlite3IsIdChar(*pBest->t.z) ){
1016 nReplace = nNew;
1017 zReplace = zNew;
1018 }else{
1019 nReplace = nQuot;
1020 zReplace = zQuot;
1021 }
1022
1023 iOff = pBest->t.z - zSql;
1024 if( pBest->t.n!=nReplace ){
1025 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
1026 nOut - (iOff + pBest->t.n)
1027 );
1028 nOut += nReplace - pBest->t.n;
1029 zOut[nOut] = '\0';
1030 }
1031 memcpy(&zOut[iOff], zReplace, nReplace);
1032 sqlite3DbFree(db, pBest);
1033 }
1034
1035 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
1036 sqlite3DbFree(db, zOut);
1037 }else{
1038 rc = SQLITE_NOMEM;
1039 }
1040
1041 sqlite3_free(zQuot);
1042 return rc;
1043}
1044
dandd1a9c82018-09-05 08:28:30 +00001045/*
1046** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
1047** it was read from the schema of database zDb. Return SQLITE_OK if
1048** successful. Otherwise, return an SQLite error code and leave an error
1049** message in the Parse object.
1050*/
1051static int renameResolveTrigger(Parse *pParse, const char *zDb){
danc9461ec2018-08-29 21:00:16 +00001052 sqlite3 *db = pParse->db;
dand5e6fef2018-09-07 15:50:31 +00001053 Trigger *pNew = pParse->pNewTrigger;
danc9461ec2018-08-29 21:00:16 +00001054 TriggerStep *pStep;
1055 NameContext sNC;
1056 int rc = SQLITE_OK;
1057
1058 memset(&sNC, 0, sizeof(sNC));
1059 sNC.pParse = pParse;
dand5e6fef2018-09-07 15:50:31 +00001060 assert( pNew->pTabSchema );
1061 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
1062 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
1063 );
1064 pParse->eTriggerOp = pNew->op;
danc9461ec2018-08-29 21:00:16 +00001065
1066 /* Resolve symbols in WHEN clause */
dand5e6fef2018-09-07 15:50:31 +00001067 if( pNew->pWhen ){
1068 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
danc9461ec2018-08-29 21:00:16 +00001069 }
1070
dand5e6fef2018-09-07 15:50:31 +00001071 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
danc9461ec2018-08-29 21:00:16 +00001072 if( pStep->pSelect ){
1073 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
1074 if( pParse->nErr ) rc = pParse->rc;
1075 }
dand5e6fef2018-09-07 15:50:31 +00001076 if( rc==SQLITE_OK && pStep->zTarget ){
danc9461ec2018-08-29 21:00:16 +00001077 Table *pTarget = sqlite3LocateTable(pParse, 0, pStep->zTarget, zDb);
1078 if( pTarget==0 ){
1079 rc = SQLITE_ERROR;
dande79e092018-09-17 13:38:45 +00001080 }else if( SQLITE_OK==(rc = sqlite3ViewGetColumnNames(pParse, pTarget)) ){
danc9461ec2018-08-29 21:00:16 +00001081 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
dandd1a9c82018-09-05 08:28:30 +00001119/*
1120** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr
1121** objects that are part of the trigger passed as the second argument.
1122*/
danc9461ec2018-08-29 21:00:16 +00001123static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){
1124 TriggerStep *pStep;
1125
1126 /* Find tokens to edit in WHEN clause */
1127 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
1128
1129 /* Find tokens to edit in trigger steps */
1130 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1131 sqlite3WalkSelect(pWalker, pStep->pSelect);
1132 sqlite3WalkExpr(pWalker, pStep->pWhere);
1133 sqlite3WalkExprList(pWalker, pStep->pExprList);
1134 if( pStep->pUpsert ){
1135 Upsert *pUpsert = pStep->pUpsert;
1136 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
1137 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
1138 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
1139 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
1140 }
1141 }
1142}
1143
dandd1a9c82018-09-05 08:28:30 +00001144/*
1145** Free the contents of Parse object (*pParse). Do not free the memory
1146** occupied by the Parse object itself.
1147*/
dan141e1192018-08-31 18:23:53 +00001148static void renameParseCleanup(Parse *pParse){
1149 sqlite3 *db = pParse->db;
1150 if( pParse->pVdbe ){
1151 sqlite3VdbeFinalize(pParse->pVdbe);
1152 }
1153 sqlite3DeleteTable(db, pParse->pNewTable);
1154 if( pParse->pNewIndex ) sqlite3FreeIndex(db, pParse->pNewIndex);
1155 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
1156 sqlite3DbFree(db, pParse->zErrMsg);
1157 renameTokenFree(db, pParse->pRename);
1158 sqlite3ParserReset(pParse);
1159}
1160
dan06249392018-08-21 15:06:59 +00001161/*
dan987db762018-08-14 20:18:50 +00001162** SQL function:
1163**
1164** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld)
1165**
1166** 0. zSql: SQL statement to rewrite
danb0137382018-08-20 20:01:01 +00001167** 1. type: Type of object ("table", "view" etc.)
1168** 2. object: Name of object
1169** 3. Database: Database name (e.g. "main")
1170** 4. Table: Table name
1171** 5. iCol: Index of column to rename
1172** 6. zNew: New column name
dan9d324822018-08-30 20:03:44 +00001173** 7. bQuote: Non-zero if the new column name should be quoted.
danb87a9a82018-09-01 20:23:28 +00001174** 8. bTemp: True if zSql comes from temp schema
dan987db762018-08-14 20:18:50 +00001175**
1176** Do a column rename operation on the CREATE statement given in zSql.
1177** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
1178** into zNew. The name should be quoted if bQuote is true.
1179**
1180** This function is used internally by the ALTER TABLE RENAME COLUMN command.
1181** Though accessible to application code, it is not intended for use by
1182** applications. The existance of this function, and the way it works,
1183** is subject to change without notice.
1184**
1185** If any of the parameters are out-of-bounds, then simply return NULL.
1186** An out-of-bounds parameter can only occur when the application calls
1187** this function directly. The parameters will always be well-formed when
1188** this routine is invoked by the bytecode for a legitimate ALTER TABLE
1189** statement.
dan6fe7f232018-08-10 19:19:33 +00001190*/
dancf8f2892018-08-09 20:47:01 +00001191static void renameColumnFunc(
1192 sqlite3_context *context,
1193 int NotUsed,
1194 sqlite3_value **argv
1195){
1196 sqlite3 *db = sqlite3_context_db_handle(context);
dan5496d6a2018-08-13 17:14:26 +00001197 RenameCtx sCtx;
drhad866a12018-08-10 19:33:09 +00001198 const char *zSql = (const char*)sqlite3_value_text(argv[0]);
danb0137382018-08-20 20:01:01 +00001199 const char *zDb = (const char*)sqlite3_value_text(argv[3]);
1200 const char *zTable = (const char*)sqlite3_value_text(argv[4]);
1201 int iCol = sqlite3_value_int(argv[5]);
1202 const char *zNew = (const char*)sqlite3_value_text(argv[6]);
danb0137382018-08-20 20:01:01 +00001203 int bQuote = sqlite3_value_int(argv[7]);
danb87a9a82018-09-01 20:23:28 +00001204 int bTemp = sqlite3_value_int(argv[8]);
dan987db762018-08-14 20:18:50 +00001205 const char *zOld;
dancf8f2892018-08-09 20:47:01 +00001206 int rc;
dancf8f2892018-08-09 20:47:01 +00001207 Parse sParse;
1208 Walker sWalker;
dancf8f2892018-08-09 20:47:01 +00001209 Index *pIdx;
dancf8f2892018-08-09 20:47:01 +00001210 int i;
dan987db762018-08-14 20:18:50 +00001211 Table *pTab;
dan141e1192018-08-31 18:23:53 +00001212#ifndef SQLITE_OMIT_AUTHORIZATION
1213 sqlite3_xauth xAuth = db->xAuth;
1214#endif
dancf8f2892018-08-09 20:47:01 +00001215
drh38d99642018-08-18 18:27:18 +00001216 UNUSED_PARAMETER(NotUsed);
dan987db762018-08-14 20:18:50 +00001217 if( zSql==0 ) return;
dan987db762018-08-14 20:18:50 +00001218 if( zTable==0 ) return;
danb0137382018-08-20 20:01:01 +00001219 if( zNew==0 ) return;
dan987db762018-08-14 20:18:50 +00001220 if( iCol<0 ) return;
drhda76adc2018-08-25 02:04:05 +00001221 sqlite3BtreeEnterAll(db);
dan987db762018-08-14 20:18:50 +00001222 pTab = sqlite3FindTable(db, zTable, zDb);
drhda76adc2018-08-25 02:04:05 +00001223 if( pTab==0 || iCol>=pTab->nCol ){
1224 sqlite3BtreeLeaveAll(db);
1225 return;
1226 }
dan987db762018-08-14 20:18:50 +00001227 zOld = pTab->aCol[iCol].zName;
dancf8f2892018-08-09 20:47:01 +00001228 memset(&sCtx, 0, sizeof(sCtx));
dan987db762018-08-14 20:18:50 +00001229 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
dancf8f2892018-08-09 20:47:01 +00001230
dan141e1192018-08-31 18:23:53 +00001231#ifndef SQLITE_OMIT_AUTHORIZATION
1232 db->xAuth = 0;
1233#endif
danc9461ec2018-08-29 21:00:16 +00001234 rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp);
dan24fedb92018-08-18 17:35:38 +00001235
dancf8f2892018-08-09 20:47:01 +00001236 /* Find tokens that need to be replaced. */
1237 memset(&sWalker, 0, sizeof(Walker));
1238 sWalker.pParse = &sParse;
1239 sWalker.xExprCallback = renameColumnExprCb;
dan987db762018-08-14 20:18:50 +00001240 sWalker.xSelectCallback = renameColumnSelectCb;
dancf8f2892018-08-09 20:47:01 +00001241 sWalker.u.pRename = &sCtx;
1242
dan0cbb0b12018-08-16 19:49:16 +00001243 sCtx.pTab = pTab;
dan987db762018-08-14 20:18:50 +00001244 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dancf8f2892018-08-09 20:47:01 +00001245 if( sParse.pNewTable ){
dan987db762018-08-14 20:18:50 +00001246 Select *pSelect = sParse.pNewTable->pSelect;
1247 if( pSelect ){
dan987db762018-08-14 20:18:50 +00001248 sParse.rc = SQLITE_OK;
1249 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0);
1250 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
1251 if( rc==SQLITE_OK ){
1252 sqlite3WalkSelect(&sWalker, pSelect);
dana8762ae2018-08-11 17:49:23 +00001253 }
dan987db762018-08-14 20:18:50 +00001254 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
1255 }else{
1256 /* A regular table */
1257 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
1258 FKey *pFKey;
1259 assert( sParse.pNewTable->pSelect==0 );
dan0cbb0b12018-08-16 19:49:16 +00001260 sCtx.pTab = sParse.pNewTable;
dan987db762018-08-14 20:18:50 +00001261 if( bFKOnly==0 ){
1262 renameTokenFind(
1263 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName
1264 );
1265 if( sCtx.iCol<0 ){
1266 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
dancf8f2892018-08-09 20:47:01 +00001267 }
dan987db762018-08-14 20:18:50 +00001268 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
1269 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
1270 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
1271 }
1272 }
1273
1274 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1275 for(i=0; i<pFKey->nCol; i++){
dan356afab2018-08-14 21:05:35 +00001276 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
dan987db762018-08-14 20:18:50 +00001277 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
1278 }
1279 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
1280 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
1281 ){
1282 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
1283 }
dan6fe7f232018-08-10 19:19:33 +00001284 }
dancf8f2892018-08-09 20:47:01 +00001285 }
1286 }
dan5496d6a2018-08-13 17:14:26 +00001287 }else if( sParse.pNewIndex ){
dancf8f2892018-08-09 20:47:01 +00001288 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
1289 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
dan5496d6a2018-08-13 17:14:26 +00001290 }else{
dan5be60c52018-08-15 20:28:39 +00001291 /* A trigger */
1292 TriggerStep *pStep;
dan0ccda962018-08-30 16:26:48 +00001293 rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb));
danc9461ec2018-08-29 21:00:16 +00001294 if( rc!=SQLITE_OK ) goto renameColumnFunc_done;
dan5be60c52018-08-15 20:28:39 +00001295
danc9461ec2018-08-29 21:00:16 +00001296 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
1297 if( pStep->zTarget ){
dan06249392018-08-21 15:06:59 +00001298 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
danc9461ec2018-08-29 21:00:16 +00001299 if( pTarget==pTab ){
dan0cbb0b12018-08-16 19:49:16 +00001300 if( pStep->pUpsert ){
danc9461ec2018-08-29 21:00:16 +00001301 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
1302 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld);
dan0cbb0b12018-08-16 19:49:16 +00001303 }
danc9461ec2018-08-29 21:00:16 +00001304 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
1305 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
dan5be60c52018-08-15 20:28:39 +00001306 }
1307 }
1308 }
1309
dan5be60c52018-08-15 20:28:39 +00001310
1311 /* Find tokens to edit in UPDATE OF clause */
dan06249392018-08-21 15:06:59 +00001312 if( sParse.pTriggerTab==pTab ){
1313 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
dan5496d6a2018-08-13 17:14:26 +00001314 }
dan5be60c52018-08-15 20:28:39 +00001315
danc9461ec2018-08-29 21:00:16 +00001316 /* Find tokens to edit in various expressions and selects */
1317 renameWalkTrigger(&sWalker, sParse.pNewTrigger);
dancf8f2892018-08-09 20:47:01 +00001318 }
1319
dan987db762018-08-14 20:18:50 +00001320 assert( rc==SQLITE_OK );
danc9461ec2018-08-29 21:00:16 +00001321 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote);
dancf8f2892018-08-09 20:47:01 +00001322
drh5fc22cd2018-08-13 13:43:11 +00001323renameColumnFunc_done:
dan987db762018-08-14 20:18:50 +00001324 if( rc!=SQLITE_OK ){
dan24fedb92018-08-18 17:35:38 +00001325 if( sParse.zErrMsg ){
dan9d324822018-08-30 20:03:44 +00001326 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
dan987db762018-08-14 20:18:50 +00001327 }else{
1328 sqlite3_result_error_code(context, rc);
1329 }
1330 }
1331
dan141e1192018-08-31 18:23:53 +00001332 renameParseCleanup(&sParse);
drh4a2c7472018-08-13 15:09:48 +00001333 renameTokenFree(db, sCtx.pList);
dan141e1192018-08-31 18:23:53 +00001334#ifndef SQLITE_OMIT_AUTHORIZATION
1335 db->xAuth = xAuth;
1336#endif
drhda76adc2018-08-25 02:04:05 +00001337 sqlite3BtreeLeaveAll(db);
dancf8f2892018-08-09 20:47:01 +00001338}
1339
dandd1a9c82018-09-05 08:28:30 +00001340/*
1341** Walker expression callback used by "RENAME TABLE".
1342*/
danc9461ec2018-08-29 21:00:16 +00001343static int renameTableExprCb(Walker *pWalker, Expr *pExpr){
1344 RenameCtx *p = pWalker->u.pRename;
drh8477f7f2018-09-19 20:14:48 +00001345 if( pExpr->op==TK_COLUMN
1346 && ALWAYS(pExpr->eX==EX_Tab)
1347 && p->pTab==pExpr->x.pTab
1348 ){
1349 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->x.pTab);
danc9461ec2018-08-29 21:00:16 +00001350 }
1351 return WRC_Continue;
1352}
1353
1354/*
dandd1a9c82018-09-05 08:28:30 +00001355** Walker select callback used by "RENAME TABLE".
danc9461ec2018-08-29 21:00:16 +00001356*/
1357static int renameTableSelectCb(Walker *pWalker, Select *pSelect){
1358 int i;
1359 RenameCtx *p = pWalker->u.pRename;
1360 SrcList *pSrc = pSelect->pSrc;
1361 for(i=0; i<pSrc->nSrc; i++){
1362 struct SrcList_item *pItem = &pSrc->a[i];
1363 if( pItem->pTab==p->pTab ){
1364 renameTokenFind(pWalker->pParse, p, pItem->zName);
1365 }
1366 }
1367
1368 return WRC_Continue;
1369}
1370
1371
1372/*
1373** This C function implements an SQL user function that is used by SQL code
1374** generated by the ALTER TABLE ... RENAME command to modify the definition
1375** of any foreign key constraints that use the table being renamed as the
1376** parent table. It is passed three arguments:
1377**
dan141e1192018-08-31 18:23:53 +00001378** 0: The database containing the table being renamed.
dan65372fa2018-09-03 20:05:15 +00001379** 1. type: Type of object ("table", "view" etc.)
1380** 2. object: Name of object
1381** 3: The complete text of the schema statement being modified,
1382** 4: The old name of the table being renamed, and
1383** 5: The new name of the table being renamed.
1384** 6: True if the schema statement comes from the temp db.
danc9461ec2018-08-29 21:00:16 +00001385**
dan141e1192018-08-31 18:23:53 +00001386** It returns the new schema statement. For example:
danc9461ec2018-08-29 21:00:16 +00001387**
dan141e1192018-08-31 18:23:53 +00001388** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0)
danc9461ec2018-08-29 21:00:16 +00001389** -> 'CREATE TABLE t1(a REFERENCES t3)'
1390*/
1391static void renameTableFunc(
1392 sqlite3_context *context,
1393 int NotUsed,
1394 sqlite3_value **argv
1395){
1396 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001397 const char *zDb = (const char*)sqlite3_value_text(argv[0]);
dan65372fa2018-09-03 20:05:15 +00001398 const char *zInput = (const char*)sqlite3_value_text(argv[3]);
1399 const char *zOld = (const char*)sqlite3_value_text(argv[4]);
1400 const char *zNew = (const char*)sqlite3_value_text(argv[5]);
1401 int bTemp = sqlite3_value_int(argv[6]);
drh5b1da302018-09-01 20:02:07 +00001402 UNUSED_PARAMETER(NotUsed);
danc9461ec2018-08-29 21:00:16 +00001403
dan141e1192018-08-31 18:23:53 +00001404 if( zInput && zOld && zNew ){
dan141e1192018-08-31 18:23:53 +00001405 Parse sParse;
1406 int rc;
1407 int bQuote = 1;
1408 RenameCtx sCtx;
1409 Walker sWalker;
danc9461ec2018-08-29 21:00:16 +00001410
dan141e1192018-08-31 18:23:53 +00001411#ifndef SQLITE_OMIT_AUTHORIZATION
1412 sqlite3_xauth xAuth = db->xAuth;
1413 db->xAuth = 0;
danc9461ec2018-08-29 21:00:16 +00001414#endif
1415
dan141e1192018-08-31 18:23:53 +00001416 sqlite3BtreeEnterAll(db);
1417
1418 memset(&sCtx, 0, sizeof(RenameCtx));
1419 sCtx.pTab = sqlite3FindTable(db, zOld, zDb);
1420 memset(&sWalker, 0, sizeof(Walker));
1421 sWalker.pParse = &sParse;
1422 sWalker.xExprCallback = renameTableExprCb;
1423 sWalker.xSelectCallback = renameTableSelectCb;
1424 sWalker.u.pRename = &sCtx;
1425
1426 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1427
1428 if( rc==SQLITE_OK ){
1429 if( sParse.pNewTable ){
1430 Table *pTab = sParse.pNewTable;
1431
1432 if( pTab->pSelect ){
1433 NameContext sNC;
1434 memset(&sNC, 0, sizeof(sNC));
1435 sNC.pParse = &sParse;
1436
1437 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC);
1438 if( sParse.nErr ) rc = sParse.rc;
1439 sqlite3WalkSelect(&sWalker, pTab->pSelect);
1440 }else{
1441 /* Modify any FK definitions to point to the new table. */
1442#ifndef SQLITE_OMIT_FOREIGN_KEY
dan202a0272018-09-07 11:51:21 +00001443 if( db->flags & SQLITE_ForeignKeys ){
1444 FKey *pFKey;
1445 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
1446 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
1447 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
1448 }
dan141e1192018-08-31 18:23:53 +00001449 }
1450 }
1451#endif
1452
1453 /* If this is the table being altered, fix any table refs in CHECK
1454 ** expressions. Also update the name that appears right after the
1455 ** "CREATE [VIRTUAL] TABLE" bit. */
1456 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
1457 sCtx.pTab = pTab;
1458 sqlite3WalkExprList(&sWalker, pTab->pCheck);
1459 renameTokenFind(&sParse, &sCtx, pTab->zName);
1460 }
danc9461ec2018-08-29 21:00:16 +00001461 }
1462 }
danc9461ec2018-08-29 21:00:16 +00001463
dan141e1192018-08-31 18:23:53 +00001464 else if( sParse.pNewIndex ){
1465 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
1466 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
1467 }
danc9461ec2018-08-29 21:00:16 +00001468
1469#ifndef SQLITE_OMIT_TRIGGER
danb87a9a82018-09-01 20:23:28 +00001470 else{
dan141e1192018-08-31 18:23:53 +00001471 Trigger *pTrigger = sParse.pNewTrigger;
1472 TriggerStep *pStep;
1473 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
1474 && sCtx.pTab->pSchema==pTrigger->pTabSchema
1475 ){
1476 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
1477 }
danc9461ec2018-08-29 21:00:16 +00001478
dan141e1192018-08-31 18:23:53 +00001479 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
1480 if( rc==SQLITE_OK ){
1481 renameWalkTrigger(&sWalker, pTrigger);
1482 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
1483 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
1484 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
1485 }
dan0ccda962018-08-30 16:26:48 +00001486 }
danc9461ec2018-08-29 21:00:16 +00001487 }
1488 }
dan141e1192018-08-31 18:23:53 +00001489#endif
danc9461ec2018-08-29 21:00:16 +00001490 }
dan141e1192018-08-31 18:23:53 +00001491
1492 if( rc==SQLITE_OK ){
1493 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote);
1494 }
1495 if( rc!=SQLITE_OK ){
dan65372fa2018-09-03 20:05:15 +00001496 if( sParse.zErrMsg ){
1497 renameColumnParseError(context, 0, argv[1], argv[2], &sParse);
1498 }else{
1499 sqlite3_result_error_code(context, rc);
1500 }
dan141e1192018-08-31 18:23:53 +00001501 }
1502
1503 renameParseCleanup(&sParse);
1504 renameTokenFree(db, sCtx.pList);
1505 sqlite3BtreeLeaveAll(db);
1506#ifndef SQLITE_OMIT_AUTHORIZATION
1507 db->xAuth = xAuth;
danc9461ec2018-08-29 21:00:16 +00001508#endif
1509 }
1510
danc9461ec2018-08-29 21:00:16 +00001511 return;
1512}
1513
dandd1a9c82018-09-05 08:28:30 +00001514/*
1515** An SQL user function that checks that there are no parse or symbol
1516** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement.
1517** After an ALTER TABLE .. RENAME operation is performed and the schema
1518** reloaded, this function is called on each SQL statement in the schema
dan1d85c6b2018-09-06 16:01:37 +00001519** to ensure that it is still usable.
dandd1a9c82018-09-05 08:28:30 +00001520**
1521** 0: Database name ("main", "temp" etc.).
1522** 1: SQL statement.
1523** 2: Object type ("view", "table", "trigger" or "index").
1524** 3: Object name.
1525** 4: True if object is from temp schema.
dan1d85c6b2018-09-06 16:01:37 +00001526**
1527** Unless it finds an error, this function normally returns NULL. However, it
1528** returns integer value 1 if:
1529**
1530** * the SQL argument creates a trigger, and
1531** * the table that the trigger is attached to is in database zDb.
dandd1a9c82018-09-05 08:28:30 +00001532*/
dan9d324822018-08-30 20:03:44 +00001533static void renameTableTest(
1534 sqlite3_context *context,
1535 int NotUsed,
1536 sqlite3_value **argv
1537){
1538 sqlite3 *db = sqlite3_context_db_handle(context);
drh5b1da302018-09-01 20:02:07 +00001539 char const *zDb = (const char*)sqlite3_value_text(argv[0]);
1540 char const *zInput = (const char*)sqlite3_value_text(argv[1]);
dan9d324822018-08-30 20:03:44 +00001541 int bTemp = sqlite3_value_int(argv[4]);
dan9d324822018-08-30 20:03:44 +00001542
dan141e1192018-08-31 18:23:53 +00001543#ifndef SQLITE_OMIT_AUTHORIZATION
1544 sqlite3_xauth xAuth = db->xAuth;
1545 db->xAuth = 0;
1546#endif
1547
drh5b1da302018-09-01 20:02:07 +00001548 UNUSED_PARAMETER(NotUsed);
dan09236502018-09-01 16:05:50 +00001549 if( zDb && zInput ){
1550 int rc;
1551 Parse sParse;
1552 rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp);
1553 if( rc==SQLITE_OK ){
1554 if( sParse.pNewTable && sParse.pNewTable->pSelect ){
1555 NameContext sNC;
1556 memset(&sNC, 0, sizeof(sNC));
1557 sNC.pParse = &sParse;
1558 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC);
1559 if( sParse.nErr ) rc = sParse.rc;
1560 }
1561
1562 else if( sParse.pNewTrigger ){
1563 rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb);
drh3b700452018-09-07 19:12:08 +00001564 if( rc==SQLITE_OK ){
dan1d85c6b2018-09-06 16:01:37 +00001565 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
1566 int i2 = sqlite3FindDbName(db, zDb);
1567 if( i1==i2 ) sqlite3_result_int(context, 1);
1568 }
dan09236502018-09-01 16:05:50 +00001569 }
dan9d324822018-08-30 20:03:44 +00001570 }
1571
dan09236502018-09-01 16:05:50 +00001572 if( rc!=SQLITE_OK ){
1573 renameColumnParseError(context, 1, argv[2], argv[3], &sParse);
dan9d324822018-08-30 20:03:44 +00001574 }
dan09236502018-09-01 16:05:50 +00001575 renameParseCleanup(&sParse);
dan9d324822018-08-30 20:03:44 +00001576 }
1577
dan141e1192018-08-31 18:23:53 +00001578#ifndef SQLITE_OMIT_AUTHORIZATION
1579 db->xAuth = xAuth;
1580#endif
dan9d324822018-08-30 20:03:44 +00001581}
1582
dancf8f2892018-08-09 20:47:01 +00001583/*
1584** Register built-in functions used to help implement ALTER TABLE
1585*/
1586void sqlite3AlterFunctions(void){
1587 static FuncDef aAlterTableFuncs[] = {
danb87a9a82018-09-01 20:23:28 +00001588 FUNCTION(sqlite_rename_column, 9, 0, 0, renameColumnFunc),
dan65372fa2018-09-03 20:05:15 +00001589 FUNCTION(sqlite_rename_table, 7, 0, 0, renameTableFunc),
dan9d324822018-08-30 20:03:44 +00001590 FUNCTION(sqlite_rename_test, 5, 0, 0, renameTableTest),
dancf8f2892018-08-09 20:47:01 +00001591 };
1592 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
1593}
drhd0e4a6c2005-02-15 20:47:57 +00001594#endif /* SQLITE_ALTER_TABLE */