4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
12 ** This file contains C code routines that used to generate VDBE code
13 ** that implements the ALTER TABLE command.
17 #include "sqliteInt.h"
21 ** The code in this file only exists if we are not omitting the
22 ** ALTER TABLE logic from the build.
24 #ifndef SQLITE_OMIT_ALTERTABLE
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:
34 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
35 ** -> 'CREATE TABLE def(a, b, c)'
37 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
38 ** -> 'CREATE INDEX i ON def(a, b, c)'
40 static void renameTableFunc(
41 sqlite3_context
*context
,
45 unsigned char const *zSql
= sqlite3_value_text(argv
[0]);
46 unsigned char const *zTableName
= sqlite3_value_text(argv
[1]);
50 char const *zCsr
= zSql
;
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.
61 /* Store the token that zCsr points to in tname. */
65 /* Advance zCsr to the next token. Store that token type in
66 * 'token', and it's length in 'len' (to be used next iteration of
71 len
= sqlite3GetToken(zCsr
, &token
);
72 } while( token
==TK_SPACE
);
75 } while( token
!=TK_LP
);
77 zRet
= sqlite3MPrintf("%.*s%Q%s", tname
.z
- zSql
, zSql
,
78 zTableName
, tname
.z
+tname
.n
);
79 sqlite3_result_text(context
, zRet
, -1, sqlite3FreeX
);
83 #ifndef SQLITE_OMIT_TRIGGER
85 * This function is used by SQL generated to implement the ALTER TABLE command.
86 * The first argument is the text of a CREATE TRIGGER statement. The second is
87 * a table name. The table name in the CREATE TRIGGER statement is replaced
88 * with the second argument and the result returned. This is analagous to
89 * renameTableFunc() above, except for CREATE TRIGGER, not CREATE INDEX and
92 static void renameTriggerFunc(
93 sqlite3_context
*context
,
97 unsigned char const *zSql
= sqlite3_value_text(argv
[0]);
98 unsigned char const *zTableName
= sqlite3_value_text(argv
[1]);
103 char const *zCsr
= zSql
;
107 /* The principle used to locate the table name in the CREATE TRIGGER
108 * statement is that the table name is the first token that is immediatedly
109 * preceded by either TK_ON or TK_DOT and immediatedly followed by one of
110 * TK_WHEN, TK_BEGIN or TK_FOR.
115 /* Store the token that zCsr points to in tname. */
119 /* Advance zCsr to the next token. Store that token type in
120 * 'token', and it's length in 'len' (to be used next iteration of
125 len
= sqlite3GetToken(zCsr
, &token
);
126 }while( token
==TK_SPACE
);
130 /* Variable 'dist' stores the number of tokens read since the most
131 * recent TK_DOT or TK_ON. This means that when a WHEN, FOR or
132 * BEGIN token is read and 'dist' equals 2, the condition stated
135 * Note that ON cannot be a database, table or column name, so
136 * there is no need to worry about syntax like CREATE TRIGGER ...
137 * ON ON.ON BEGIN ..." etc.
140 if( token
==TK_DOT
|| token
==TK_ON
)
144 } while( dist
!=2 || (
147 token
!= TK_BEGIN
) );
149 /* Variable tname now contains the token that is the old table-name in
150 * the CREATE TRIGGER statement.
152 zRet
= sqlite3MPrintf("%.*s%Q%s", tname
.z
- zSql
, zSql
,
153 zTableName
, tname
.z
+tname
.n
);
154 sqlite3_result_text(context
, zRet
, -1, sqlite3FreeX
);
157 #endif /* !SQLITE_OMIT_TRIGGER */
161 * Register built-in functions used to help implement ALTER TABLE
164 void sqlite3AlterFunctions(sqlite3
*db
)
166 static const struct {
169 void (*xFunc
)(sqlite3_context
*,int,sqlite3_value
**);
171 { "sqlite_rename_table", 2, renameTableFunc
},
172 #ifndef SQLITE_OMIT_TRIGGER
173 { "sqlite_rename_trigger", 2, renameTriggerFunc
},
178 for( i
=0; i
< sizeof(aFuncs
)/sizeof(aFuncs
[0]); i
++)
180 sqlite3_create_function(db
, aFuncs
[i
].zName
, aFuncs
[i
].nArg
,
181 SQLITE_UTF8
, 0, aFuncs
[i
].xFunc
, 0, 0);
187 * Generate the text of a WHERE expression which can be used to select all
188 * temporary triggers on table pTab from the sqlite_temp_master table. If
189 * table pTab has no temporary triggers, or is itself stored in the temporary
190 * database, NULL is returned.
192 static char *whereTempTriggers(Parse
*pParse
, Table
*pTab
)
199 for( pTrig
=pTab
->pTrigger
; pTrig
; pTrig
=pTrig
->pNext
)
201 if( 1 == pTrig
->iDb
)
204 zWhere
= sqlite3MPrintf("name=%Q", pTrig
->name
);
207 zWhere
= sqlite3MPrintf("%s OR name=%Q",
208 zWhere
, pTrig
->name
);
219 * Generate code to drop and reload the internal representation of table pTab
220 * from the database, including triggers and temporary triggers. Argument
221 * zName is the name of the table in the database schema at the time the
222 * generated code is executed. This can be different from pTab->zName if this
223 * function is being called to code part of an "ALTER TABLE RENAME TO"
226 static void reloadTableSchema(Parse
*pParse
, Table
*pTab
, const char *zName
)
231 #ifndef SQLITE_OMIT_TRIGGER
235 if( ! (v
= sqlite3GetVdbe(pParse
))) return;
238 #ifndef SQLITE_OMIT_TRIGGER
239 /* Drop any table triggers from the internal schema. */
240 for( pTrig
= pTab
->pTrigger
; pTrig
; pTrig
= pTrig
->pNext
)
242 assert( pTrig
->iDb
==iDb
|| pTrig
->iDb
==1 );
243 sqlite3VdbeOp3(v
, OP_DropTrigger
, pTrig
->iDb
, 0, pTrig
->name
, 0);
247 /* Drop the table and index from the internal schema */
248 sqlite3VdbeOp3(v
, OP_DropTable
, iDb
, 0, pTab
->zName
, 0);
250 /* Reload the table, index and permanent trigger schemas. */
251 if( ! (zWhere
= sqlite3MPrintf("tbl_name=%Q", zName
))) return;
252 sqlite3VdbeOp3(v
, OP_ParseSchema
, iDb
, 0, zWhere
, P3_DYNAMIC
);
254 #ifndef SQLITE_OMIT_TRIGGER
255 /* Now, if the table is not stored in the temp database, reload any temp
256 * triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
258 if( (zWhere
=whereTempTriggers(pParse
, pTab
)) )
259 sqlite3VdbeOp3(v
, OP_ParseSchema
, 1, 0, zWhere
, P3_DYNAMIC
);
265 * Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" command.
267 void sqlite3AlterRenameTable(
268 Parse
*pParse
, /* Parser context. */
269 SrcList
*pSrc
, /* The table to rename. */
270 Token
*pName
/* The new table name. */
272 int iDb
; /* Database that contains the table */
273 char *zDb
; /* Name of database iDb */
274 Table
*pTab
; /* Table being renamed */
275 char *zName
= 0; /* NULL-terminated version of pName */
276 sqlite3
*db
= pParse
->db
; /* Database connection */
278 #ifndef SQLITE_OMIT_TRIGGER
279 char *zWhere
= 0; /* Where clause to locate temp triggers */
282 assert( pSrc
->nSrc
==1 );
284 pTab
= sqlite3LocateTable(pParse
, pSrc
->a
[0].zName
, pSrc
->a
[0].zDatabase
);
285 if( !pTab
) goto exit_rename_table
;
287 zDb
= db
->aDb
[iDb
].zName
;
289 /* Get a NULL terminated version of the new table name. */
290 zName
= sqlite3NameFromToken(pName
);
291 if( !zName
) goto exit_rename_table
;
294 * Check that a table or index named 'zName' does not already exist in
295 * database iDb. If so, this is an error.
297 if( sqlite3FindTable(db
, zName
, zDb
) || sqlite3FindIndex(db
, zName
, zDb
) )
299 sqlite3ErrorMsg(pParse
,
300 "there is already another table or index with this name: %s",
302 goto exit_rename_table
;
306 * Make sure it is not a system table being altered, or a reserved name
307 * that the table is being renamed to.
309 if( strlen(pTab
->zName
)>6 && 0==sqlite3StrNICmp(pTab
->zName
, "sqlite_", 7) )
311 sqlite3ErrorMsg(pParse
, "table %s may not be altered", pTab
->zName
);
312 goto exit_rename_table
;
314 if( SQLITE_OK
!= sqlite3CheckObjectName(pParse
, zName
))
315 goto exit_rename_table
;
317 #ifndef SQLITE_OMIT_AUTHORIZATION
318 /* Invoke the authorization callback. */
319 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0))
320 goto exit_rename_table
;
324 * Begin a transaction and code the VerifyCookie for database iDb. Then
325 * modify the schema cookie (since the ALTER TABLE modifies the schema).
327 if( 0 == (v
= sqlite3GetVdbe(pParse
)))
328 goto exit_rename_table
;
330 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
331 sqlite3ChangeCookie(db
, v
, iDb
);
333 /* Modify the sqlite_master table to use the new table name. */
334 sqlite3NestedParse(pParse
,
336 #ifdef SQLITE_OMIT_TRIGGER
337 "sql = sqlite_rename_table(sql, %Q), "
340 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
341 "ELSE sqlite_rename_table(sql, %Q) END, "
345 "WHEN type='table' THEN %Q "
346 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
347 "'sqlite_autoindex_' || %Q || substr(name, %d+18,10) "
349 "WHERE tbl_name=%Q AND "
350 "(type='table' OR type='index' OR type='trigger');",
351 zDb
, SCHEMA_TABLE(iDb
), zName
, zName
, zName
,
352 #ifndef SQLITE_OMIT_TRIGGER
355 zName
, strlen(pTab
->zName
), pTab
->zName
358 #ifndef SQLITE_OMIT_AUTOINCREMENT
360 * If the sqlite_sequence table exists in this database, then update it
361 * with the new table name.
363 if( sqlite3FindTable(db
, "sqlite_sequence", zDb
))
364 sqlite3NestedParse(pParse
,
365 "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
366 zDb
, zName
, pTab
->zName
);
369 #ifndef SQLITE_OMIT_TRIGGER
371 * If there are TEMP triggers on this table, modify the sqlite_temp_master
372 * table. Don't do this if the table being ALTERed is itself located in
375 if( (zWhere
= whereTempTriggers( pParse
, pTab
)))
377 sqlite3NestedParse( pParse
,
378 "UPDATE sqlite_temp_master SET "
379 "sql = sqlite_rename_trigger(sql, %Q), "
381 "WHERE %s;", zName
, zName
, zWhere
);
382 sqliteFree( zWhere
);
386 /* Drop and reload the internal table schema. */
387 reloadTableSchema( pParse
, pTab
, zName
);
390 sqlite3SrcListDelete( pSrc
);
396 * This function is called after an "ALTER TABLE ... ADD" statement has been
397 * parsed. Argument pColDef contains the text of the new column definition.
399 * The Table structure pParse->pNewTable was extended to include the new
400 * column during parsing.
402 void sqlite3AlterFinishAddColumn(Parse
*pParse
, Token
*pColDef
)
404 Table
*pNew
; /* Copy of pParse->pNewTable */
405 Table
*pTab
; /* Table being altered */
406 int iDb
; /* Database number */
407 const char *zDb
; /* Database name */
408 const char *zTab
; /* Table name */
409 char *zCol
; /* Null-terminated column definition */
410 Column
*pCol
; /* The new column */
411 Expr
*pDflt
; /* Default value for the new column */
414 if( pParse
->nErr
) return;
415 pNew
= pParse
->pNewTable
;
419 zDb
= pParse
->db
->aDb
[iDb
].zName
;
421 pCol
= &pNew
->aCol
[pNew
->nCol
-1];
423 pTab
= sqlite3FindTable( pParse
->db
, zTab
, zDb
);
427 * If the default value for the new column was specified with a literal
428 * NULL, then set pDflt to 0. This simplifies checking for an SQL NULL
431 if( pDflt
&& pDflt
->op
==TK_NULL
)
435 * Check that the new column is not specified as PRIMARY KEY or UNIQUE.
436 * If there is a NOT NULL constraint, then the default value for the
437 * column must not be NULL.
439 if( pCol
->isPrimKey
)
441 sqlite3ErrorMsg( pParse
, "Cannot add a PRIMARY KEY column");
446 sqlite3ErrorMsg( pParse
, "Cannot add a UNIQUE column");
449 if( pCol
->notNull
&& !pDflt
)
451 sqlite3ErrorMsg( pParse
,
452 "Cannot add a NOT NULL column with default value NULL");
457 * Ensure the default expression is something that sqlite3ValueFromExpr()
458 * can handle (i.e. not CURRENT_TIME etc.)
463 if( sqlite3ValueFromExpr(pDflt
, SQLITE_UTF8
, SQLITE_AFF_NONE
, &pVal
))
465 /* malloc() has failed */
470 sqlite3ErrorMsg( pParse
,
471 "Cannot add a column with non-constant default");
474 sqlite3ValueFree(pVal
);
477 /* Modify the CREATE TABLE statement. */
478 if( (zCol
= sqliteStrNDup(pColDef
->z
, pColDef
->n
)))
480 char *zEnd
= &zCol
[pColDef
->n
-1];
481 while( (zEnd
>zCol
&& *zEnd
==';') || isspace(*(unsigned char *)zEnd
))
484 sqlite3NestedParse( pParse
,
486 "sql = substr(sql,1,%d) || ', "
487 "' || %Q || substr(sql,%d,length(sql)) "
488 "WHERE type = 'table' AND name = %Q",
489 zDb
, SCHEMA_TABLE(iDb
), pNew
->addColOffset
, zCol
,
490 pNew
->addColOffset
+1, zTab
496 * If the default value of the new column is NULL, then set the file
497 * format to 2. If the default value of the new column is not NULL, the
498 * file format becomes 3.
500 if( (v
= sqlite3GetVdbe(pParse
)))
504 /* Only set the file format to $f if it is currently less than $f. */
505 sqlite3VdbeAddOp(v
, OP_ReadCookie
, iDb
, 1);
506 sqlite3VdbeAddOp(v
, OP_Integer
, f
, 0);
507 sqlite3VdbeAddOp(v
, OP_Ge
, 0, sqlite3VdbeCurrentAddr(v
)+3);
508 sqlite3VdbeAddOp(v
, OP_Integer
, f
, 0);
509 sqlite3VdbeAddOp(v
, OP_SetCookie
, iDb
, 1);
512 /* Reload the schema of the modified table. */
513 reloadTableSchema(pParse
, pTab
, pTab
->zName
);
518 * This function is called by the parser after the table-name in an "ALTER
519 * TABLE <table-name> ADD" statement is parsed. Argument pSrc is the full-name
520 * of the table being altered.
522 * This routine makes a (partial) copy of the Table structure for the table
523 * being altered and sets Parse.pNewTable to point to it. Routines called by
524 * the parser as the column definition is parsed (i.e. sqlite3AddColumn()) add
525 * the new Column data to the copy. The copy of the Table structure is deleted
526 * by tokenize.c after parsing is finished.
528 * Routine sqlite3AlterFinishAddColumn() will be called to complete coding the
529 * "ALTER TABLE ... ADD" statement.
531 void sqlite3AlterBeginAddColumn(Parse
*pParse
, SrcList
*pSrc
)
540 /* Look up the table being altered. */
541 assert( !pParse
->pNewTable
);
542 pTab
= sqlite3LocateTable(pParse
, pSrc
->a
[0].zName
, pSrc
->a
[0].zDatabase
);
543 if( !pTab
) goto exit_begin_add_column
;
545 /* Make sure this is not an attempt to ALTER a view. */
548 sqlite3ErrorMsg(pParse
, "Cannot add a column to a view");
549 goto exit_begin_add_column
;
552 assert( pTab
->addColOffset
>0 );
556 * Put a copy of the Table struct in Parse.pNewTable for the
557 * sqlite3AddColumn() function and friends to modify.
559 pNew
= (Table
*)sqliteMalloc(sizeof(Table
));
560 if( !pNew
) goto exit_begin_add_column
;
561 pParse
->pNewTable
= pNew
;
562 pNew
->nCol
= pTab
->nCol
;
563 assert( pNew
->nCol
>0 );
564 nAlloc
= (((pNew
->nCol
-1)/8)*8)+8;
565 assert( nAlloc
>=pNew
->nCol
&& nAlloc
%8==0 && nAlloc
-pNew
->nCol
<8 );
566 pNew
->aCol
= (Column
*)sqliteMalloc(sizeof(Column
)*nAlloc
);
567 pNew
->zName
= sqliteStrDup(pTab
->zName
);
568 if( !pNew
->aCol
|| !pNew
->zName
)
569 goto exit_begin_add_column
;
570 memcpy(pNew
->aCol
, pTab
->aCol
, sizeof(Column
)*pNew
->nCol
);
571 for( i
=0; i
<pNew
->nCol
; i
++ )
573 Column
*pCol
= &pNew
->aCol
[i
];
574 pCol
->zName
= sqliteStrDup(pCol
->zName
);
579 pNew
->addColOffset
= pTab
->addColOffset
;
582 /* Begin a transaction and increment the schema cookie. */
583 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
584 v
= sqlite3GetVdbe(pParse
);
585 if( !v
) goto exit_begin_add_column
;
586 sqlite3ChangeCookie(pParse
->db
, v
, iDb
);
588 exit_begin_add_column
:
589 sqlite3SrcListDelete(pSrc
);
591 #endif /* SQLITE_ALTER_TABLE */