blob: eba01e2960d0ee0e5ea9641edb63a4ff3b749a28 [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.
14**
drh0bbaa1b2005-08-19 19:14:12 +000015** $Id: alter.c,v 1.8 2005/08/19 19:14:13 drh Exp $
drhd0e4a6c2005-02-15 20:47:57 +000016*/
17#include "sqliteInt.h"
danielk197719a8e7e2005-03-17 05:03:38 +000018#include <ctype.h>
drhd0e4a6c2005-02-15 20:47:57 +000019
drh1f01ec12005-02-15 21:36:18 +000020/*
21** The code in this file only exists if we are not omitting the
22** ALTER TABLE logic from the build.
23*/
drhd0e4a6c2005-02-15 20:47:57 +000024#ifndef SQLITE_OMIT_ALTERTABLE
drh1f01ec12005-02-15 21:36:18 +000025
26
27/*
28** This function is used by SQL generated to implement the
29** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
30** CREATE INDEX command. The second is a table name. The table name in
31** the CREATE TABLE or CREATE INDEX statement is replaced with the second
32** argument and the result returned. Examples:
33**
34** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
35** -> 'CREATE TABLE def(a, b, c)'
36**
37** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
38** -> 'CREATE INDEX i ON def(a, b, c)'
39*/
40static void renameTableFunc(
41 sqlite3_context *context,
42 int argc,
43 sqlite3_value **argv
44){
45 unsigned char const *zSql = sqlite3_value_text(argv[0]);
46 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
47
48 int token;
49 Token tname;
50 char const *zCsr = zSql;
51 int len = 0;
52 char *zRet;
53
54 /* The principle used to locate the table name in the CREATE TABLE
55 ** statement is that the table name is the first token that is immediatedly
56 ** followed by a left parenthesis - TK_LP.
57 */
58 if( zSql ){
59 do {
60 /* Store the token that zCsr points to in tname. */
61 tname.z = zCsr;
62 tname.n = len;
63
64 /* Advance zCsr to the next token. Store that token type in 'token',
65 ** and it's length in 'len' (to be used next iteration of this loop).
66 */
67 do {
68 zCsr += len;
69 len = sqlite3GetToken(zCsr, &token);
70 } while( token==TK_SPACE );
71 assert( len>0 );
72 } while( token!=TK_LP );
73
74 zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
75 zTableName, tname.z+tname.n);
76 sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
77 }
78}
79
80#ifndef SQLITE_OMIT_TRIGGER
81/* This function is used by SQL generated to implement the ALTER TABLE
82** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
83** statement. The second is a table name. The table name in the CREATE
84** TRIGGER statement is replaced with the second argument and the result
85** returned. This is analagous to renameTableFunc() above, except for CREATE
86** TRIGGER, not CREATE INDEX and CREATE TABLE.
87*/
88static void renameTriggerFunc(
89 sqlite3_context *context,
90 int argc,
91 sqlite3_value **argv
92){
93 unsigned char const *zSql = sqlite3_value_text(argv[0]);
94 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
95
96 int token;
97 Token tname;
98 int dist = 3;
99 char const *zCsr = zSql;
100 int len = 0;
101 char *zRet;
102
103 /* The principle used to locate the table name in the CREATE TRIGGER
104 ** statement is that the table name is the first token that is immediatedly
105 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
106 ** of TK_WHEN, TK_BEGIN or TK_FOR.
107 */
108 if( zSql ){
109 do {
110 /* Store the token that zCsr points to in tname. */
111 tname.z = zCsr;
112 tname.n = len;
113
114 /* Advance zCsr to the next token. Store that token type in 'token',
115 ** and it's length in 'len' (to be used next iteration of this loop).
116 */
117 do {
118 zCsr += len;
119 len = sqlite3GetToken(zCsr, &token);
120 }while( token==TK_SPACE );
121 assert( len>0 );
122
123 /* Variable 'dist' stores the number of tokens read since the most
124 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
125 ** token is read and 'dist' equals 2, the condition stated above
126 ** to be met.
127 **
128 ** Note that ON cannot be a database, table or column name, so
129 ** there is no need to worry about syntax like
130 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
131 */
132 dist++;
133 if( token==TK_DOT || token==TK_ON ){
134 dist = 0;
135 }
136 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
137
138 /* Variable tname now contains the token that is the old table-name
139 ** in the CREATE TRIGGER statement.
140 */
141 zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql,
142 zTableName, tname.z+tname.n);
143 sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
144 }
145}
146#endif /* !SQLITE_OMIT_TRIGGER */
147
148/*
149** Register built-in functions used to help implement ALTER TABLE
150*/
151void sqlite3AlterFunctions(sqlite3 *db){
152 static const struct {
153 char *zName;
154 signed char nArg;
155 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
156 } aFuncs[] = {
157 { "sqlite_rename_table", 2, renameTableFunc},
158#ifndef SQLITE_OMIT_TRIGGER
159 { "sqlite_rename_trigger", 2, renameTriggerFunc},
160#endif
161 };
162 int i;
163
164 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
165 sqlite3_create_function(db, aFuncs[i].zName, aFuncs[i].nArg,
166 SQLITE_UTF8, 0, aFuncs[i].xFunc, 0, 0);
167 }
168}
169
drhd0e4a6c2005-02-15 20:47:57 +0000170/*
danielk197719a8e7e2005-03-17 05:03:38 +0000171** Generate the text of a WHERE expression which can be used to select all
172** temporary triggers on table pTab from the sqlite_temp_master table. If
173** table pTab has no temporary triggers, or is itself stored in the
174** temporary database, NULL is returned.
175*/
176static char *whereTempTriggers(Parse *pParse, Table *pTab){
177 Trigger *pTrig;
178 char *zWhere = 0;
179 char *tmp = 0;
180 if( pTab->iDb!=1 ){
181 for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
182 if( pTrig->iDb==1 ){
183 if( !zWhere ){
184 zWhere = sqlite3MPrintf("name=%Q", pTrig->name);
185 }else{
186 tmp = zWhere;
187 zWhere = sqlite3MPrintf("%s OR name=%Q", zWhere, pTrig->name);
188 sqliteFree(tmp);
189 }
190 }
191 }
192 }
193 return zWhere;
194}
195
196/*
197** Generate code to drop and reload the internal representation of table
198** pTab from the database, including triggers and temporary triggers.
199** Argument zName is the name of the table in the database schema at
200** the time the generated code is executed. This can be different from
201** pTab->zName if this function is being called to code part of an
202** "ALTER TABLE RENAME TO" statement.
203*/
204static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
205 Vdbe *v;
206 char *zWhere;
207 int iDb;
208#ifndef SQLITE_OMIT_TRIGGER
209 Trigger *pTrig;
210#endif
211
212 v = sqlite3GetVdbe(pParse);
213 if( !v ) return;
214 iDb = pTab->iDb;
215
216#ifndef SQLITE_OMIT_TRIGGER
217 /* Drop any table triggers from the internal schema. */
218 for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
219 assert( pTrig->iDb==iDb || pTrig->iDb==1 );
220 sqlite3VdbeOp3(v, OP_DropTrigger, pTrig->iDb, 0, pTrig->name, 0);
221 }
222#endif
223
224 /* Drop the table and index from the internal schema */
225 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
226
227 /* Reload the table, index and permanent trigger schemas. */
228 zWhere = sqlite3MPrintf("tbl_name=%Q", zName);
229 if( !zWhere ) return;
230 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
231
232#ifndef SQLITE_OMIT_TRIGGER
233 /* Now, if the table is not stored in the temp database, reload any temp
234 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
235 */
236 if( (zWhere=whereTempTriggers(pParse, pTab)) ){
237 sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
238 }
239#endif
240}
241
242/*
drhd0e4a6c2005-02-15 20:47:57 +0000243** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
244** command.
245*/
246void sqlite3AlterRenameTable(
247 Parse *pParse, /* Parser context. */
248 SrcList *pSrc, /* The table to rename. */
249 Token *pName /* The new table name. */
250){
251 int iDb; /* Database that contains the table */
252 char *zDb; /* Name of database iDb */
253 Table *pTab; /* Table being renamed */
254 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000255 sqlite3 *db = pParse->db; /* Database connection */
256 Vdbe *v;
257#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000258 char *zWhere = 0; /* Where clause to locate temp triggers */
drhd0e4a6c2005-02-15 20:47:57 +0000259#endif
260
drh0bbaa1b2005-08-19 19:14:12 +0000261 if( sqlite3_malloc_failed ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000262 assert( pSrc->nSrc==1 );
263
264 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
265 if( !pTab ) goto exit_rename_table;
266 iDb = pTab->iDb;
267 zDb = db->aDb[iDb].zName;
268
269 /* Get a NULL terminated version of the new table name. */
270 zName = sqlite3NameFromToken(pName);
271 if( !zName ) goto exit_rename_table;
272
273 /* Check that a table or index named 'zName' does not already exist
274 ** in database iDb. If so, this is an error.
275 */
276 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
277 sqlite3ErrorMsg(pParse,
278 "there is already another table or index with this name: %s", zName);
279 goto exit_rename_table;
280 }
281
282 /* Make sure it is not a system table being altered, or a reserved name
283 ** that the table is being renamed to.
284 */
285 if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
286 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
287 goto exit_rename_table;
288 }
289 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
290 goto exit_rename_table;
291 }
292
293#ifndef SQLITE_OMIT_AUTHORIZATION
294 /* Invoke the authorization callback. */
295 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
296 goto exit_rename_table;
297 }
298#endif
299
300 /* Begin a transaction and code the VerifyCookie for database iDb.
301 ** Then modify the schema cookie (since the ALTER TABLE modifies the
302 ** schema).
303 */
304 v = sqlite3GetVdbe(pParse);
305 if( v==0 ){
306 goto exit_rename_table;
307 }
308 sqlite3BeginWriteOperation(pParse, 0, iDb);
309 sqlite3ChangeCookie(db, v, iDb);
310
311 /* Modify the sqlite_master table to use the new table name. */
312 sqlite3NestedParse(pParse,
313 "UPDATE %Q.%s SET "
314#ifdef SQLITE_OMIT_TRIGGER
315 "sql = sqlite_rename_table(sql, %Q), "
316#else
317 "sql = CASE "
318 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
319 "ELSE sqlite_rename_table(sql, %Q) END, "
320#endif
321 "tbl_name = %Q, "
322 "name = CASE "
323 "WHEN type='table' THEN %Q "
324 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
325 "'sqlite_autoindex_' || %Q || substr(name, %d+18,10) "
326 "ELSE name END "
327 "WHERE tbl_name=%Q AND "
328 "(type='table' OR type='index' OR type='trigger');",
329 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
330#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000331 zName,
drhd0e4a6c2005-02-15 20:47:57 +0000332#endif
333 zName, strlen(pTab->zName), pTab->zName
334 );
335
336#ifndef SQLITE_OMIT_AUTOINCREMENT
337 /* If the sqlite_sequence table exists in this database, then update
338 ** it with the new table name.
339 */
340 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
341 sqlite3NestedParse(pParse,
342 "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
343 zDb, zName, pTab->zName);
344 }
345#endif
346
347#ifndef SQLITE_OMIT_TRIGGER
348 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
349 ** table. Don't do this if the table being ALTERed is itself located in
350 ** the temp database.
351 */
danielk197719a8e7e2005-03-17 05:03:38 +0000352 if( (zWhere=whereTempTriggers(pParse, pTab)) ){
353 sqlite3NestedParse(pParse,
354 "UPDATE sqlite_temp_master SET "
355 "sql = sqlite_rename_trigger(sql, %Q), "
356 "tbl_name = %Q "
357 "WHERE %s;", zName, zName, zWhere);
358 sqliteFree(zWhere);
drhd0e4a6c2005-02-15 20:47:57 +0000359 }
360#endif
361
danielk197719a8e7e2005-03-17 05:03:38 +0000362 /* Drop and reload the internal table schema. */
363 reloadTableSchema(pParse, pTab, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000364
365exit_rename_table:
366 sqlite3SrcListDelete(pSrc);
367 sqliteFree(zName);
368}
danielk197719a8e7e2005-03-17 05:03:38 +0000369
370
371/*
372** This function is called after an "ALTER TABLE ... ADD" statement
373** has been parsed. Argument pColDef contains the text of the new
374** column definition.
375**
376** The Table structure pParse->pNewTable was extended to include
377** the new column during parsing.
378*/
379void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
380 Table *pNew; /* Copy of pParse->pNewTable */
381 Table *pTab; /* Table being altered */
382 int iDb; /* Database number */
383 const char *zDb; /* Database name */
384 const char *zTab; /* Table name */
385 char *zCol; /* Null-terminated column definition */
386 Column *pCol; /* The new column */
387 Expr *pDflt; /* Default value for the new column */
388 Vdbe *v;
389
390 if( pParse->nErr ) return;
391 pNew = pParse->pNewTable;
392 assert( pNew );
393
394 iDb = pNew->iDb;
395 zDb = pParse->db->aDb[iDb].zName;
396 zTab = pNew->zName;
397 pCol = &pNew->aCol[pNew->nCol-1];
398 pDflt = pCol->pDflt;
399 pTab = sqlite3FindTable(pParse->db, zTab, zDb);
400 assert( pTab );
401
402 /* If the default value for the new column was specified with a
403 ** literal NULL, then set pDflt to 0. This simplifies checking
404 ** for an SQL NULL default below.
405 */
406 if( pDflt && pDflt->op==TK_NULL ){
407 pDflt = 0;
408 }
409
410 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
411 ** If there is a NOT NULL constraint, then the default value for the
412 ** column must not be NULL.
413 */
414 if( pCol->isPrimKey ){
415 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
416 return;
417 }
418 if( pNew->pIndex ){
419 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
420 return;
421 }
422 if( pCol->notNull && !pDflt ){
423 sqlite3ErrorMsg(pParse,
424 "Cannot add a NOT NULL column with default value NULL");
425 return;
426 }
427
428 /* Ensure the default expression is something that sqlite3ValueFromExpr()
429 ** can handle (i.e. not CURRENT_TIME etc.)
430 */
431 if( pDflt ){
432 sqlite3_value *pVal;
433 if( sqlite3ValueFromExpr(pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
434 /* malloc() has failed */
435 return;
436 }
437 if( !pVal ){
438 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
439 return;
440 }
441 sqlite3ValueFree(pVal);
442 }
443
444 /* Modify the CREATE TABLE statement. */
445 zCol = sqliteStrNDup(pColDef->z, pColDef->n);
446 if( zCol ){
447 char *zEnd = &zCol[pColDef->n-1];
drh47b4b292005-03-19 14:45:48 +0000448 while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000449 *zEnd-- = '\0';
450 }
451 sqlite3NestedParse(pParse,
452 "UPDATE %Q.%s SET "
danielk1977f0b57922005-03-28 00:07:16 +0000453 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d,length(sql)) "
danielk197719a8e7e2005-03-17 05:03:38 +0000454 "WHERE type = 'table' AND name = %Q",
455 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
456 zTab
457 );
458 sqliteFree(zCol);
459 }
460
461 /* If the default value of the new column is NULL, then set the file
462 ** format to 2. If the default value of the new column is not NULL,
463 ** the file format becomes 3.
464 */
465 if( (v=sqlite3GetVdbe(pParse)) ){
466 int f = (pDflt?3:2);
467
468 /* Only set the file format to $f if it is currently less than $f. */
469 sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
470 sqlite3VdbeAddOp(v, OP_Integer, f, 0);
471 sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
472 sqlite3VdbeAddOp(v, OP_Integer, f, 0);
473 sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1);
474 }
475
476 /* Reload the schema of the modified table. */
477 reloadTableSchema(pParse, pTab, pTab->zName);
478}
479
480
481/*
482** This function is called by the parser after the table-name in
483** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
484** pSrc is the full-name of the table being altered.
485**
486** This routine makes a (partial) copy of the Table structure
487** for the table being altered and sets Parse.pNewTable to point
488** to it. Routines called by the parser as the column definition
489** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
490** the copy. The copy of the Table structure is deleted by tokenize.c
491** after parsing is finished.
492**
493** Routine sqlite3AlterFinishAddColumn() will be called to complete
494** coding the "ALTER TABLE ... ADD" statement.
495*/
496void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
497 Table *pNew;
498 Table *pTab;
499 Vdbe *v;
500 int iDb;
501 int i;
502 int nAlloc;
503
drh0bbaa1b2005-08-19 19:14:12 +0000504
danielk197719a8e7e2005-03-17 05:03:38 +0000505 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000506 assert( pParse->pNewTable==0 );
507 if( sqlite3_malloc_failed ) goto exit_begin_add_column;
danielk197719a8e7e2005-03-17 05:03:38 +0000508 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
509 if( !pTab ) goto exit_begin_add_column;
510
511 /* Make sure this is not an attempt to ALTER a view. */
512 if( pTab->pSelect ){
513 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
514 goto exit_begin_add_column;
515 }
516
517 assert( pTab->addColOffset>0 );
518 iDb = pTab->iDb;
519
520 /* Put a copy of the Table struct in Parse.pNewTable for the
521 ** sqlite3AddColumn() function and friends to modify.
522 */
523 pNew = (Table *)sqliteMalloc(sizeof(Table));
524 if( !pNew ) goto exit_begin_add_column;
525 pParse->pNewTable = pNew;
drh0bbaa1b2005-08-19 19:14:12 +0000526 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000527 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000528 assert( pNew->nCol>0 );
529 nAlloc = (((pNew->nCol-1)/8)*8)+8;
530 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197719a8e7e2005-03-17 05:03:38 +0000531 pNew->aCol = (Column *)sqliteMalloc(sizeof(Column)*nAlloc);
532 pNew->zName = sqliteStrDup(pTab->zName);
533 if( !pNew->aCol || !pNew->zName ){
534 goto exit_begin_add_column;
535 }
536 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
537 for(i=0; i<pNew->nCol; i++){
538 Column *pCol = &pNew->aCol[i];
539 pCol->zName = sqliteStrDup(pCol->zName);
540 pCol->zType = 0;
541 pCol->pDflt = 0;
542 }
543 pNew->iDb = iDb;
544 pNew->addColOffset = pTab->addColOffset;
drhed8a3bb2005-06-06 21:19:56 +0000545 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000546
547 /* Begin a transaction and increment the schema cookie. */
548 sqlite3BeginWriteOperation(pParse, 0, iDb);
549 v = sqlite3GetVdbe(pParse);
550 if( !v ) goto exit_begin_add_column;
551 sqlite3ChangeCookie(pParse->db, v, iDb);
552
553exit_begin_add_column:
554 sqlite3SrcListDelete(pSrc);
555 return;
556}
drhd0e4a6c2005-02-15 20:47:57 +0000557#endif /* SQLITE_ALTER_TABLE */