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.
15 #include "sqliteInt.h"
18 ** The code in this file only exists if we are not omitting the
19 ** ALTER TABLE logic from the build.
21 #ifndef SQLITE_OMIT_ALTERTABLE
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
28 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
29 ** argument and the result returned. Examples:
31 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
32 ** -> 'CREATE TABLE def(a, b, c)'
34 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
35 ** -> 'CREATE INDEX i ON def(a, b, c)'
37 static void renameTableFunc(
38 sqlite3_context
*context
,
42 unsigned char const *zSql
= sqlite3_value_text(argv
[0]);
43 unsigned char const *zTableName
= sqlite3_value_text(argv
[1]);
47 unsigned char const *zCsr
= zSql
;
51 sqlite3
*db
= sqlite3_context_db_handle(context
);
53 UNUSED_PARAMETER(NotUsed
);
55 /* The principle used to locate the table name in the CREATE TABLE
56 ** statement is that the table name is the first non-space token that
57 ** is immediately followed by a TK_LP or TK_USING token.
62 /* Ran out of input before finding an opening bracket. Return NULL. */
66 /* Store the token that zCsr points to in tname. */
67 tname
.z
= (char*)zCsr
;
70 /* Advance zCsr to the next token. Store that token type in 'token',
71 ** and its length in 'len' (to be used next iteration of this loop).
75 len
= sqlite3GetToken(zCsr
, &token
);
76 } while( token
==TK_SPACE
);
78 } while( token
!=TK_LP
&& token
!=TK_USING
);
80 zRet
= sqlite3MPrintf(db
, "%.*s\"%w\"%s", (int)(((u8
*)tname
.z
) - zSql
),
81 zSql
, zTableName
, tname
.z
+tname
.n
);
82 sqlite3_result_text(context
, zRet
, -1, SQLITE_DYNAMIC
);
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:
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.
96 ** It returns the new CREATE TABLE statement. For example:
98 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
99 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
101 #ifndef SQLITE_OMIT_FOREIGN_KEY
102 static void renameParentFunc(
103 sqlite3_context
*context
,
107 sqlite3
*db
= sqlite3_context_db_handle(context
);
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]);
114 unsigned const char *z
; /* Pointer to token */
115 int n
; /* Length of token z */
116 int token
; /* Type of token */
118 UNUSED_PARAMETER(NotUsed
);
119 if( zInput
==0 || zOld
==0 ) return;
120 for(z
=zInput
; *z
; z
=z
+n
){
121 n
= sqlite3GetToken(z
, &token
);
122 if( token
==TK_REFERENCES
){
126 n
= sqlite3GetToken(z
, &token
);
127 }while( token
==TK_SPACE
);
129 if( token
==TK_ILLEGAL
) break;
130 zParent
= sqlite3DbStrNDup(db
, (const char *)z
, n
);
131 if( zParent
==0 ) break;
132 sqlite3Dequote(zParent
);
133 if( 0==sqlite3StrICmp((const char *)zOld
, zParent
) ){
134 char *zOut
= sqlite3MPrintf(db
, "%s%.*s\"%w\"",
135 (zOutput
?zOutput
:""), (int)(z
-zInput
), zInput
, (const char *)zNew
137 sqlite3DbFree(db
, zOutput
);
141 sqlite3DbFree(db
, zParent
);
145 zResult
= sqlite3MPrintf(db
, "%s%s", (zOutput
?zOutput
:""), zInput
);
146 sqlite3_result_text(context
, zResult
, -1, SQLITE_DYNAMIC
);
147 sqlite3DbFree(db
, zOutput
);
151 #ifndef SQLITE_OMIT_TRIGGER
152 /* This function is used by SQL generated to implement the
153 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
154 ** statement. The second is a table name. The table name in the CREATE
155 ** TRIGGER statement is replaced with the third argument and the result
156 ** returned. This is analagous to renameTableFunc() above, except for CREATE
157 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
159 static void renameTriggerFunc(
160 sqlite3_context
*context
,
164 unsigned char const *zSql
= sqlite3_value_text(argv
[0]);
165 unsigned char const *zTableName
= sqlite3_value_text(argv
[1]);
170 unsigned char const *zCsr
= zSql
;
173 sqlite3
*db
= sqlite3_context_db_handle(context
);
175 UNUSED_PARAMETER(NotUsed
);
177 /* The principle used to locate the table name in the CREATE TRIGGER
178 ** statement is that the table name is the first token that is immediately
179 ** preceded by either TK_ON or TK_DOT and immediately followed by one
180 ** of TK_WHEN, TK_BEGIN or TK_FOR.
186 /* Ran out of input before finding the table name. Return NULL. */
190 /* Store the token that zCsr points to in tname. */
191 tname
.z
= (char*)zCsr
;
194 /* Advance zCsr to the next token. Store that token type in 'token',
195 ** and its length in 'len' (to be used next iteration of this loop).
199 len
= sqlite3GetToken(zCsr
, &token
);
200 }while( token
==TK_SPACE
);
203 /* Variable 'dist' stores the number of tokens read since the most
204 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
205 ** token is read and 'dist' equals 2, the condition stated above
208 ** Note that ON cannot be a database, table or column name, so
209 ** there is no need to worry about syntax like
210 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
213 if( token
==TK_DOT
|| token
==TK_ON
){
216 } while( dist
!=2 || (token
!=TK_WHEN
&& token
!=TK_FOR
&& token
!=TK_BEGIN
) );
218 /* Variable tname now contains the token that is the old table-name
219 ** in the CREATE TRIGGER statement.
221 zRet
= sqlite3MPrintf(db
, "%.*s\"%w\"%s", (int)(((u8
*)tname
.z
) - zSql
),
222 zSql
, zTableName
, tname
.z
+tname
.n
);
223 sqlite3_result_text(context
, zRet
, -1, SQLITE_DYNAMIC
);
226 #endif /* !SQLITE_OMIT_TRIGGER */
229 ** Register built-in functions used to help implement ALTER TABLE
231 void sqlite3AlterFunctions(void){
232 static FuncDef aAlterTableFuncs
[] = {
233 FUNCTION(sqlite_rename_table
, 2, 0, 0, renameTableFunc
),
234 #ifndef SQLITE_OMIT_TRIGGER
235 FUNCTION(sqlite_rename_trigger
, 2, 0, 0, renameTriggerFunc
),
237 #ifndef SQLITE_OMIT_FOREIGN_KEY
238 FUNCTION(sqlite_rename_parent
, 3, 0, 0, renameParentFunc
),
241 sqlite3InsertBuiltinFuncs(aAlterTableFuncs
, ArraySize(aAlterTableFuncs
));
245 ** This function is used to create the text of expressions of the form:
247 ** name=<constant1> OR name=<constant2> OR ...
249 ** If argument zWhere is NULL, then a pointer string containing the text
250 ** "name=<constant>" is returned, where <constant> is the quoted version
251 ** of the string passed as argument zConstant. The returned buffer is
252 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
253 ** caller to ensure that it is eventually freed.
255 ** If argument zWhere is not NULL, then the string returned is
256 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
257 ** In this case zWhere is passed to sqlite3DbFree() before returning.
260 static char *whereOrName(sqlite3
*db
, char *zWhere
, char *zConstant
){
263 zNew
= sqlite3MPrintf(db
, "name=%Q", zConstant
);
265 zNew
= sqlite3MPrintf(db
, "%s OR name=%Q", zWhere
, zConstant
);
266 sqlite3DbFree(db
, zWhere
);
271 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
273 ** Generate the text of a WHERE expression which can be used to select all
274 ** tables that have foreign key constraints that refer to table pTab (i.e.
275 ** constraints for which pTab is the parent table) from the sqlite_master
278 static char *whereForeignKeys(Parse
*pParse
, Table
*pTab
){
281 for(p
=sqlite3FkReferences(pTab
); p
; p
=p
->pNextTo
){
282 zWhere
= whereOrName(pParse
->db
, zWhere
, p
->pFrom
->zName
);
289 ** Generate the text of a WHERE expression which can be used to select all
290 ** temporary triggers on table pTab from the sqlite_temp_master table. If
291 ** table pTab has no temporary triggers, or is itself stored in the
292 ** temporary database, NULL is returned.
294 static char *whereTempTriggers(Parse
*pParse
, Table
*pTab
){
297 const Schema
*pTempSchema
= pParse
->db
->aDb
[1].pSchema
; /* Temp db schema */
299 /* If the table is not located in the temp-db (in which case NULL is
300 ** returned, loop through the tables list of triggers. For each trigger
301 ** that is not part of the temp-db schema, add a clause to the WHERE
302 ** expression being built up in zWhere.
304 if( pTab
->pSchema
!=pTempSchema
){
305 sqlite3
*db
= pParse
->db
;
306 for(pTrig
=sqlite3TriggerList(pParse
, pTab
); pTrig
; pTrig
=pTrig
->pNext
){
307 if( pTrig
->pSchema
==pTempSchema
){
308 zWhere
= whereOrName(db
, zWhere
, pTrig
->zName
);
313 char *zNew
= sqlite3MPrintf(pParse
->db
, "type='trigger' AND (%s)", zWhere
);
314 sqlite3DbFree(pParse
->db
, zWhere
);
321 ** Generate code to drop and reload the internal representation of table
322 ** pTab from the database, including triggers and temporary triggers.
323 ** Argument zName is the name of the table in the database schema at
324 ** the time the generated code is executed. This can be different from
325 ** pTab->zName if this function is being called to code part of an
326 ** "ALTER TABLE RENAME TO" statement.
328 static void reloadTableSchema(Parse
*pParse
, Table
*pTab
, const char *zName
){
331 int iDb
; /* Index of database containing pTab */
332 #ifndef SQLITE_OMIT_TRIGGER
336 v
= sqlite3GetVdbe(pParse
);
337 if( NEVER(v
==0) ) return;
338 assert( sqlite3BtreeHoldsAllMutexes(pParse
->db
) );
339 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
342 #ifndef SQLITE_OMIT_TRIGGER
343 /* Drop any table triggers from the internal schema. */
344 for(pTrig
=sqlite3TriggerList(pParse
, pTab
); pTrig
; pTrig
=pTrig
->pNext
){
345 int iTrigDb
= sqlite3SchemaToIndex(pParse
->db
, pTrig
->pSchema
);
346 assert( iTrigDb
==iDb
|| iTrigDb
==1 );
347 sqlite3VdbeAddOp4(v
, OP_DropTrigger
, iTrigDb
, 0, 0, pTrig
->zName
, 0);
351 /* Drop the table and index from the internal schema. */
352 sqlite3VdbeAddOp4(v
, OP_DropTable
, iDb
, 0, 0, pTab
->zName
, 0);
354 /* Reload the table, index and permanent trigger schemas. */
355 zWhere
= sqlite3MPrintf(pParse
->db
, "tbl_name=%Q", zName
);
356 if( !zWhere
) return;
357 sqlite3VdbeAddParseSchemaOp(v
, iDb
, zWhere
);
359 #ifndef SQLITE_OMIT_TRIGGER
360 /* Now, if the table is not stored in the temp database, reload any temp
361 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
363 if( (zWhere
=whereTempTriggers(pParse
, pTab
))!=0 ){
364 sqlite3VdbeAddParseSchemaOp(v
, 1, zWhere
);
370 ** Parameter zName is the name of a table that is about to be altered
371 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
372 ** If the table is a system table, this function leaves an error message
373 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
375 ** Or, if zName is not a system table, zero is returned.
377 static int isSystemTable(Parse
*pParse
, const char *zName
){
378 if( 0==sqlite3StrNICmp(zName
, "sqlite_", 7) ){
379 sqlite3ErrorMsg(pParse
, "table %s may not be altered", zName
);
386 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
389 void sqlite3AlterRenameTable(
390 Parse
*pParse
, /* Parser context. */
391 SrcList
*pSrc
, /* The table to rename. */
392 Token
*pName
/* The new table name. */
394 int iDb
; /* Database that contains the table */
395 char *zDb
; /* Name of database iDb */
396 Table
*pTab
; /* Table being renamed */
397 char *zName
= 0; /* NULL-terminated version of pName */
398 sqlite3
*db
= pParse
->db
; /* Database connection */
399 int nTabName
; /* Number of UTF-8 characters in zTabName */
400 const char *zTabName
; /* Original name of the table */
402 #ifndef SQLITE_OMIT_TRIGGER
403 char *zWhere
= 0; /* Where clause to locate temp triggers */
405 VTable
*pVTab
= 0; /* Non-zero if this is a v-tab with an xRename() */
406 u32 savedDbFlags
; /* Saved value of db->mDbFlags */
408 savedDbFlags
= db
->mDbFlags
;
409 if( NEVER(db
->mallocFailed
) ) goto exit_rename_table
;
410 assert( pSrc
->nSrc
==1 );
411 assert( sqlite3BtreeHoldsAllMutexes(pParse
->db
) );
413 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
414 if( !pTab
) goto exit_rename_table
;
415 iDb
= sqlite3SchemaToIndex(pParse
->db
, pTab
->pSchema
);
416 zDb
= db
->aDb
[iDb
].zDbSName
;
417 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
419 /* Get a NULL terminated version of the new table name. */
420 zName
= sqlite3NameFromToken(db
, pName
);
421 if( !zName
) goto exit_rename_table
;
423 /* Check that a table or index named 'zName' does not already exist
424 ** in database iDb. If so, this is an error.
426 if( sqlite3FindTable(db
, zName
, zDb
) || sqlite3FindIndex(db
, zName
, zDb
) ){
427 sqlite3ErrorMsg(pParse
,
428 "there is already another table or index with this name: %s", zName
);
429 goto exit_rename_table
;
432 /* Make sure it is not a system table being altered, or a reserved name
433 ** that the table is being renamed to.
435 if( SQLITE_OK
!=isSystemTable(pParse
, pTab
->zName
) ){
436 goto exit_rename_table
;
438 if( SQLITE_OK
!=sqlite3CheckObjectName(pParse
, zName
) ){ goto
442 #ifndef SQLITE_OMIT_VIEW
444 sqlite3ErrorMsg(pParse
, "view %s may not be altered", pTab
->zName
);
445 goto exit_rename_table
;
449 #ifndef SQLITE_OMIT_AUTHORIZATION
450 /* Invoke the authorization callback. */
451 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
452 goto exit_rename_table
;
456 #ifndef SQLITE_OMIT_VIRTUALTABLE
457 if( sqlite3ViewGetColumnNames(pParse
, pTab
) ){
458 goto exit_rename_table
;
460 if( IsVirtual(pTab
) ){
461 pVTab
= sqlite3GetVTable(db
, pTab
);
462 if( pVTab
->pVtab
->pModule
->xRename
==0 ){
468 /* Begin a transaction for database iDb.
469 ** Then modify the schema cookie (since the ALTER TABLE modifies the
470 ** schema). Open a statement transaction if the table is a virtual
473 v
= sqlite3GetVdbe(pParse
);
475 goto exit_rename_table
;
477 sqlite3BeginWriteOperation(pParse
, pVTab
!=0, iDb
);
478 sqlite3ChangeCookie(pParse
, iDb
);
480 /* If this is a virtual table, invoke the xRename() function if
481 ** one is defined. The xRename() callback will modify the names
482 ** of any resources used by the v-table implementation (including other
483 ** SQLite tables) that are identified by the name of the virtual table.
485 #ifndef SQLITE_OMIT_VIRTUALTABLE
487 int i
= ++pParse
->nMem
;
488 sqlite3VdbeLoadString(v
, i
, zName
);
489 sqlite3VdbeAddOp4(v
, OP_VRename
, i
, 0, 0,(const char*)pVTab
, P4_VTAB
);
490 sqlite3MayAbort(pParse
);
494 /* figure out how many UTF-8 characters are in zName */
495 zTabName
= pTab
->zName
;
496 nTabName
= sqlite3Utf8CharLen(zTabName
, -1);
498 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
499 if( db
->flags
&SQLITE_ForeignKeys
){
500 /* If foreign-key support is enabled, rewrite the CREATE TABLE
501 ** statements corresponding to all child tables of foreign key constraints
502 ** for which the renamed table is the parent table. */
503 if( (zWhere
=whereForeignKeys(pParse
, pTab
))!=0 ){
504 sqlite3NestedParse(pParse
,
505 "UPDATE \"%w\".%s SET "
506 "sql = sqlite_rename_parent(sql, %Q, %Q) "
507 "WHERE %s;", zDb
, MASTER_NAME
, zTabName
, zName
, zWhere
);
508 sqlite3DbFree(db
, zWhere
);
513 /* Modify the sqlite_master table to use the new table name. */
514 sqlite3NestedParse(pParse
,
516 #ifdef SQLITE_OMIT_TRIGGER
517 "sql = sqlite_rename_table(sql, %Q), "
520 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
521 "ELSE sqlite_rename_table(sql, %Q) END, "
525 "WHEN type='table' THEN %Q "
526 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
527 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
529 "WHERE tbl_name=%Q COLLATE nocase AND "
530 "(type='table' OR type='index' OR type='trigger');",
531 zDb
, MASTER_NAME
, zName
, zName
, zName
,
532 #ifndef SQLITE_OMIT_TRIGGER
535 zName
, nTabName
, zTabName
538 #ifndef SQLITE_OMIT_AUTOINCREMENT
539 /* If the sqlite_sequence table exists in this database, then update
540 ** it with the new table name.
542 if( sqlite3FindTable(db
, "sqlite_sequence", zDb
) ){
543 sqlite3NestedParse(pParse
,
544 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
545 zDb
, zName
, pTab
->zName
);
549 #ifndef SQLITE_OMIT_TRIGGER
550 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
551 ** table. Don't do this if the table being ALTERed is itself located in
552 ** the temp database.
554 if( (zWhere
=whereTempTriggers(pParse
, pTab
))!=0 ){
555 sqlite3NestedParse(pParse
,
556 "UPDATE sqlite_temp_master SET "
557 "sql = sqlite_rename_trigger(sql, %Q), "
559 "WHERE %s;", zName
, zName
, zWhere
);
560 sqlite3DbFree(db
, zWhere
);
564 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
565 if( db
->flags
&SQLITE_ForeignKeys
){
567 for(p
=sqlite3FkReferences(pTab
); p
; p
=p
->pNextTo
){
568 Table
*pFrom
= p
->pFrom
;
570 reloadTableSchema(pParse
, p
->pFrom
, pFrom
->zName
);
576 /* Drop and reload the internal table schema. */
577 reloadTableSchema(pParse
, pTab
, zName
);
580 sqlite3SrcListDelete(db
, pSrc
);
581 sqlite3DbFree(db
, zName
);
582 db
->mDbFlags
= savedDbFlags
;
586 ** This function is called after an "ALTER TABLE ... ADD" statement
587 ** has been parsed. Argument pColDef contains the text of the new
588 ** column definition.
590 ** The Table structure pParse->pNewTable was extended to include
591 ** the new column during parsing.
593 void sqlite3AlterFinishAddColumn(Parse
*pParse
, Token
*pColDef
){
594 Table
*pNew
; /* Copy of pParse->pNewTable */
595 Table
*pTab
; /* Table being altered */
596 int iDb
; /* Database number */
597 const char *zDb
; /* Database name */
598 const char *zTab
; /* Table name */
599 char *zCol
; /* Null-terminated column definition */
600 Column
*pCol
; /* The new column */
601 Expr
*pDflt
; /* Default value for the new column */
602 sqlite3
*db
; /* The database connection; */
603 Vdbe
*v
= pParse
->pVdbe
; /* The prepared statement under construction */
604 int r1
; /* Temporary registers */
607 if( pParse
->nErr
|| db
->mallocFailed
) return;
609 pNew
= pParse
->pNewTable
;
612 assert( sqlite3BtreeHoldsAllMutexes(db
) );
613 iDb
= sqlite3SchemaToIndex(db
, pNew
->pSchema
);
614 zDb
= db
->aDb
[iDb
].zDbSName
;
615 zTab
= &pNew
->zName
[16]; /* Skip the "sqlite_altertab_" prefix on the name */
616 pCol
= &pNew
->aCol
[pNew
->nCol
-1];
618 pTab
= sqlite3FindTable(db
, zTab
, zDb
);
621 #ifndef SQLITE_OMIT_AUTHORIZATION
622 /* Invoke the authorization callback. */
623 if( sqlite3AuthCheck(pParse
, SQLITE_ALTER_TABLE
, zDb
, pTab
->zName
, 0) ){
628 /* If the default value for the new column was specified with a
629 ** literal NULL, then set pDflt to 0. This simplifies checking
630 ** for an SQL NULL default below.
632 assert( pDflt
==0 || pDflt
->op
==TK_SPAN
);
633 if( pDflt
&& pDflt
->pLeft
->op
==TK_NULL
){
637 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
638 ** If there is a NOT NULL constraint, then the default value for the
639 ** column must not be NULL.
641 if( pCol
->colFlags
& COLFLAG_PRIMKEY
){
642 sqlite3ErrorMsg(pParse
, "Cannot add a PRIMARY KEY column");
646 sqlite3ErrorMsg(pParse
, "Cannot add a UNIQUE column");
649 if( (db
->flags
&SQLITE_ForeignKeys
) && pNew
->pFKey
&& pDflt
){
650 sqlite3ErrorMsg(pParse
,
651 "Cannot add a REFERENCES column with non-NULL default value");
654 if( pCol
->notNull
&& !pDflt
){
655 sqlite3ErrorMsg(pParse
,
656 "Cannot add a NOT NULL column with default value NULL");
660 /* Ensure the default expression is something that sqlite3ValueFromExpr()
661 ** can handle (i.e. not CURRENT_TIME etc.)
664 sqlite3_value
*pVal
= 0;
666 rc
= sqlite3ValueFromExpr(db
, pDflt
, SQLITE_UTF8
, SQLITE_AFF_BLOB
, &pVal
);
667 assert( rc
==SQLITE_OK
|| rc
==SQLITE_NOMEM
);
669 assert( db
->mallocFailed
== 1 );
673 sqlite3ErrorMsg(pParse
, "Cannot add a column with non-constant default");
676 sqlite3ValueFree(pVal
);
679 /* Modify the CREATE TABLE statement. */
680 zCol
= sqlite3DbStrNDup(db
, (char*)pColDef
->z
, pColDef
->n
);
682 char *zEnd
= &zCol
[pColDef
->n
-1];
683 u32 savedDbFlags
= db
->mDbFlags
;
684 while( zEnd
>zCol
&& (*zEnd
==';' || sqlite3Isspace(*zEnd
)) ){
687 db
->mDbFlags
|= DBFLAG_PreferBuiltin
;
688 sqlite3NestedParse(pParse
,
689 "UPDATE \"%w\".%s SET "
690 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
691 "WHERE type = 'table' AND name = %Q",
692 zDb
, MASTER_NAME
, pNew
->addColOffset
, zCol
, pNew
->addColOffset
+1,
695 sqlite3DbFree(db
, zCol
);
696 db
->mDbFlags
= savedDbFlags
;
699 /* Make sure the schema version is at least 3. But do not upgrade
700 ** from less than 3 to 4, as that will corrupt any preexisting DESC
703 r1
= sqlite3GetTempReg(pParse
);
704 sqlite3VdbeAddOp3(v
, OP_ReadCookie
, iDb
, r1
, BTREE_FILE_FORMAT
);
705 sqlite3VdbeUsesBtree(v
, iDb
);
706 sqlite3VdbeAddOp2(v
, OP_AddImm
, r1
, -2);
707 sqlite3VdbeAddOp2(v
, OP_IfPos
, r1
, sqlite3VdbeCurrentAddr(v
)+2);
709 sqlite3VdbeAddOp3(v
, OP_SetCookie
, iDb
, BTREE_FILE_FORMAT
, 3);
710 sqlite3ReleaseTempReg(pParse
, r1
);
712 /* Reload the schema of the modified table. */
713 reloadTableSchema(pParse
, pTab
, pTab
->zName
);
717 ** This function is called by the parser after the table-name in
718 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
719 ** pSrc is the full-name of the table being altered.
721 ** This routine makes a (partial) copy of the Table structure
722 ** for the table being altered and sets Parse.pNewTable to point
723 ** to it. Routines called by the parser as the column definition
724 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
725 ** the copy. The copy of the Table structure is deleted by tokenize.c
726 ** after parsing is finished.
728 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
729 ** coding the "ALTER TABLE ... ADD" statement.
731 void sqlite3AlterBeginAddColumn(Parse
*pParse
, SrcList
*pSrc
){
738 sqlite3
*db
= pParse
->db
;
740 /* Look up the table being altered. */
741 assert( pParse
->pNewTable
==0 );
742 assert( sqlite3BtreeHoldsAllMutexes(db
) );
743 if( db
->mallocFailed
) goto exit_begin_add_column
;
744 pTab
= sqlite3LocateTableItem(pParse
, 0, &pSrc
->a
[0]);
745 if( !pTab
) goto exit_begin_add_column
;
747 #ifndef SQLITE_OMIT_VIRTUALTABLE
748 if( IsVirtual(pTab
) ){
749 sqlite3ErrorMsg(pParse
, "virtual tables may not be altered");
750 goto exit_begin_add_column
;
754 /* Make sure this is not an attempt to ALTER a view. */
756 sqlite3ErrorMsg(pParse
, "Cannot add a column to a view");
757 goto exit_begin_add_column
;
759 if( SQLITE_OK
!=isSystemTable(pParse
, pTab
->zName
) ){
760 goto exit_begin_add_column
;
763 assert( pTab
->addColOffset
>0 );
764 iDb
= sqlite3SchemaToIndex(db
, pTab
->pSchema
);
766 /* Put a copy of the Table struct in Parse.pNewTable for the
767 ** 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.
773 pNew
= (Table
*)sqlite3DbMallocZero(db
, sizeof(Table
));
774 if( !pNew
) goto exit_begin_add_column
;
775 pParse
->pNewTable
= pNew
;
777 pNew
->nCol
= pTab
->nCol
;
778 assert( pNew
->nCol
>0 );
779 nAlloc
= (((pNew
->nCol
-1)/8)*8)+8;
780 assert( nAlloc
>=pNew
->nCol
&& nAlloc
%8==0 && nAlloc
-pNew
->nCol
<8 );
781 pNew
->aCol
= (Column
*)sqlite3DbMallocZero(db
, sizeof(Column
)*nAlloc
);
782 pNew
->zName
= sqlite3MPrintf(db
, "sqlite_altertab_%s", pTab
->zName
);
783 if( !pNew
->aCol
|| !pNew
->zName
){
784 assert( db
->mallocFailed
);
785 goto exit_begin_add_column
;
787 memcpy(pNew
->aCol
, pTab
->aCol
, sizeof(Column
)*pNew
->nCol
);
788 for(i
=0; i
<pNew
->nCol
; i
++){
789 Column
*pCol
= &pNew
->aCol
[i
];
790 pCol
->zName
= sqlite3DbStrDup(db
, pCol
->zName
);
794 pNew
->pSchema
= db
->aDb
[iDb
].pSchema
;
795 pNew
->addColOffset
= pTab
->addColOffset
;
798 /* Begin a transaction and increment the schema cookie. */
799 sqlite3BeginWriteOperation(pParse
, 0, iDb
);
800 v
= sqlite3GetVdbe(pParse
);
801 if( !v
) goto exit_begin_add_column
;
802 sqlite3ChangeCookie(pParse
, iDb
);
804 exit_begin_add_column
:
805 sqlite3SrcListDelete(db
, pSrc
);
808 #endif /* SQLITE_ALTER_TABLE */