xref: /sqlite-3.40.0/src/alter.c (revision fd3b2226)
1 /*
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 **
15 ** $Id: alter.c,v 1.62 2009/07/24 17:58:53 danielk1977 Exp $
16 */
17 #include "sqliteInt.h"
18 
19 /*
20 ** The code in this file only exists if we are not omitting the
21 ** ALTER TABLE logic from the build.
22 */
23 #ifndef SQLITE_OMIT_ALTERTABLE
24 
25 
26 /*
27 ** This function is used by SQL generated to implement the
28 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
29 ** CREATE INDEX command. The second is a table name. The table name in
30 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
31 ** argument and the result returned. Examples:
32 **
33 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
34 **     -> 'CREATE TABLE def(a, b, c)'
35 **
36 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
37 **     -> 'CREATE INDEX i ON def(a, b, c)'
38 */
39 static void renameTableFunc(
40   sqlite3_context *context,
41   int NotUsed,
42   sqlite3_value **argv
43 ){
44   unsigned char const *zSql = sqlite3_value_text(argv[0]);
45   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
46 
47   int token;
48   Token tname;
49   unsigned char const *zCsr = zSql;
50   int len = 0;
51   char *zRet;
52 
53   sqlite3 *db = sqlite3_context_db_handle(context);
54 
55   UNUSED_PARAMETER(NotUsed);
56 
57   /* The principle used to locate the table name in the CREATE TABLE
58   ** statement is that the table name is the first non-space token that
59   ** is immediately followed by a TK_LP or TK_USING token.
60   */
61   if( zSql ){
62     do {
63       if( !*zCsr ){
64         /* Ran out of input before finding an opening bracket. Return NULL. */
65         return;
66       }
67 
68       /* Store the token that zCsr points to in tname. */
69       tname.z = (char*)zCsr;
70       tname.n = len;
71 
72       /* Advance zCsr to the next token. Store that token type in 'token',
73       ** and its length in 'len' (to be used next iteration of this loop).
74       */
75       do {
76         zCsr += len;
77         len = sqlite3GetToken(zCsr, &token);
78       } while( token==TK_SPACE );
79       assert( len>0 );
80     } while( token!=TK_LP && token!=TK_USING );
81 
82     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
83        zTableName, tname.z+tname.n);
84     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
85   }
86 }
87 
88 /*
89 ** This C function implements an SQL user function that is used by SQL code
90 ** generated by the ALTER TABLE ... RENAME command to modify the definition
91 ** of any foreign key constraints that use the table being renamed as the
92 ** parent table. It is passed three arguments:
93 **
94 **   1) The complete text of the CREATE TABLE statement being modified,
95 **   2) The old name of the table being renamed, and
96 **   3) The new name of the table being renamed.
97 **
98 ** It returns the new CREATE TABLE statement. For example:
99 **
100 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
101 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
102 */
103 #ifndef SQLITE_OMIT_FOREIGN_KEY
104 static void renameParentFunc(
105   sqlite3_context *context,
106   int NotUsed,
107   sqlite3_value **argv
108 ){
109   sqlite3 *db = sqlite3_context_db_handle(context);
110   char *zOutput = 0;
111   char *zResult;
112   unsigned char const *zInput = sqlite3_value_text(argv[0]);
113   unsigned char const *zOld = sqlite3_value_text(argv[1]);
114   unsigned char const *zNew = sqlite3_value_text(argv[2]);
115 
116   unsigned const char *z;         /* Pointer to token */
117   int n;                          /* Length of token z */
118   int token;                      /* Type of token */
119 
120   UNUSED_PARAMETER(NotUsed);
121   for(z=zInput; *z; z=z+n){
122     n = sqlite3GetToken(z, &token);
123     if( token==TK_REFERENCES ){
124       char *zParent;
125       do {
126         z += n;
127         n = sqlite3GetToken(z, &token);
128       }while( token==TK_SPACE );
129 
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:""), z-zInput, zInput, (const char *)zNew
136         );
137         sqlite3DbFree(db, zOutput);
138         zOutput = zOut;
139         zInput = &z[n];
140       }
141       sqlite3DbFree(db, zParent);
142     }
143   }
144 
145   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
146   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
147   sqlite3DbFree(db, zOutput);
148 }
149 #endif
150 
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.
158 */
159 static void renameTriggerFunc(
160   sqlite3_context *context,
161   int NotUsed,
162   sqlite3_value **argv
163 ){
164   unsigned char const *zSql = sqlite3_value_text(argv[0]);
165   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
166 
167   int token;
168   Token tname;
169   int dist = 3;
170   unsigned char const *zCsr = zSql;
171   int len = 0;
172   char *zRet;
173   sqlite3 *db = sqlite3_context_db_handle(context);
174 
175   UNUSED_PARAMETER(NotUsed);
176 
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 immediatedly
179   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
180   ** of TK_WHEN, TK_BEGIN or TK_FOR.
181   */
182   if( zSql ){
183     do {
184 
185       if( !*zCsr ){
186         /* Ran out of input before finding the table name. Return NULL. */
187         return;
188       }
189 
190       /* Store the token that zCsr points to in tname. */
191       tname.z = (char*)zCsr;
192       tname.n = len;
193 
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).
196       */
197       do {
198         zCsr += len;
199         len = sqlite3GetToken(zCsr, &token);
200       }while( token==TK_SPACE );
201       assert( len>0 );
202 
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
206       ** to be met.
207       **
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.
211       */
212       dist++;
213       if( token==TK_DOT || token==TK_ON ){
214         dist = 0;
215       }
216     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
217 
218     /* Variable tname now contains the token that is the old table-name
219     ** in the CREATE TRIGGER statement.
220     */
221     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
222        zTableName, tname.z+tname.n);
223     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
224   }
225 }
226 #endif   /* !SQLITE_OMIT_TRIGGER */
227 
228 /*
229 ** Register built-in functions used to help implement ALTER TABLE
230 */
231 void sqlite3AlterFunctions(sqlite3 *db){
232   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
233                          renameTableFunc, 0, 0);
234 #ifndef SQLITE_OMIT_TRIGGER
235   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
236                          renameTriggerFunc, 0, 0);
237 #endif
238 #ifndef SQLITE_OMIT_FOREIGN_KEY
239   sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
240                          renameParentFunc, 0, 0);
241 #endif
242 }
243 
244 /*
245 ** This function is used to create the text of expressions of the form:
246 **
247 **   name=<constant1> OR name=<constant2> OR ...
248 **
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.
254 **
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.
258 **
259 */
260 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
261   char *zNew;
262   if( !zWhere ){
263     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
264   }else{
265     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
266     sqlite3DbFree(db, zWhere);
267   }
268   return zNew;
269 }
270 
271 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
272 /*
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
276 ** table.
277 */
278 static char *whereForeignKeys(Parse *pParse, Table *pTab){
279   FKey *p;
280   char *zWhere = 0;
281   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
282     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
283   }
284   return zWhere;
285 }
286 #endif
287 
288 /*
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.
293 */
294 static char *whereTempTriggers(Parse *pParse, Table *pTab){
295   Trigger *pTrig;
296   char *zWhere = 0;
297   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
298 
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.
303   */
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);
309       }
310     }
311   }
312   return zWhere;
313 }
314 
315 /*
316 ** Generate code to drop and reload the internal representation of table
317 ** pTab from the database, including triggers and temporary triggers.
318 ** Argument zName is the name of the table in the database schema at
319 ** the time the generated code is executed. This can be different from
320 ** pTab->zName if this function is being called to code part of an
321 ** "ALTER TABLE RENAME TO" statement.
322 */
323 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
324   Vdbe *v;
325   char *zWhere;
326   int iDb;                   /* Index of database containing pTab */
327 #ifndef SQLITE_OMIT_TRIGGER
328   Trigger *pTrig;
329 #endif
330 
331   v = sqlite3GetVdbe(pParse);
332   if( NEVER(v==0) ) return;
333   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
334   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
335   assert( iDb>=0 );
336 
337 #ifndef SQLITE_OMIT_TRIGGER
338   /* Drop any table triggers from the internal schema. */
339   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
340     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
341     assert( iTrigDb==iDb || iTrigDb==1 );
342     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
343   }
344 #endif
345 
346   /* Drop the table and index from the internal schema.  */
347   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
348 
349   /* Reload the table, index and permanent trigger schemas. */
350   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
351   if( !zWhere ) return;
352   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
353 
354 #ifndef SQLITE_OMIT_TRIGGER
355   /* Now, if the table is not stored in the temp database, reload any temp
356   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
357   */
358   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
359     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
360   }
361 #endif
362 }
363 
364 /*
365 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
366 ** command.
367 */
368 void sqlite3AlterRenameTable(
369   Parse *pParse,            /* Parser context. */
370   SrcList *pSrc,            /* The table to rename. */
371   Token *pName              /* The new table name. */
372 ){
373   int iDb;                  /* Database that contains the table */
374   char *zDb;                /* Name of database iDb */
375   Table *pTab;              /* Table being renamed */
376   char *zName = 0;          /* NULL-terminated version of pName */
377   sqlite3 *db = pParse->db; /* Database connection */
378   int nTabName;             /* Number of UTF-8 characters in zTabName */
379   const char *zTabName;     /* Original name of the table */
380   Vdbe *v;
381 #ifndef SQLITE_OMIT_TRIGGER
382   char *zWhere = 0;         /* Where clause to locate temp triggers */
383 #endif
384   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
385 
386   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
387   assert( pSrc->nSrc==1 );
388   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
389 
390   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
391   if( !pTab ) goto exit_rename_table;
392   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
393   zDb = db->aDb[iDb].zName;
394 
395   /* Get a NULL terminated version of the new table name. */
396   zName = sqlite3NameFromToken(db, pName);
397   if( !zName ) goto exit_rename_table;
398 
399   /* Check that a table or index named 'zName' does not already exist
400   ** in database iDb. If so, this is an error.
401   */
402   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
403     sqlite3ErrorMsg(pParse,
404         "there is already another table or index with this name: %s", zName);
405     goto exit_rename_table;
406   }
407 
408   /* Make sure it is not a system table being altered, or a reserved name
409   ** that the table is being renamed to.
410   */
411   if( sqlite3Strlen30(pTab->zName)>6
412    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
413   ){
414     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
415     goto exit_rename_table;
416   }
417   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
418     goto exit_rename_table;
419   }
420 
421 #ifndef SQLITE_OMIT_VIEW
422   if( pTab->pSelect ){
423     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
424     goto exit_rename_table;
425   }
426 #endif
427 
428 #ifndef SQLITE_OMIT_AUTHORIZATION
429   /* Invoke the authorization callback. */
430   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
431     goto exit_rename_table;
432   }
433 #endif
434 
435 #ifndef SQLITE_OMIT_VIRTUALTABLE
436   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
437     goto exit_rename_table;
438   }
439   if( IsVirtual(pTab) ){
440     pVTab = sqlite3GetVTable(db, pTab);
441     if( pVTab->pVtab->pModule->xRename==0 ){
442       pVTab = 0;
443     }
444   }
445 #endif
446 
447   /* Begin a transaction and code the VerifyCookie for database iDb.
448   ** Then modify the schema cookie (since the ALTER TABLE modifies the
449   ** schema). Open a statement transaction if the table is a virtual
450   ** table.
451   */
452   v = sqlite3GetVdbe(pParse);
453   if( v==0 ){
454     goto exit_rename_table;
455   }
456   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
457   sqlite3ChangeCookie(pParse, iDb);
458 
459   /* If this is a virtual table, invoke the xRename() function if
460   ** one is defined. The xRename() callback will modify the names
461   ** of any resources used by the v-table implementation (including other
462   ** SQLite tables) that are identified by the name of the virtual table.
463   */
464 #ifndef SQLITE_OMIT_VIRTUALTABLE
465   if( pVTab ){
466     int i = ++pParse->nMem;
467     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
468     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
469     sqlite3MayAbort(pParse);
470   }
471 #endif
472 
473   /* figure out how many UTF-8 characters are in zName */
474   zTabName = pTab->zName;
475   nTabName = sqlite3Utf8CharLen(zTabName, -1);
476 
477 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
478   if( db->flags&SQLITE_ForeignKeys ){
479     /* If foreign-key support is enabled, rewrite the CREATE TABLE
480     ** statements corresponding to all child tables of foreign key constraints
481     ** for which the renamed table is the parent table.  */
482     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
483       sqlite3NestedParse(pParse,
484           "UPDATE sqlite_master SET "
485               "sql = sqlite_rename_parent(sql, %Q, %Q) "
486               "WHERE %s;", zTabName, zName, zWhere);
487       sqlite3DbFree(db, zWhere);
488     }
489   }
490 #endif
491 
492   /* Modify the sqlite_master table to use the new table name. */
493   sqlite3NestedParse(pParse,
494       "UPDATE %Q.%s SET "
495 #ifdef SQLITE_OMIT_TRIGGER
496           "sql = sqlite_rename_table(sql, %Q), "
497 #else
498           "sql = CASE "
499             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
500             "ELSE sqlite_rename_table(sql, %Q) END, "
501 #endif
502           "tbl_name = %Q, "
503           "name = CASE "
504             "WHEN type='table' THEN %Q "
505             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
506              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
507             "ELSE name END "
508       "WHERE tbl_name=%Q AND "
509           "(type='table' OR type='index' OR type='trigger');",
510       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
511 #ifndef SQLITE_OMIT_TRIGGER
512       zName,
513 #endif
514       zName, nTabName, zTabName
515   );
516 
517 #ifndef SQLITE_OMIT_AUTOINCREMENT
518   /* If the sqlite_sequence table exists in this database, then update
519   ** it with the new table name.
520   */
521   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
522     sqlite3NestedParse(pParse,
523         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
524         zDb, zName, pTab->zName);
525   }
526 #endif
527 
528 #ifndef SQLITE_OMIT_TRIGGER
529   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
530   ** table. Don't do this if the table being ALTERed is itself located in
531   ** the temp database.
532   */
533   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
534     sqlite3NestedParse(pParse,
535         "UPDATE sqlite_temp_master SET "
536             "sql = sqlite_rename_trigger(sql, %Q), "
537             "tbl_name = %Q "
538             "WHERE %s;", zName, zName, zWhere);
539     sqlite3DbFree(db, zWhere);
540   }
541 #endif
542 
543 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
544   if( db->flags&SQLITE_ForeignKeys ){
545     FKey *p;
546     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
547       Table *pFrom = p->pFrom;
548       if( pFrom!=pTab ){
549         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
550       }
551     }
552   }
553 #endif
554 
555   /* Drop and reload the internal table schema. */
556   reloadTableSchema(pParse, pTab, zName);
557 
558 exit_rename_table:
559   sqlite3SrcListDelete(db, pSrc);
560   sqlite3DbFree(db, zName);
561 }
562 
563 
564 /*
565 ** Generate code to make sure the file format number is at least minFormat.
566 ** The generated code will increase the file format number if necessary.
567 */
568 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
569   Vdbe *v;
570   v = sqlite3GetVdbe(pParse);
571   /* The VDBE should have been allocated before this routine is called.
572   ** If that allocation failed, we would have quit before reaching this
573   ** point */
574   if( ALWAYS(v) ){
575     int r1 = sqlite3GetTempReg(pParse);
576     int r2 = sqlite3GetTempReg(pParse);
577     int j1;
578     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
579     sqlite3VdbeUsesBtree(v, iDb);
580     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
581     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
582     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
583     sqlite3VdbeJumpHere(v, j1);
584     sqlite3ReleaseTempReg(pParse, r1);
585     sqlite3ReleaseTempReg(pParse, r2);
586   }
587 }
588 
589 /*
590 ** This function is called after an "ALTER TABLE ... ADD" statement
591 ** has been parsed. Argument pColDef contains the text of the new
592 ** column definition.
593 **
594 ** The Table structure pParse->pNewTable was extended to include
595 ** the new column during parsing.
596 */
597 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
598   Table *pNew;              /* Copy of pParse->pNewTable */
599   Table *pTab;              /* Table being altered */
600   int iDb;                  /* Database number */
601   const char *zDb;          /* Database name */
602   const char *zTab;         /* Table name */
603   char *zCol;               /* Null-terminated column definition */
604   Column *pCol;             /* The new column */
605   Expr *pDflt;              /* Default value for the new column */
606   sqlite3 *db;              /* The database connection; */
607 
608   db = pParse->db;
609   if( pParse->nErr || db->mallocFailed ) return;
610   pNew = pParse->pNewTable;
611   assert( pNew );
612 
613   assert( sqlite3BtreeHoldsAllMutexes(db) );
614   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
615   zDb = db->aDb[iDb].zName;
616   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
617   pCol = &pNew->aCol[pNew->nCol-1];
618   pDflt = pCol->pDflt;
619   pTab = sqlite3FindTable(db, zTab, zDb);
620   assert( pTab );
621 
622 #ifndef SQLITE_OMIT_AUTHORIZATION
623   /* Invoke the authorization callback. */
624   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
625     return;
626   }
627 #endif
628 
629   /* If the default value for the new column was specified with a
630   ** literal NULL, then set pDflt to 0. This simplifies checking
631   ** for an SQL NULL default below.
632   */
633   if( pDflt && pDflt->op==TK_NULL ){
634     pDflt = 0;
635   }
636 
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.
640   */
641   if( pCol->isPrimKey ){
642     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
643     return;
644   }
645   if( pNew->pIndex ){
646     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
647     return;
648   }
649   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
650     sqlite3ErrorMsg(pParse,
651         "Cannot add a REFERENCES column with non-NULL default value");
652     return;
653   }
654   if( pCol->notNull && !pDflt ){
655     sqlite3ErrorMsg(pParse,
656         "Cannot add a NOT NULL column with default value NULL");
657     return;
658   }
659 
660   /* Ensure the default expression is something that sqlite3ValueFromExpr()
661   ** can handle (i.e. not CURRENT_TIME etc.)
662   */
663   if( pDflt ){
664     sqlite3_value *pVal;
665     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
666       db->mallocFailed = 1;
667       return;
668     }
669     if( !pVal ){
670       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
671       return;
672     }
673     sqlite3ValueFree(pVal);
674   }
675 
676   /* Modify the CREATE TABLE statement. */
677   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
678   if( zCol ){
679     char *zEnd = &zCol[pColDef->n-1];
680     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
681       *zEnd-- = '\0';
682     }
683     sqlite3NestedParse(pParse,
684         "UPDATE \"%w\".%s SET "
685           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
686         "WHERE type = 'table' AND name = %Q",
687       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
688       zTab
689     );
690     sqlite3DbFree(db, zCol);
691   }
692 
693   /* If the default value of the new column is NULL, then set the file
694   ** format to 2. If the default value of the new column is not NULL,
695   ** the file format becomes 3.
696   */
697   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
698 
699   /* Reload the schema of the modified table. */
700   reloadTableSchema(pParse, pTab, pTab->zName);
701 }
702 
703 /*
704 ** This function is called by the parser after the table-name in
705 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
706 ** pSrc is the full-name of the table being altered.
707 **
708 ** This routine makes a (partial) copy of the Table structure
709 ** for the table being altered and sets Parse.pNewTable to point
710 ** to it. Routines called by the parser as the column definition
711 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
712 ** the copy. The copy of the Table structure is deleted by tokenize.c
713 ** after parsing is finished.
714 **
715 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
716 ** coding the "ALTER TABLE ... ADD" statement.
717 */
718 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
719   Table *pNew;
720   Table *pTab;
721   Vdbe *v;
722   int iDb;
723   int i;
724   int nAlloc;
725   sqlite3 *db = pParse->db;
726 
727   /* Look up the table being altered. */
728   assert( pParse->pNewTable==0 );
729   assert( sqlite3BtreeHoldsAllMutexes(db) );
730   if( db->mallocFailed ) goto exit_begin_add_column;
731   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
732   if( !pTab ) goto exit_begin_add_column;
733 
734 #ifndef SQLITE_OMIT_VIRTUALTABLE
735   if( IsVirtual(pTab) ){
736     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
737     goto exit_begin_add_column;
738   }
739 #endif
740 
741   /* Make sure this is not an attempt to ALTER a view. */
742   if( pTab->pSelect ){
743     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
744     goto exit_begin_add_column;
745   }
746 
747   assert( pTab->addColOffset>0 );
748   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
749 
750   /* Put a copy of the Table struct in Parse.pNewTable for the
751   ** sqlite3AddColumn() function and friends to modify.  But modify
752   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
753   ** prefix, we insure that the name will not collide with an existing
754   ** table because user table are not allowed to have the "sqlite_"
755   ** prefix on their name.
756   */
757   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
758   if( !pNew ) goto exit_begin_add_column;
759   pParse->pNewTable = pNew;
760   pNew->nRef = 1;
761   pNew->dbMem = pTab->dbMem;
762   pNew->nCol = pTab->nCol;
763   assert( pNew->nCol>0 );
764   nAlloc = (((pNew->nCol-1)/8)*8)+8;
765   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
766   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
767   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
768   if( !pNew->aCol || !pNew->zName ){
769     db->mallocFailed = 1;
770     goto exit_begin_add_column;
771   }
772   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
773   for(i=0; i<pNew->nCol; i++){
774     Column *pCol = &pNew->aCol[i];
775     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
776     pCol->zColl = 0;
777     pCol->zType = 0;
778     pCol->pDflt = 0;
779     pCol->zDflt = 0;
780   }
781   pNew->pSchema = db->aDb[iDb].pSchema;
782   pNew->addColOffset = pTab->addColOffset;
783   pNew->nRef = 1;
784 
785   /* Begin a transaction and increment the schema cookie.  */
786   sqlite3BeginWriteOperation(pParse, 0, iDb);
787   v = sqlite3GetVdbe(pParse);
788   if( !v ) goto exit_begin_add_column;
789   sqlite3ChangeCookie(pParse, iDb);
790 
791 exit_begin_add_column:
792   sqlite3SrcListDelete(db, pSrc);
793   return;
794 }
795 #endif  /* SQLITE_ALTER_TABLE */
796