blob: 1534fdf69eab969ff04d8c475fecc7077358d917 [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 );
drh1f01ec12005-02-15 21:36:18 +000077 assert( len>0 );
danielk1977182c4ba2007-06-27 15:53:34 +000078 } while( token!=TK_LP && token!=TK_USING );
drh1f01ec12005-02-15 21:36:18 +000079
drhb7916a72009-05-27 10:31:29 +000080 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
drh1f01ec12005-02-15 21:36:18 +000081 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);
dan432cc5b2009-09-26 17:51:48 +0000119 for(z=zInput; *z; z=z+n){
120 n = sqlite3GetToken(z, &token);
121 if( token==TK_REFERENCES ){
122 char *zParent;
123 do {
124 z += n;
125 n = sqlite3GetToken(z, &token);
126 }while( token==TK_SPACE );
127
128 zParent = sqlite3DbStrNDup(db, (const char *)z, n);
drha172c342009-10-08 01:43:55 +0000129 if( zParent==0 ) break;
dan432cc5b2009-09-26 17:51:48 +0000130 sqlite3Dequote(zParent);
131 if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
132 char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
133 (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
134 );
135 sqlite3DbFree(db, zOutput);
136 zOutput = zOut;
137 zInput = &z[n];
138 }
139 sqlite3DbFree(db, zParent);
140 }
141 }
142
143 zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
144 sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
145 sqlite3DbFree(db, zOutput);
146}
147#endif
148
drh1f01ec12005-02-15 21:36:18 +0000149#ifndef SQLITE_OMIT_TRIGGER
drhf11c34d2006-09-08 12:27:36 +0000150/* This function is used by SQL generated to implement the
drh1f01ec12005-02-15 21:36:18 +0000151** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
152** statement. The second is a table name. The table name in the CREATE
drhf11c34d2006-09-08 12:27:36 +0000153** TRIGGER statement is replaced with the third argument and the result
drh1f01ec12005-02-15 21:36:18 +0000154** returned. This is analagous to renameTableFunc() above, except for CREATE
155** TRIGGER, not CREATE INDEX and CREATE TABLE.
156*/
157static void renameTriggerFunc(
158 sqlite3_context *context,
danielk197762c14b32008-11-19 09:05:26 +0000159 int NotUsed,
drh1f01ec12005-02-15 21:36:18 +0000160 sqlite3_value **argv
161){
162 unsigned char const *zSql = sqlite3_value_text(argv[0]);
163 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
164
165 int token;
166 Token tname;
167 int dist = 3;
drh2646da72005-12-09 20:02:05 +0000168 unsigned char const *zCsr = zSql;
drh1f01ec12005-02-15 21:36:18 +0000169 int len = 0;
170 char *zRet;
drhfa4a4b92008-03-19 21:45:51 +0000171 sqlite3 *db = sqlite3_context_db_handle(context);
danielk19771e536952007-08-16 10:09:01 +0000172
danielk197762c14b32008-11-19 09:05:26 +0000173 UNUSED_PARAMETER(NotUsed);
174
drh1f01ec12005-02-15 21:36:18 +0000175 /* The principle used to locate the table name in the CREATE TRIGGER
176 ** statement is that the table name is the first token that is immediatedly
177 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
178 ** of TK_WHEN, TK_BEGIN or TK_FOR.
179 */
180 if( zSql ){
181 do {
danielk1977dce872b2007-05-08 12:37:45 +0000182
183 if( !*zCsr ){
184 /* Ran out of input before finding the table name. Return NULL. */
185 return;
186 }
187
drh1f01ec12005-02-15 21:36:18 +0000188 /* Store the token that zCsr points to in tname. */
drhb7916a72009-05-27 10:31:29 +0000189 tname.z = (char*)zCsr;
drh1f01ec12005-02-15 21:36:18 +0000190 tname.n = len;
191
192 /* Advance zCsr to the next token. Store that token type in 'token',
drh85b623f2007-12-13 21:54:09 +0000193 ** and its length in 'len' (to be used next iteration of this loop).
drh1f01ec12005-02-15 21:36:18 +0000194 */
195 do {
196 zCsr += len;
197 len = sqlite3GetToken(zCsr, &token);
198 }while( token==TK_SPACE );
199 assert( len>0 );
200
201 /* Variable 'dist' stores the number of tokens read since the most
202 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
203 ** token is read and 'dist' equals 2, the condition stated above
204 ** to be met.
205 **
206 ** Note that ON cannot be a database, table or column name, so
207 ** there is no need to worry about syntax like
208 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
209 */
210 dist++;
211 if( token==TK_DOT || token==TK_ON ){
212 dist = 0;
213 }
214 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
215
216 /* Variable tname now contains the token that is the old table-name
217 ** in the CREATE TRIGGER statement.
218 */
drhb7916a72009-05-27 10:31:29 +0000219 zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
drh1f01ec12005-02-15 21:36:18 +0000220 zTableName, tname.z+tname.n);
drh633e6d52008-07-28 19:34:53 +0000221 sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
drh1f01ec12005-02-15 21:36:18 +0000222 }
223}
224#endif /* !SQLITE_OMIT_TRIGGER */
225
226/*
227** Register built-in functions used to help implement ALTER TABLE
228*/
drh545f5872010-04-24 14:02:59 +0000229void sqlite3AlterFunctions(void){
230 static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
231 FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
drh1f01ec12005-02-15 21:36:18 +0000232#ifndef SQLITE_OMIT_TRIGGER
drh545f5872010-04-24 14:02:59 +0000233 FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
drh1f01ec12005-02-15 21:36:18 +0000234#endif
dan432cc5b2009-09-26 17:51:48 +0000235#ifndef SQLITE_OMIT_FOREIGN_KEY
drh545f5872010-04-24 14:02:59 +0000236 FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
dan432cc5b2009-09-26 17:51:48 +0000237#endif
drh545f5872010-04-24 14:02:59 +0000238 };
239 int i;
240 FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
241 FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
242
243 for(i=0; i<ArraySize(aAlterTableFuncs); i++){
244 sqlite3FuncDefInsert(pHash, &aFunc[i]);
245 }
dan432cc5b2009-09-26 17:51:48 +0000246}
247
248/*
249** This function is used to create the text of expressions of the form:
250**
251** name=<constant1> OR name=<constant2> OR ...
252**
253** If argument zWhere is NULL, then a pointer string containing the text
254** "name=<constant>" is returned, where <constant> is the quoted version
255** of the string passed as argument zConstant. The returned buffer is
256** allocated using sqlite3DbMalloc(). It is the responsibility of the
257** caller to ensure that it is eventually freed.
258**
259** If argument zWhere is not NULL, then the string returned is
260** "<where> OR name=<constant>", where <where> is the contents of zWhere.
261** In this case zWhere is passed to sqlite3DbFree() before returning.
262**
263*/
264static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
265 char *zNew;
266 if( !zWhere ){
267 zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
268 }else{
269 zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
270 sqlite3DbFree(db, zWhere);
271 }
272 return zNew;
273}
274
dan856ef1a2009-09-29 06:33:23 +0000275#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000276/*
277** Generate the text of a WHERE expression which can be used to select all
278** tables that have foreign key constraints that refer to table pTab (i.e.
279** constraints for which pTab is the parent table) from the sqlite_master
280** table.
281*/
282static char *whereForeignKeys(Parse *pParse, Table *pTab){
283 FKey *p;
284 char *zWhere = 0;
285 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
286 zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
287 }
288 return zWhere;
drh1f01ec12005-02-15 21:36:18 +0000289}
dan856ef1a2009-09-29 06:33:23 +0000290#endif
drh1f01ec12005-02-15 21:36:18 +0000291
drhd0e4a6c2005-02-15 20:47:57 +0000292/*
danielk197719a8e7e2005-03-17 05:03:38 +0000293** Generate the text of a WHERE expression which can be used to select all
294** temporary triggers on table pTab from the sqlite_temp_master table. If
295** table pTab has no temporary triggers, or is itself stored in the
296** temporary database, NULL is returned.
297*/
298static char *whereTempTriggers(Parse *pParse, Table *pTab){
299 Trigger *pTrig;
300 char *zWhere = 0;
danielk1977e501b892006-01-09 06:29:47 +0000301 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
danielk1977da184232006-01-05 11:34:32 +0000302
303 /* If the table is not located in the temp-db (in which case NULL is
304 ** returned, loop through the tables list of triggers. For each trigger
305 ** that is not part of the temp-db schema, add a clause to the WHERE
306 ** expression being built up in zWhere.
307 */
308 if( pTab->pSchema!=pTempSchema ){
danielk19771e536952007-08-16 10:09:01 +0000309 sqlite3 *db = pParse->db;
danielk19772f886d12009-02-28 10:47:41 +0000310 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000311 if( pTrig->pSchema==pTempSchema ){
dan432cc5b2009-09-26 17:51:48 +0000312 zWhere = whereOrName(db, zWhere, pTrig->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000313 }
314 }
315 }
dan39f1bcb2010-09-29 07:16:46 +0000316 if( zWhere ){
317 char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
318 sqlite3DbFree(pParse->db, zWhere);
319 zWhere = zNew;
320 }
danielk197719a8e7e2005-03-17 05:03:38 +0000321 return zWhere;
322}
323
324/*
325** Generate code to drop and reload the internal representation of table
326** pTab from the database, including triggers and temporary triggers.
327** Argument zName is the name of the table in the database schema at
328** the time the generated code is executed. This can be different from
329** pTab->zName if this function is being called to code part of an
330** "ALTER TABLE RENAME TO" statement.
331*/
332static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
333 Vdbe *v;
334 char *zWhere;
danielk1977da184232006-01-05 11:34:32 +0000335 int iDb; /* Index of database containing pTab */
danielk197719a8e7e2005-03-17 05:03:38 +0000336#ifndef SQLITE_OMIT_TRIGGER
337 Trigger *pTrig;
338#endif
339
340 v = sqlite3GetVdbe(pParse);
drhd3264c72009-04-15 13:39:47 +0000341 if( NEVER(v==0) ) return;
drh1fee73e2007-08-29 04:00:57 +0000342 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +0000343 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
344 assert( iDb>=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000345
346#ifndef SQLITE_OMIT_TRIGGER
347 /* Drop any table triggers from the internal schema. */
danielk19772f886d12009-02-28 10:47:41 +0000348 for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000349 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
350 assert( iTrigDb==iDb || iTrigDb==1 );
dan165921a2009-08-28 18:53:45 +0000351 sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000352 }
353#endif
354
dan432cc5b2009-09-26 17:51:48 +0000355 /* Drop the table and index from the internal schema. */
drh66a51672008-01-03 00:01:23 +0000356 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000357
358 /* Reload the table, index and permanent trigger schemas. */
danielk19771e536952007-08-16 10:09:01 +0000359 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000360 if( !zWhere ) return;
drh66a51672008-01-03 00:01:23 +0000361 sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
danielk197719a8e7e2005-03-17 05:03:38 +0000362
363#ifndef SQLITE_OMIT_TRIGGER
364 /* Now, if the table is not stored in the temp database, reload any temp
365 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
366 */
drhd9cb6ac2005-10-20 07:28:17 +0000367 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
drh66a51672008-01-03 00:01:23 +0000368 sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
danielk197719a8e7e2005-03-17 05:03:38 +0000369 }
370#endif
371}
372
373/*
drhd0e4a6c2005-02-15 20:47:57 +0000374** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
375** command.
376*/
377void sqlite3AlterRenameTable(
378 Parse *pParse, /* Parser context. */
379 SrcList *pSrc, /* The table to rename. */
380 Token *pName /* The new table name. */
381){
382 int iDb; /* Database that contains the table */
383 char *zDb; /* Name of database iDb */
384 Table *pTab; /* Table being renamed */
385 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000386 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000387 int nTabName; /* Number of UTF-8 characters in zTabName */
388 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000389 Vdbe *v;
390#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000391 char *zWhere = 0; /* Where clause to locate temp triggers */
drhd0e4a6c2005-02-15 20:47:57 +0000392#endif
danielk1977595a5232009-07-24 17:58:53 +0000393 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
drh545f5872010-04-24 14:02:59 +0000394 int savedDbFlags; /* Saved value of db->flags */
395
396 savedDbFlags = db->flags;
drh56d56f72009-04-16 16:30:17 +0000397 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000398 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000399 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000400
drhca424112008-01-25 15:04:48 +0000401 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
drhd0e4a6c2005-02-15 20:47:57 +0000402 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000403 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhd0e4a6c2005-02-15 20:47:57 +0000404 zDb = db->aDb[iDb].zName;
drh545f5872010-04-24 14:02:59 +0000405 db->flags |= SQLITE_PreferBuiltin;
drhd0e4a6c2005-02-15 20:47:57 +0000406
407 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000408 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000409 if( !zName ) goto exit_rename_table;
410
411 /* Check that a table or index named 'zName' does not already exist
412 ** in database iDb. If so, this is an error.
413 */
414 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
415 sqlite3ErrorMsg(pParse,
416 "there is already another table or index with this name: %s", zName);
417 goto exit_rename_table;
418 }
419
420 /* Make sure it is not a system table being altered, or a reserved name
421 ** that the table is being renamed to.
422 */
drhea678832008-12-10 19:26:22 +0000423 if( sqlite3Strlen30(pTab->zName)>6
424 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
425 ){
drhd0e4a6c2005-02-15 20:47:57 +0000426 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
427 goto exit_rename_table;
428 }
429 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
430 goto exit_rename_table;
431 }
432
danielk197761116ae2007-12-13 08:15:30 +0000433#ifndef SQLITE_OMIT_VIEW
434 if( pTab->pSelect ){
435 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
436 goto exit_rename_table;
437 }
438#endif
439
drhd0e4a6c2005-02-15 20:47:57 +0000440#ifndef SQLITE_OMIT_AUTHORIZATION
441 /* Invoke the authorization callback. */
442 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
443 goto exit_rename_table;
444 }
445#endif
446
danielk1977182c4ba2007-06-27 15:53:34 +0000447#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000448 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
449 goto exit_rename_table;
450 }
danielk1977595a5232009-07-24 17:58:53 +0000451 if( IsVirtual(pTab) ){
452 pVTab = sqlite3GetVTable(db, pTab);
453 if( pVTab->pVtab->pModule->xRename==0 ){
454 pVTab = 0;
455 }
danielk1977182c4ba2007-06-27 15:53:34 +0000456 }
457#endif
458
drhd0e4a6c2005-02-15 20:47:57 +0000459 /* Begin a transaction and code the VerifyCookie for database iDb.
460 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000461 ** schema). Open a statement transaction if the table is a virtual
462 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000463 */
464 v = sqlite3GetVdbe(pParse);
465 if( v==0 ){
466 goto exit_rename_table;
467 }
danielk1977595a5232009-07-24 17:58:53 +0000468 sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
drh9cbf3422008-01-17 16:22:13 +0000469 sqlite3ChangeCookie(pParse, iDb);
drhd0e4a6c2005-02-15 20:47:57 +0000470
danielk1977182c4ba2007-06-27 15:53:34 +0000471 /* If this is a virtual table, invoke the xRename() function if
472 ** one is defined. The xRename() callback will modify the names
473 ** of any resources used by the v-table implementation (including other
474 ** SQLite tables) that are identified by the name of the virtual table.
475 */
476#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk1977595a5232009-07-24 17:58:53 +0000477 if( pVTab ){
danielk1977a29f18c2008-01-04 11:01:03 +0000478 int i = ++pParse->nMem;
drh4c583122008-01-04 22:01:03 +0000479 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
danielk1977595a5232009-07-24 17:58:53 +0000480 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
dane0af83a2009-09-08 19:15:01 +0000481 sqlite3MayAbort(pParse);
danielk1977182c4ba2007-06-27 15:53:34 +0000482 }
483#endif
484
drh4e5dd852007-05-15 03:56:49 +0000485 /* figure out how many UTF-8 characters are in zName */
486 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000487 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000488
dan856ef1a2009-09-29 06:33:23 +0000489#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000490 if( db->flags&SQLITE_ForeignKeys ){
491 /* If foreign-key support is enabled, rewrite the CREATE TABLE
492 ** statements corresponding to all child tables of foreign key constraints
493 ** for which the renamed table is the parent table. */
494 if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
495 sqlite3NestedParse(pParse,
drh9a6ffc82010-02-15 18:03:20 +0000496 "UPDATE \"%w\".%s SET "
dan432cc5b2009-09-26 17:51:48 +0000497 "sql = sqlite_rename_parent(sql, %Q, %Q) "
drh9a6ffc82010-02-15 18:03:20 +0000498 "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
dan432cc5b2009-09-26 17:51:48 +0000499 sqlite3DbFree(db, zWhere);
500 }
501 }
502#endif
503
drhd0e4a6c2005-02-15 20:47:57 +0000504 /* Modify the sqlite_master table to use the new table name. */
505 sqlite3NestedParse(pParse,
506 "UPDATE %Q.%s SET "
507#ifdef SQLITE_OMIT_TRIGGER
508 "sql = sqlite_rename_table(sql, %Q), "
509#else
510 "sql = CASE "
511 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
512 "ELSE sqlite_rename_table(sql, %Q) END, "
513#endif
514 "tbl_name = %Q, "
515 "name = CASE "
516 "WHEN type='table' THEN %Q "
517 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000518 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000519 "ELSE name END "
520 "WHERE tbl_name=%Q AND "
521 "(type='table' OR type='index' OR type='trigger');",
522 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
523#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000524 zName,
drhd0e4a6c2005-02-15 20:47:57 +0000525#endif
drh4e5dd852007-05-15 03:56:49 +0000526 zName, nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000527 );
528
529#ifndef SQLITE_OMIT_AUTOINCREMENT
530 /* If the sqlite_sequence table exists in this database, then update
531 ** it with the new table name.
532 */
533 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
534 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000535 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
drhd0e4a6c2005-02-15 20:47:57 +0000536 zDb, zName, pTab->zName);
537 }
538#endif
539
540#ifndef SQLITE_OMIT_TRIGGER
541 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
542 ** table. Don't do this if the table being ALTERed is itself located in
543 ** the temp database.
544 */
drhd9cb6ac2005-10-20 07:28:17 +0000545 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000546 sqlite3NestedParse(pParse,
547 "UPDATE sqlite_temp_master SET "
548 "sql = sqlite_rename_trigger(sql, %Q), "
549 "tbl_name = %Q "
550 "WHERE %s;", zName, zName, zWhere);
drh633e6d52008-07-28 19:34:53 +0000551 sqlite3DbFree(db, zWhere);
drhd0e4a6c2005-02-15 20:47:57 +0000552 }
553#endif
554
dan856ef1a2009-09-29 06:33:23 +0000555#if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
dan432cc5b2009-09-26 17:51:48 +0000556 if( db->flags&SQLITE_ForeignKeys ){
557 FKey *p;
558 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
559 Table *pFrom = p->pFrom;
560 if( pFrom!=pTab ){
561 reloadTableSchema(pParse, p->pFrom, pFrom->zName);
562 }
563 }
564 }
565#endif
566
danielk197719a8e7e2005-03-17 05:03:38 +0000567 /* Drop and reload the internal table schema. */
568 reloadTableSchema(pParse, pTab, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000569
570exit_rename_table:
drh633e6d52008-07-28 19:34:53 +0000571 sqlite3SrcListDelete(db, pSrc);
572 sqlite3DbFree(db, zName);
drh545f5872010-04-24 14:02:59 +0000573 db->flags = savedDbFlags;
drhd0e4a6c2005-02-15 20:47:57 +0000574}
danielk197719a8e7e2005-03-17 05:03:38 +0000575
576
577/*
drhd3001712009-05-12 17:46:53 +0000578** Generate code to make sure the file format number is at least minFormat.
579** The generated code will increase the file format number if necessary.
580*/
581void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
582 Vdbe *v;
583 v = sqlite3GetVdbe(pParse);
584 /* The VDBE should have been allocated before this routine is called.
585 ** If that allocation failed, we would have quit before reaching this
586 ** point */
587 if( ALWAYS(v) ){
588 int r1 = sqlite3GetTempReg(pParse);
589 int r2 = sqlite3GetTempReg(pParse);
590 int j1;
danielk19770d19f7a2009-06-03 11:25:07 +0000591 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
drhd3001712009-05-12 17:46:53 +0000592 sqlite3VdbeUsesBtree(v, iDb);
593 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
594 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
danielk19770d19f7a2009-06-03 11:25:07 +0000595 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
drhd3001712009-05-12 17:46:53 +0000596 sqlite3VdbeJumpHere(v, j1);
597 sqlite3ReleaseTempReg(pParse, r1);
598 sqlite3ReleaseTempReg(pParse, r2);
599 }
600}
601
602/*
danielk197719a8e7e2005-03-17 05:03:38 +0000603** This function is called after an "ALTER TABLE ... ADD" statement
604** has been parsed. Argument pColDef contains the text of the new
605** column definition.
606**
607** The Table structure pParse->pNewTable was extended to include
608** the new column during parsing.
609*/
610void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
611 Table *pNew; /* Copy of pParse->pNewTable */
612 Table *pTab; /* Table being altered */
613 int iDb; /* Database number */
614 const char *zDb; /* Database name */
615 const char *zTab; /* Table name */
616 char *zCol; /* Null-terminated column definition */
617 Column *pCol; /* The new column */
618 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000619 sqlite3 *db; /* The database connection; */
danielk197719a8e7e2005-03-17 05:03:38 +0000620
danielk1977f150c9d2008-10-30 17:21:12 +0000621 db = pParse->db;
622 if( pParse->nErr || db->mallocFailed ) return;
danielk197719a8e7e2005-03-17 05:03:38 +0000623 pNew = pParse->pNewTable;
624 assert( pNew );
625
drh1fee73e2007-08-29 04:00:57 +0000626 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000627 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
628 zDb = db->aDb[iDb].zName;
drh03881232009-02-13 03:43:31 +0000629 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
danielk197719a8e7e2005-03-17 05:03:38 +0000630 pCol = &pNew->aCol[pNew->nCol-1];
631 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000632 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000633 assert( pTab );
634
drh81f2ccd2006-01-31 14:28:44 +0000635#ifndef SQLITE_OMIT_AUTHORIZATION
636 /* Invoke the authorization callback. */
637 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
638 return;
639 }
640#endif
641
danielk197719a8e7e2005-03-17 05:03:38 +0000642 /* If the default value for the new column was specified with a
643 ** literal NULL, then set pDflt to 0. This simplifies checking
644 ** for an SQL NULL default below.
645 */
646 if( pDflt && pDflt->op==TK_NULL ){
647 pDflt = 0;
648 }
649
650 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
651 ** If there is a NOT NULL constraint, then the default value for the
652 ** column must not be NULL.
653 */
654 if( pCol->isPrimKey ){
655 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
656 return;
657 }
658 if( pNew->pIndex ){
659 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
660 return;
661 }
dan53c3fa82009-09-25 11:26:54 +0000662 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
663 sqlite3ErrorMsg(pParse,
664 "Cannot add a REFERENCES column with non-NULL default value");
665 return;
666 }
danielk197719a8e7e2005-03-17 05:03:38 +0000667 if( pCol->notNull && !pDflt ){
668 sqlite3ErrorMsg(pParse,
669 "Cannot add a NOT NULL column with default value NULL");
670 return;
671 }
672
673 /* Ensure the default expression is something that sqlite3ValueFromExpr()
674 ** can handle (i.e. not CURRENT_TIME etc.)
675 */
676 if( pDflt ){
677 sqlite3_value *pVal;
danielk19771e536952007-08-16 10:09:01 +0000678 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
drh17435752007-08-16 04:30:38 +0000679 db->mallocFailed = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000680 return;
681 }
682 if( !pVal ){
683 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
684 return;
685 }
686 sqlite3ValueFree(pVal);
687 }
688
689 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000690 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000691 if( zCol ){
692 char *zEnd = &zCol[pColDef->n-1];
drh545f5872010-04-24 14:02:59 +0000693 int savedDbFlags = db->flags;
drh56d56f72009-04-16 16:30:17 +0000694 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000695 *zEnd-- = '\0';
696 }
drh545f5872010-04-24 14:02:59 +0000697 db->flags |= SQLITE_PreferBuiltin;
danielk197719a8e7e2005-03-17 05:03:38 +0000698 sqlite3NestedParse(pParse,
drh8e5b5f82008-02-09 14:30:29 +0000699 "UPDATE \"%w\".%s SET "
drha21a9292007-10-20 20:58:57 +0000700 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000701 "WHERE type = 'table' AND name = %Q",
702 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
703 zTab
704 );
drh633e6d52008-07-28 19:34:53 +0000705 sqlite3DbFree(db, zCol);
drh545f5872010-04-24 14:02:59 +0000706 db->flags = savedDbFlags;
danielk197719a8e7e2005-03-17 05:03:38 +0000707 }
708
709 /* If the default value of the new column is NULL, then set the file
710 ** format to 2. If the default value of the new column is not NULL,
711 ** the file format becomes 3.
712 */
drhfdd6e852005-12-16 01:06:16 +0000713 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
danielk197719a8e7e2005-03-17 05:03:38 +0000714
715 /* Reload the schema of the modified table. */
716 reloadTableSchema(pParse, pTab, pTab->zName);
717}
718
drhfdd6e852005-12-16 01:06:16 +0000719/*
danielk197719a8e7e2005-03-17 05:03:38 +0000720** This function is called by the parser after the table-name in
721** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
722** pSrc is the full-name of the table being altered.
723**
724** This routine makes a (partial) copy of the Table structure
725** for the table being altered and sets Parse.pNewTable to point
726** to it. Routines called by the parser as the column definition
727** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
728** the copy. The copy of the Table structure is deleted by tokenize.c
729** after parsing is finished.
730**
731** Routine sqlite3AlterFinishAddColumn() will be called to complete
732** coding the "ALTER TABLE ... ADD" statement.
733*/
734void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
735 Table *pNew;
736 Table *pTab;
737 Vdbe *v;
738 int iDb;
739 int i;
740 int nAlloc;
drh17435752007-08-16 04:30:38 +0000741 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000742
743 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000744 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000745 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000746 if( db->mallocFailed ) goto exit_begin_add_column;
drhca424112008-01-25 15:04:48 +0000747 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
danielk197719a8e7e2005-03-17 05:03:38 +0000748 if( !pTab ) goto exit_begin_add_column;
749
danielk19775ee9d692006-06-21 12:36:25 +0000750#ifndef SQLITE_OMIT_VIRTUALTABLE
751 if( IsVirtual(pTab) ){
752 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
753 goto exit_begin_add_column;
754 }
755#endif
756
danielk197719a8e7e2005-03-17 05:03:38 +0000757 /* Make sure this is not an attempt to ALTER a view. */
758 if( pTab->pSelect ){
759 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
760 goto exit_begin_add_column;
761 }
762
763 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000764 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000765
766 /* Put a copy of the Table struct in Parse.pNewTable for the
drh03881232009-02-13 03:43:31 +0000767 ** sqlite3AddColumn() function and friends to modify. But modify
768 ** the name by adding an "sqlite_altertab_" prefix. By adding this
769 ** prefix, we insure that the name will not collide with an existing
770 ** table because user table are not allowed to have the "sqlite_"
771 ** prefix on their name.
danielk197719a8e7e2005-03-17 05:03:38 +0000772 */
drh17435752007-08-16 04:30:38 +0000773 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000774 if( !pNew ) goto exit_begin_add_column;
775 pParse->pNewTable = pNew;
drh0bbaa1b2005-08-19 19:14:12 +0000776 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000777 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000778 assert( pNew->nCol>0 );
779 nAlloc = (((pNew->nCol-1)/8)*8)+8;
780 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000781 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh03881232009-02-13 03:43:31 +0000782 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000783 if( !pNew->aCol || !pNew->zName ){
drh17435752007-08-16 04:30:38 +0000784 db->mallocFailed = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000785 goto exit_begin_add_column;
786 }
787 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
788 for(i=0; i<pNew->nCol; i++){
789 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000790 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000791 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000792 pCol->zType = 0;
793 pCol->pDflt = 0;
drhb7916a72009-05-27 10:31:29 +0000794 pCol->zDflt = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000795 }
drh17435752007-08-16 04:30:38 +0000796 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000797 pNew->addColOffset = pTab->addColOffset;
drhed8a3bb2005-06-06 21:19:56 +0000798 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000799
800 /* Begin a transaction and increment the schema cookie. */
801 sqlite3BeginWriteOperation(pParse, 0, iDb);
802 v = sqlite3GetVdbe(pParse);
803 if( !v ) goto exit_begin_add_column;
drh9cbf3422008-01-17 16:22:13 +0000804 sqlite3ChangeCookie(pParse, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000805
806exit_begin_add_column:
drh633e6d52008-07-28 19:34:53 +0000807 sqlite3SrcListDelete(db, pSrc);
danielk197719a8e7e2005-03-17 05:03:38 +0000808 return;
809}
drhd0e4a6c2005-02-15 20:47:57 +0000810#endif /* SQLITE_ALTER_TABLE */