blob: 61953e2b8a140e6293f751041e2603cc9930e748 [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**
drh85b623f2007-12-13 21:54:09 +000015** $Id: alter.c,v 1.35 2007/12/13 21:54:11 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
drhf11c34d2006-09-08 12:27:36 +000031** the CREATE TABLE or CREATE INDEX statement is replaced with the third
drh1f01ec12005-02-15 21:36:18 +000032** 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;
drh2646da72005-12-09 20:02:05 +000050 unsigned char const *zCsr = zSql;
drh1f01ec12005-02-15 21:36:18 +000051 int len = 0;
52 char *zRet;
53
danielk19771e536952007-08-16 10:09:01 +000054 sqlite3 *db = sqlite3_user_data(context);
55
drh1f01ec12005-02-15 21:36:18 +000056 /* The principle used to locate the table name in the CREATE TABLE
57 ** statement is that the table name is the first token that is immediatedly
danielk1977182c4ba2007-06-27 15:53:34 +000058 ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
drh1f01ec12005-02-15 21:36:18 +000059 */
60 if( zSql ){
61 do {
danielk1977dce872b2007-05-08 12:37:45 +000062 if( !*zCsr ){
63 /* Ran out of input before finding an opening bracket. Return NULL. */
64 return;
65 }
66
drh1f01ec12005-02-15 21:36:18 +000067 /* Store the token that zCsr points to in tname. */
68 tname.z = zCsr;
69 tname.n = len;
70
71 /* Advance zCsr to the next token. Store that token type in 'token',
drh85b623f2007-12-13 21:54:09 +000072 ** and its length in 'len' (to be used next iteration of this loop).
drh1f01ec12005-02-15 21:36:18 +000073 */
74 do {
75 zCsr += len;
76 len = sqlite3GetToken(zCsr, &token);
77 } while( token==TK_SPACE );
78 assert( len>0 );
danielk1977182c4ba2007-06-27 15:53:34 +000079 } while( token!=TK_LP && token!=TK_USING );
drh1f01ec12005-02-15 21:36:18 +000080
danielk19771e536952007-08-16 10:09:01 +000081 zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql,
drh1f01ec12005-02-15 21:36:18 +000082 zTableName, tname.z+tname.n);
danielk19771e536952007-08-16 10:09:01 +000083 sqlite3_result_text(context, zRet, -1, sqlite3_free);
drh1f01ec12005-02-15 21:36:18 +000084 }
85}
86
87#ifndef SQLITE_OMIT_TRIGGER
drhf11c34d2006-09-08 12:27:36 +000088/* This function is used by SQL generated to implement the
drh1f01ec12005-02-15 21:36:18 +000089** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
90** statement. The second is a table name. The table name in the CREATE
drhf11c34d2006-09-08 12:27:36 +000091** TRIGGER statement is replaced with the third argument and the result
drh1f01ec12005-02-15 21:36:18 +000092** returned. This is analagous to renameTableFunc() above, except for CREATE
93** TRIGGER, not CREATE INDEX and CREATE TABLE.
94*/
95static void renameTriggerFunc(
96 sqlite3_context *context,
97 int argc,
98 sqlite3_value **argv
99){
100 unsigned char const *zSql = sqlite3_value_text(argv[0]);
101 unsigned char const *zTableName = sqlite3_value_text(argv[1]);
102
103 int token;
104 Token tname;
105 int dist = 3;
drh2646da72005-12-09 20:02:05 +0000106 unsigned char const *zCsr = zSql;
drh1f01ec12005-02-15 21:36:18 +0000107 int len = 0;
108 char *zRet;
109
danielk19771e536952007-08-16 10:09:01 +0000110 sqlite3 *db = sqlite3_user_data(context);
111
drh1f01ec12005-02-15 21:36:18 +0000112 /* The principle used to locate the table name in the CREATE TRIGGER
113 ** statement is that the table name is the first token that is immediatedly
114 ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
115 ** of TK_WHEN, TK_BEGIN or TK_FOR.
116 */
117 if( zSql ){
118 do {
danielk1977dce872b2007-05-08 12:37:45 +0000119
120 if( !*zCsr ){
121 /* Ran out of input before finding the table name. Return NULL. */
122 return;
123 }
124
drh1f01ec12005-02-15 21:36:18 +0000125 /* Store the token that zCsr points to in tname. */
126 tname.z = zCsr;
127 tname.n = len;
128
129 /* Advance zCsr to the next token. Store that token type in 'token',
drh85b623f2007-12-13 21:54:09 +0000130 ** and its length in 'len' (to be used next iteration of this loop).
drh1f01ec12005-02-15 21:36:18 +0000131 */
132 do {
133 zCsr += len;
134 len = sqlite3GetToken(zCsr, &token);
135 }while( token==TK_SPACE );
136 assert( len>0 );
137
138 /* Variable 'dist' stores the number of tokens read since the most
139 ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
140 ** token is read and 'dist' equals 2, the condition stated above
141 ** to be met.
142 **
143 ** Note that ON cannot be a database, table or column name, so
144 ** there is no need to worry about syntax like
145 ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
146 */
147 dist++;
148 if( token==TK_DOT || token==TK_ON ){
149 dist = 0;
150 }
151 } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
152
153 /* Variable tname now contains the token that is the old table-name
154 ** in the CREATE TRIGGER statement.
155 */
danielk19771e536952007-08-16 10:09:01 +0000156 zRet = sqlite3MPrintf(db, "%.*s%Q%s", tname.z - zSql, zSql,
drh1f01ec12005-02-15 21:36:18 +0000157 zTableName, tname.z+tname.n);
danielk19771e536952007-08-16 10:09:01 +0000158 sqlite3_result_text(context, zRet, -1, sqlite3_free);
drh1f01ec12005-02-15 21:36:18 +0000159 }
160}
161#endif /* !SQLITE_OMIT_TRIGGER */
162
163/*
164** Register built-in functions used to help implement ALTER TABLE
165*/
166void sqlite3AlterFunctions(sqlite3 *db){
167 static const struct {
168 char *zName;
169 signed char nArg;
170 void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
171 } aFuncs[] = {
172 { "sqlite_rename_table", 2, renameTableFunc},
173#ifndef SQLITE_OMIT_TRIGGER
174 { "sqlite_rename_trigger", 2, renameTriggerFunc},
175#endif
176 };
177 int i;
178
179 for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
danielk1977771151b2006-01-17 13:21:40 +0000180 sqlite3CreateFunc(db, aFuncs[i].zName, aFuncs[i].nArg,
danielk19771e536952007-08-16 10:09:01 +0000181 SQLITE_UTF8, (void *)db, aFuncs[i].xFunc, 0, 0);
drh1f01ec12005-02-15 21:36:18 +0000182 }
183}
184
drhd0e4a6c2005-02-15 20:47:57 +0000185/*
danielk197719a8e7e2005-03-17 05:03:38 +0000186** Generate the text of a WHERE expression which can be used to select all
187** temporary triggers on table pTab from the sqlite_temp_master table. If
188** table pTab has no temporary triggers, or is itself stored in the
189** temporary database, NULL is returned.
190*/
191static char *whereTempTriggers(Parse *pParse, Table *pTab){
192 Trigger *pTrig;
193 char *zWhere = 0;
194 char *tmp = 0;
danielk1977e501b892006-01-09 06:29:47 +0000195 const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
danielk1977da184232006-01-05 11:34:32 +0000196
197 /* If the table is not located in the temp-db (in which case NULL is
198 ** returned, loop through the tables list of triggers. For each trigger
199 ** that is not part of the temp-db schema, add a clause to the WHERE
200 ** expression being built up in zWhere.
201 */
202 if( pTab->pSchema!=pTempSchema ){
danielk19771e536952007-08-16 10:09:01 +0000203 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000204 for( pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext ){
danielk1977da184232006-01-05 11:34:32 +0000205 if( pTrig->pSchema==pTempSchema ){
danielk197719a8e7e2005-03-17 05:03:38 +0000206 if( !zWhere ){
danielk19771e536952007-08-16 10:09:01 +0000207 zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
danielk197719a8e7e2005-03-17 05:03:38 +0000208 }else{
209 tmp = zWhere;
danielk19771e536952007-08-16 10:09:01 +0000210 zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
drh17435752007-08-16 04:30:38 +0000211 sqlite3_free(tmp);
danielk197719a8e7e2005-03-17 05:03:38 +0000212 }
213 }
214 }
215 }
216 return zWhere;
217}
218
219/*
220** Generate code to drop and reload the internal representation of table
221** pTab from the database, including triggers and temporary triggers.
222** Argument zName is the name of the table in the database schema at
223** the time the generated code is executed. This can be different from
224** pTab->zName if this function is being called to code part of an
225** "ALTER TABLE RENAME TO" statement.
226*/
227static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
228 Vdbe *v;
229 char *zWhere;
danielk1977da184232006-01-05 11:34:32 +0000230 int iDb; /* Index of database containing pTab */
danielk197719a8e7e2005-03-17 05:03:38 +0000231#ifndef SQLITE_OMIT_TRIGGER
232 Trigger *pTrig;
233#endif
234
235 v = sqlite3GetVdbe(pParse);
236 if( !v ) return;
drh1fee73e2007-08-29 04:00:57 +0000237 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +0000238 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
239 assert( iDb>=0 );
danielk197719a8e7e2005-03-17 05:03:38 +0000240
241#ifndef SQLITE_OMIT_TRIGGER
242 /* Drop any table triggers from the internal schema. */
243 for(pTrig=pTab->pTrigger; pTrig; pTrig=pTrig->pNext){
danielk1977da184232006-01-05 11:34:32 +0000244 int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
245 assert( iTrigDb==iDb || iTrigDb==1 );
246 sqlite3VdbeOp3(v, OP_DropTrigger, iTrigDb, 0, pTrig->name, 0);
danielk197719a8e7e2005-03-17 05:03:38 +0000247 }
248#endif
249
250 /* Drop the table and index from the internal schema */
251 sqlite3VdbeOp3(v, OP_DropTable, iDb, 0, pTab->zName, 0);
252
253 /* Reload the table, index and permanent trigger schemas. */
danielk19771e536952007-08-16 10:09:01 +0000254 zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000255 if( !zWhere ) return;
256 sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, zWhere, P3_DYNAMIC);
257
258#ifndef SQLITE_OMIT_TRIGGER
259 /* Now, if the table is not stored in the temp database, reload any temp
260 ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
261 */
drhd9cb6ac2005-10-20 07:28:17 +0000262 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000263 sqlite3VdbeOp3(v, OP_ParseSchema, 1, 0, zWhere, P3_DYNAMIC);
264 }
265#endif
266}
267
268/*
drhd0e4a6c2005-02-15 20:47:57 +0000269** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
270** command.
271*/
272void sqlite3AlterRenameTable(
273 Parse *pParse, /* Parser context. */
274 SrcList *pSrc, /* The table to rename. */
275 Token *pName /* The new table name. */
276){
277 int iDb; /* Database that contains the table */
278 char *zDb; /* Name of database iDb */
279 Table *pTab; /* Table being renamed */
280 char *zName = 0; /* NULL-terminated version of pName */
drhd0e4a6c2005-02-15 20:47:57 +0000281 sqlite3 *db = pParse->db; /* Database connection */
drh4e5dd852007-05-15 03:56:49 +0000282 int nTabName; /* Number of UTF-8 characters in zTabName */
283 const char *zTabName; /* Original name of the table */
drhd0e4a6c2005-02-15 20:47:57 +0000284 Vdbe *v;
285#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000286 char *zWhere = 0; /* Where clause to locate temp triggers */
drhd0e4a6c2005-02-15 20:47:57 +0000287#endif
danielk1977182c4ba2007-06-27 15:53:34 +0000288 int isVirtualRename = 0; /* True if this is a v-table with an xRename() */
drhd0e4a6c2005-02-15 20:47:57 +0000289
drh17435752007-08-16 04:30:38 +0000290 if( db->mallocFailed ) goto exit_rename_table;
drhd0e4a6c2005-02-15 20:47:57 +0000291 assert( pSrc->nSrc==1 );
drh1fee73e2007-08-29 04:00:57 +0000292 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhd0e4a6c2005-02-15 20:47:57 +0000293
294 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
295 if( !pTab ) goto exit_rename_table;
danielk1977da184232006-01-05 11:34:32 +0000296 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhd0e4a6c2005-02-15 20:47:57 +0000297 zDb = db->aDb[iDb].zName;
298
299 /* Get a NULL terminated version of the new table name. */
drh17435752007-08-16 04:30:38 +0000300 zName = sqlite3NameFromToken(db, pName);
drhd0e4a6c2005-02-15 20:47:57 +0000301 if( !zName ) goto exit_rename_table;
302
303 /* Check that a table or index named 'zName' does not already exist
304 ** in database iDb. If so, this is an error.
305 */
306 if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
307 sqlite3ErrorMsg(pParse,
308 "there is already another table or index with this name: %s", zName);
309 goto exit_rename_table;
310 }
311
312 /* Make sure it is not a system table being altered, or a reserved name
313 ** that the table is being renamed to.
314 */
315 if( strlen(pTab->zName)>6 && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ){
316 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
317 goto exit_rename_table;
318 }
319 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
320 goto exit_rename_table;
321 }
322
danielk197761116ae2007-12-13 08:15:30 +0000323#ifndef SQLITE_OMIT_VIEW
324 if( pTab->pSelect ){
325 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
326 goto exit_rename_table;
327 }
328#endif
329
drhd0e4a6c2005-02-15 20:47:57 +0000330#ifndef SQLITE_OMIT_AUTHORIZATION
331 /* Invoke the authorization callback. */
332 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
333 goto exit_rename_table;
334 }
335#endif
336
danielk1977182c4ba2007-06-27 15:53:34 +0000337#ifndef SQLITE_OMIT_VIRTUALTABLE
danielk19775c558862007-06-27 17:09:24 +0000338 if( sqlite3ViewGetColumnNames(pParse, pTab) ){
339 goto exit_rename_table;
340 }
danielk1977182c4ba2007-06-27 15:53:34 +0000341 if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
342 isVirtualRename = 1;
343 }
344#endif
345
drhd0e4a6c2005-02-15 20:47:57 +0000346 /* Begin a transaction and code the VerifyCookie for database iDb.
347 ** Then modify the schema cookie (since the ALTER TABLE modifies the
danielk1977182c4ba2007-06-27 15:53:34 +0000348 ** schema). Open a statement transaction if the table is a virtual
349 ** table.
drhd0e4a6c2005-02-15 20:47:57 +0000350 */
351 v = sqlite3GetVdbe(pParse);
352 if( v==0 ){
353 goto exit_rename_table;
354 }
danielk1977182c4ba2007-06-27 15:53:34 +0000355 sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
drhd0e4a6c2005-02-15 20:47:57 +0000356 sqlite3ChangeCookie(db, v, iDb);
357
danielk1977182c4ba2007-06-27 15:53:34 +0000358 /* If this is a virtual table, invoke the xRename() function if
359 ** one is defined. The xRename() callback will modify the names
360 ** of any resources used by the v-table implementation (including other
361 ** SQLite tables) that are identified by the name of the virtual table.
362 */
363#ifndef SQLITE_OMIT_VIRTUALTABLE
364 if( isVirtualRename ){
365 sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0);
366 sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB);
367 }
368#endif
369
drh4e5dd852007-05-15 03:56:49 +0000370 /* figure out how many UTF-8 characters are in zName */
371 zTabName = pTab->zName;
drh9a087a92007-05-15 14:34:32 +0000372 nTabName = sqlite3Utf8CharLen(zTabName, -1);
drh4e5dd852007-05-15 03:56:49 +0000373
drhd0e4a6c2005-02-15 20:47:57 +0000374 /* Modify the sqlite_master table to use the new table name. */
375 sqlite3NestedParse(pParse,
376 "UPDATE %Q.%s SET "
377#ifdef SQLITE_OMIT_TRIGGER
378 "sql = sqlite_rename_table(sql, %Q), "
379#else
380 "sql = CASE "
381 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
382 "ELSE sqlite_rename_table(sql, %Q) END, "
383#endif
384 "tbl_name = %Q, "
385 "name = CASE "
386 "WHEN type='table' THEN %Q "
387 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
drha21a9292007-10-20 20:58:57 +0000388 "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
drhd0e4a6c2005-02-15 20:47:57 +0000389 "ELSE name END "
390 "WHERE tbl_name=%Q AND "
391 "(type='table' OR type='index' OR type='trigger');",
392 zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
393#ifndef SQLITE_OMIT_TRIGGER
danielk197719a8e7e2005-03-17 05:03:38 +0000394 zName,
drhd0e4a6c2005-02-15 20:47:57 +0000395#endif
drh4e5dd852007-05-15 03:56:49 +0000396 zName, nTabName, zTabName
drhd0e4a6c2005-02-15 20:47:57 +0000397 );
398
399#ifndef SQLITE_OMIT_AUTOINCREMENT
400 /* If the sqlite_sequence table exists in this database, then update
401 ** it with the new table name.
402 */
403 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
404 sqlite3NestedParse(pParse,
405 "UPDATE %Q.sqlite_sequence set name = %Q WHERE name = %Q",
406 zDb, zName, pTab->zName);
407 }
408#endif
409
410#ifndef SQLITE_OMIT_TRIGGER
411 /* If there are TEMP triggers on this table, modify the sqlite_temp_master
412 ** table. Don't do this if the table being ALTERed is itself located in
413 ** the temp database.
414 */
drhd9cb6ac2005-10-20 07:28:17 +0000415 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
danielk197719a8e7e2005-03-17 05:03:38 +0000416 sqlite3NestedParse(pParse,
417 "UPDATE sqlite_temp_master SET "
418 "sql = sqlite_rename_trigger(sql, %Q), "
419 "tbl_name = %Q "
420 "WHERE %s;", zName, zName, zWhere);
drh17435752007-08-16 04:30:38 +0000421 sqlite3_free(zWhere);
drhd0e4a6c2005-02-15 20:47:57 +0000422 }
423#endif
424
danielk197719a8e7e2005-03-17 05:03:38 +0000425 /* Drop and reload the internal table schema. */
426 reloadTableSchema(pParse, pTab, zName);
drhd0e4a6c2005-02-15 20:47:57 +0000427
428exit_rename_table:
429 sqlite3SrcListDelete(pSrc);
drh17435752007-08-16 04:30:38 +0000430 sqlite3_free(zName);
drhd0e4a6c2005-02-15 20:47:57 +0000431}
danielk197719a8e7e2005-03-17 05:03:38 +0000432
433
434/*
435** This function is called after an "ALTER TABLE ... ADD" statement
436** has been parsed. Argument pColDef contains the text of the new
437** column definition.
438**
439** The Table structure pParse->pNewTable was extended to include
440** the new column during parsing.
441*/
442void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
443 Table *pNew; /* Copy of pParse->pNewTable */
444 Table *pTab; /* Table being altered */
445 int iDb; /* Database number */
446 const char *zDb; /* Database name */
447 const char *zTab; /* Table name */
448 char *zCol; /* Null-terminated column definition */
449 Column *pCol; /* The new column */
450 Expr *pDflt; /* Default value for the new column */
drh17435752007-08-16 04:30:38 +0000451 sqlite3 *db; /* The database connection; */
danielk197719a8e7e2005-03-17 05:03:38 +0000452
453 if( pParse->nErr ) return;
454 pNew = pParse->pNewTable;
455 assert( pNew );
456
drh17435752007-08-16 04:30:38 +0000457 db = pParse->db;
drh1fee73e2007-08-29 04:00:57 +0000458 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000459 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
460 zDb = db->aDb[iDb].zName;
danielk197719a8e7e2005-03-17 05:03:38 +0000461 zTab = pNew->zName;
462 pCol = &pNew->aCol[pNew->nCol-1];
463 pDflt = pCol->pDflt;
drh17435752007-08-16 04:30:38 +0000464 pTab = sqlite3FindTable(db, zTab, zDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000465 assert( pTab );
466
drh81f2ccd2006-01-31 14:28:44 +0000467#ifndef SQLITE_OMIT_AUTHORIZATION
468 /* Invoke the authorization callback. */
469 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
470 return;
471 }
472#endif
473
danielk197719a8e7e2005-03-17 05:03:38 +0000474 /* If the default value for the new column was specified with a
475 ** literal NULL, then set pDflt to 0. This simplifies checking
476 ** for an SQL NULL default below.
477 */
478 if( pDflt && pDflt->op==TK_NULL ){
479 pDflt = 0;
480 }
481
482 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
483 ** If there is a NOT NULL constraint, then the default value for the
484 ** column must not be NULL.
485 */
486 if( pCol->isPrimKey ){
487 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
488 return;
489 }
490 if( pNew->pIndex ){
491 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
492 return;
493 }
494 if( pCol->notNull && !pDflt ){
495 sqlite3ErrorMsg(pParse,
496 "Cannot add a NOT NULL column with default value NULL");
497 return;
498 }
499
500 /* Ensure the default expression is something that sqlite3ValueFromExpr()
501 ** can handle (i.e. not CURRENT_TIME etc.)
502 */
503 if( pDflt ){
504 sqlite3_value *pVal;
danielk19771e536952007-08-16 10:09:01 +0000505 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
drh17435752007-08-16 04:30:38 +0000506 db->mallocFailed = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000507 return;
508 }
509 if( !pVal ){
510 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
511 return;
512 }
513 sqlite3ValueFree(pVal);
514 }
515
516 /* Modify the CREATE TABLE statement. */
drh17435752007-08-16 04:30:38 +0000517 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
danielk197719a8e7e2005-03-17 05:03:38 +0000518 if( zCol ){
519 char *zEnd = &zCol[pColDef->n-1];
drh47b4b292005-03-19 14:45:48 +0000520 while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
danielk197719a8e7e2005-03-17 05:03:38 +0000521 *zEnd-- = '\0';
522 }
523 sqlite3NestedParse(pParse,
524 "UPDATE %Q.%s SET "
drha21a9292007-10-20 20:58:57 +0000525 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
danielk197719a8e7e2005-03-17 05:03:38 +0000526 "WHERE type = 'table' AND name = %Q",
527 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
528 zTab
529 );
drh17435752007-08-16 04:30:38 +0000530 sqlite3_free(zCol);
danielk197719a8e7e2005-03-17 05:03:38 +0000531 }
532
533 /* If the default value of the new column is NULL, then set the file
534 ** format to 2. If the default value of the new column is not NULL,
535 ** the file format becomes 3.
536 */
drhfdd6e852005-12-16 01:06:16 +0000537 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
danielk197719a8e7e2005-03-17 05:03:38 +0000538
539 /* Reload the schema of the modified table. */
540 reloadTableSchema(pParse, pTab, pTab->zName);
541}
542
drhfdd6e852005-12-16 01:06:16 +0000543/*
danielk197719a8e7e2005-03-17 05:03:38 +0000544** This function is called by the parser after the table-name in
545** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
546** pSrc is the full-name of the table being altered.
547**
548** This routine makes a (partial) copy of the Table structure
549** for the table being altered and sets Parse.pNewTable to point
550** to it. Routines called by the parser as the column definition
551** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
552** the copy. The copy of the Table structure is deleted by tokenize.c
553** after parsing is finished.
554**
555** Routine sqlite3AlterFinishAddColumn() will be called to complete
556** coding the "ALTER TABLE ... ADD" statement.
557*/
558void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
559 Table *pNew;
560 Table *pTab;
561 Vdbe *v;
562 int iDb;
563 int i;
564 int nAlloc;
drh17435752007-08-16 04:30:38 +0000565 sqlite3 *db = pParse->db;
danielk197719a8e7e2005-03-17 05:03:38 +0000566
567 /* Look up the table being altered. */
drh0bbaa1b2005-08-19 19:14:12 +0000568 assert( pParse->pNewTable==0 );
drh1fee73e2007-08-29 04:00:57 +0000569 assert( sqlite3BtreeHoldsAllMutexes(db) );
drh17435752007-08-16 04:30:38 +0000570 if( db->mallocFailed ) goto exit_begin_add_column;
danielk197719a8e7e2005-03-17 05:03:38 +0000571 pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
572 if( !pTab ) goto exit_begin_add_column;
573
danielk19775ee9d692006-06-21 12:36:25 +0000574#ifndef SQLITE_OMIT_VIRTUALTABLE
575 if( IsVirtual(pTab) ){
576 sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
577 goto exit_begin_add_column;
578 }
579#endif
580
danielk197719a8e7e2005-03-17 05:03:38 +0000581 /* Make sure this is not an attempt to ALTER a view. */
582 if( pTab->pSelect ){
583 sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
584 goto exit_begin_add_column;
585 }
586
587 assert( pTab->addColOffset>0 );
drh17435752007-08-16 04:30:38 +0000588 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk197719a8e7e2005-03-17 05:03:38 +0000589
590 /* Put a copy of the Table struct in Parse.pNewTable for the
591 ** sqlite3AddColumn() function and friends to modify.
592 */
drh17435752007-08-16 04:30:38 +0000593 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
danielk197719a8e7e2005-03-17 05:03:38 +0000594 if( !pNew ) goto exit_begin_add_column;
595 pParse->pNewTable = pNew;
drh0bbaa1b2005-08-19 19:14:12 +0000596 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000597 pNew->nCol = pTab->nCol;
danielk1977b3a2cce2005-03-27 01:56:30 +0000598 assert( pNew->nCol>0 );
599 nAlloc = (((pNew->nCol-1)/8)*8)+8;
600 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
danielk197726783a52007-08-29 14:06:22 +0000601 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
drh17435752007-08-16 04:30:38 +0000602 pNew->zName = sqlite3DbStrDup(db, pTab->zName);
danielk197719a8e7e2005-03-17 05:03:38 +0000603 if( !pNew->aCol || !pNew->zName ){
drh17435752007-08-16 04:30:38 +0000604 db->mallocFailed = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000605 goto exit_begin_add_column;
606 }
607 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
608 for(i=0; i<pNew->nCol; i++){
609 Column *pCol = &pNew->aCol[i];
drh17435752007-08-16 04:30:38 +0000610 pCol->zName = sqlite3DbStrDup(db, pCol->zName);
drhff22e182006-02-09 02:56:02 +0000611 pCol->zColl = 0;
danielk197719a8e7e2005-03-17 05:03:38 +0000612 pCol->zType = 0;
613 pCol->pDflt = 0;
614 }
drh17435752007-08-16 04:30:38 +0000615 pNew->pSchema = db->aDb[iDb].pSchema;
danielk197719a8e7e2005-03-17 05:03:38 +0000616 pNew->addColOffset = pTab->addColOffset;
drhed8a3bb2005-06-06 21:19:56 +0000617 pNew->nRef = 1;
danielk197719a8e7e2005-03-17 05:03:38 +0000618
619 /* Begin a transaction and increment the schema cookie. */
620 sqlite3BeginWriteOperation(pParse, 0, iDb);
621 v = sqlite3GetVdbe(pParse);
622 if( !v ) goto exit_begin_add_column;
drh17435752007-08-16 04:30:38 +0000623 sqlite3ChangeCookie(db, v, iDb);
danielk197719a8e7e2005-03-17 05:03:38 +0000624
625exit_begin_add_column:
626 sqlite3SrcListDelete(pSrc);
627 return;
628}
drhd0e4a6c2005-02-15 20:47:57 +0000629#endif /* SQLITE_ALTER_TABLE */