xref: /sqlite-3.40.0/src/alter.c (revision 5d00d0a8)
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 #ifndef SQLITE_OMIT_TRIGGER
89 /* This function is used by SQL generated to implement the
90 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
91 ** statement. The second is a table name. The table name in the CREATE
92 ** TRIGGER statement is replaced with the third argument and the result
93 ** returned. This is analagous to renameTableFunc() above, except for CREATE
94 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
95 */
96 static void renameTriggerFunc(
97   sqlite3_context *context,
98   int NotUsed,
99   sqlite3_value **argv
100 ){
101   unsigned char const *zSql = sqlite3_value_text(argv[0]);
102   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
103 
104   int token;
105   Token tname;
106   int dist = 3;
107   unsigned char const *zCsr = zSql;
108   int len = 0;
109   char *zRet;
110   sqlite3 *db = sqlite3_context_db_handle(context);
111 
112   UNUSED_PARAMETER(NotUsed);
113 
114   /* The principle used to locate the table name in the CREATE TRIGGER
115   ** statement is that the table name is the first token that is immediatedly
116   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
117   ** of TK_WHEN, TK_BEGIN or TK_FOR.
118   */
119   if( zSql ){
120     do {
121 
122       if( !*zCsr ){
123         /* Ran out of input before finding the table name. Return NULL. */
124         return;
125       }
126 
127       /* Store the token that zCsr points to in tname. */
128       tname.z = (char*)zCsr;
129       tname.n = len;
130 
131       /* Advance zCsr to the next token. Store that token type in 'token',
132       ** and its length in 'len' (to be used next iteration of this loop).
133       */
134       do {
135         zCsr += len;
136         len = sqlite3GetToken(zCsr, &token);
137       }while( token==TK_SPACE );
138       assert( len>0 );
139 
140       /* Variable 'dist' stores the number of tokens read since the most
141       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
142       ** token is read and 'dist' equals 2, the condition stated above
143       ** to be met.
144       **
145       ** Note that ON cannot be a database, table or column name, so
146       ** there is no need to worry about syntax like
147       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
148       */
149       dist++;
150       if( token==TK_DOT || token==TK_ON ){
151         dist = 0;
152       }
153     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
154 
155     /* Variable tname now contains the token that is the old table-name
156     ** in the CREATE TRIGGER statement.
157     */
158     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
159        zTableName, tname.z+tname.n);
160     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
161   }
162 }
163 #endif   /* !SQLITE_OMIT_TRIGGER */
164 
165 /*
166 ** Register built-in functions used to help implement ALTER TABLE
167 */
168 void sqlite3AlterFunctions(sqlite3 *db){
169   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
170                          renameTableFunc, 0, 0);
171 #ifndef SQLITE_OMIT_TRIGGER
172   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
173                          renameTriggerFunc, 0, 0);
174 #endif
175 }
176 
177 /*
178 ** Generate the text of a WHERE expression which can be used to select all
179 ** temporary triggers on table pTab from the sqlite_temp_master table. If
180 ** table pTab has no temporary triggers, or is itself stored in the
181 ** temporary database, NULL is returned.
182 */
183 static char *whereTempTriggers(Parse *pParse, Table *pTab){
184   Trigger *pTrig;
185   char *zWhere = 0;
186   char *tmp = 0;
187   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
188 
189   /* If the table is not located in the temp-db (in which case NULL is
190   ** returned, loop through the tables list of triggers. For each trigger
191   ** that is not part of the temp-db schema, add a clause to the WHERE
192   ** expression being built up in zWhere.
193   */
194   if( pTab->pSchema!=pTempSchema ){
195     sqlite3 *db = pParse->db;
196     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
197       if( pTrig->pSchema==pTempSchema ){
198         if( !zWhere ){
199           zWhere = sqlite3MPrintf(db, "name=%Q", pTrig->name);
200         }else{
201           tmp = zWhere;
202           zWhere = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, pTrig->name);
203           sqlite3DbFree(db, tmp);
204         }
205       }
206     }
207   }
208   return zWhere;
209 }
210 
211 /*
212 ** Generate code to drop and reload the internal representation of table
213 ** pTab from the database, including triggers and temporary triggers.
214 ** Argument zName is the name of the table in the database schema at
215 ** the time the generated code is executed. This can be different from
216 ** pTab->zName if this function is being called to code part of an
217 ** "ALTER TABLE RENAME TO" statement.
218 */
219 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
220   Vdbe *v;
221   char *zWhere;
222   int iDb;                   /* Index of database containing pTab */
223 #ifndef SQLITE_OMIT_TRIGGER
224   Trigger *pTrig;
225 #endif
226 
227   v = sqlite3GetVdbe(pParse);
228   if( NEVER(v==0) ) return;
229   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
230   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
231   assert( iDb>=0 );
232 
233 #ifndef SQLITE_OMIT_TRIGGER
234   /* Drop any table triggers from the internal schema. */
235   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
236     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
237     assert( iTrigDb==iDb || iTrigDb==1 );
238     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->name, 0);
239   }
240 #endif
241 
242   /* Drop the table and index from the internal schema */
243   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
244 
245   /* Reload the table, index and permanent trigger schemas. */
246   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
247   if( !zWhere ) return;
248   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
249 
250 #ifndef SQLITE_OMIT_TRIGGER
251   /* Now, if the table is not stored in the temp database, reload any temp
252   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
253   */
254   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
255     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
256   }
257 #endif
258 }
259 
260 /*
261 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
262 ** command.
263 */
264 void sqlite3AlterRenameTable(
265   Parse *pParse,            /* Parser context. */
266   SrcList *pSrc,            /* The table to rename. */
267   Token *pName              /* The new table name. */
268 ){
269   int iDb;                  /* Database that contains the table */
270   char *zDb;                /* Name of database iDb */
271   Table *pTab;              /* Table being renamed */
272   char *zName = 0;          /* NULL-terminated version of pName */
273   sqlite3 *db = pParse->db; /* Database connection */
274   int nTabName;             /* Number of UTF-8 characters in zTabName */
275   const char *zTabName;     /* Original name of the table */
276   Vdbe *v;
277 #ifndef SQLITE_OMIT_TRIGGER
278   char *zWhere = 0;         /* Where clause to locate temp triggers */
279 #endif
280   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
281 
282   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
283   assert( pSrc->nSrc==1 );
284   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
285 
286   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
287   if( !pTab ) goto exit_rename_table;
288   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
289   zDb = db->aDb[iDb].zName;
290 
291   /* Get a NULL terminated version of the new table name. */
292   zName = sqlite3NameFromToken(db, pName);
293   if( !zName ) goto exit_rename_table;
294 
295   /* Check that a table or index named 'zName' does not already exist
296   ** in database iDb. If so, this is an error.
297   */
298   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
299     sqlite3ErrorMsg(pParse,
300         "there is already another table or index with this name: %s", zName);
301     goto exit_rename_table;
302   }
303 
304   /* Make sure it is not a system table being altered, or a reserved name
305   ** that the table is being renamed to.
306   */
307   if( sqlite3Strlen30(pTab->zName)>6
308    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
309   ){
310     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
311     goto exit_rename_table;
312   }
313   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
314     goto exit_rename_table;
315   }
316 
317 #ifndef SQLITE_OMIT_VIEW
318   if( pTab->pSelect ){
319     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
320     goto exit_rename_table;
321   }
322 #endif
323 
324 #ifndef SQLITE_OMIT_AUTHORIZATION
325   /* Invoke the authorization callback. */
326   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
327     goto exit_rename_table;
328   }
329 #endif
330 
331 #ifndef SQLITE_OMIT_VIRTUALTABLE
332   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
333     goto exit_rename_table;
334   }
335   if( IsVirtual(pTab) ){
336     pVTab = sqlite3GetVTable(db, pTab);
337     if( pVTab->pVtab->pModule->xRename==0 ){
338       pVTab = 0;
339     }
340   }
341 #endif
342 
343   /* Begin a transaction and code the VerifyCookie for database iDb.
344   ** Then modify the schema cookie (since the ALTER TABLE modifies the
345   ** schema). Open a statement transaction if the table is a virtual
346   ** table.
347   */
348   v = sqlite3GetVdbe(pParse);
349   if( v==0 ){
350     goto exit_rename_table;
351   }
352   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
353   sqlite3ChangeCookie(pParse, iDb);
354 
355   /* If this is a virtual table, invoke the xRename() function if
356   ** one is defined. The xRename() callback will modify the names
357   ** of any resources used by the v-table implementation (including other
358   ** SQLite tables) that are identified by the name of the virtual table.
359   */
360 #ifndef SQLITE_OMIT_VIRTUALTABLE
361   if( pVTab ){
362     int i = ++pParse->nMem;
363     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
364     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
365   }
366 #endif
367 
368   /* figure out how many UTF-8 characters are in zName */
369   zTabName = pTab->zName;
370   nTabName = sqlite3Utf8CharLen(zTabName, -1);
371 
372   /* Modify the sqlite_master table to use the new table name. */
373   sqlite3NestedParse(pParse,
374       "UPDATE %Q.%s SET "
375 #ifdef SQLITE_OMIT_TRIGGER
376           "sql = sqlite_rename_table(sql, %Q), "
377 #else
378           "sql = CASE "
379             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
380             "ELSE sqlite_rename_table(sql, %Q) END, "
381 #endif
382           "tbl_name = %Q, "
383           "name = CASE "
384             "WHEN type='table' THEN %Q "
385             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
386              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
387             "ELSE name END "
388       "WHERE tbl_name=%Q AND "
389           "(type='table' OR type='index' OR type='trigger');",
390       zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
391 #ifndef SQLITE_OMIT_TRIGGER
392       zName,
393 #endif
394       zName, nTabName, zTabName
395   );
396 
397 #ifndef SQLITE_OMIT_AUTOINCREMENT
398   /* If the sqlite_sequence table exists in this database, then update
399   ** it with the new table name.
400   */
401   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
402     sqlite3NestedParse(pParse,
403         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
404         zDb, zName, pTab->zName);
405   }
406 #endif
407 
408 #ifndef SQLITE_OMIT_TRIGGER
409   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
410   ** table. Don't do this if the table being ALTERed is itself located in
411   ** the temp database.
412   */
413   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
414     sqlite3NestedParse(pParse,
415         "UPDATE sqlite_temp_master SET "
416             "sql = sqlite_rename_trigger(sql, %Q), "
417             "tbl_name = %Q "
418             "WHERE %s;", zName, zName, zWhere);
419     sqlite3DbFree(db, zWhere);
420   }
421 #endif
422 
423   /* Drop and reload the internal table schema. */
424   reloadTableSchema(pParse, pTab, zName);
425 
426 exit_rename_table:
427   sqlite3SrcListDelete(db, pSrc);
428   sqlite3DbFree(db, zName);
429 }
430 
431 
432 /*
433 ** Generate code to make sure the file format number is at least minFormat.
434 ** The generated code will increase the file format number if necessary.
435 */
436 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
437   Vdbe *v;
438   v = sqlite3GetVdbe(pParse);
439   /* The VDBE should have been allocated before this routine is called.
440   ** If that allocation failed, we would have quit before reaching this
441   ** point */
442   if( ALWAYS(v) ){
443     int r1 = sqlite3GetTempReg(pParse);
444     int r2 = sqlite3GetTempReg(pParse);
445     int j1;
446     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
447     sqlite3VdbeUsesBtree(v, iDb);
448     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
449     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
450     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
451     sqlite3VdbeJumpHere(v, j1);
452     sqlite3ReleaseTempReg(pParse, r1);
453     sqlite3ReleaseTempReg(pParse, r2);
454   }
455 }
456 
457 /*
458 ** This function is called after an "ALTER TABLE ... ADD" statement
459 ** has been parsed. Argument pColDef contains the text of the new
460 ** column definition.
461 **
462 ** The Table structure pParse->pNewTable was extended to include
463 ** the new column during parsing.
464 */
465 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
466   Table *pNew;              /* Copy of pParse->pNewTable */
467   Table *pTab;              /* Table being altered */
468   int iDb;                  /* Database number */
469   const char *zDb;          /* Database name */
470   const char *zTab;         /* Table name */
471   char *zCol;               /* Null-terminated column definition */
472   Column *pCol;             /* The new column */
473   Expr *pDflt;              /* Default value for the new column */
474   sqlite3 *db;              /* The database connection; */
475 
476   db = pParse->db;
477   if( pParse->nErr || db->mallocFailed ) return;
478   pNew = pParse->pNewTable;
479   assert( pNew );
480 
481   assert( sqlite3BtreeHoldsAllMutexes(db) );
482   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
483   zDb = db->aDb[iDb].zName;
484   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
485   pCol = &pNew->aCol[pNew->nCol-1];
486   pDflt = pCol->pDflt;
487   pTab = sqlite3FindTable(db, zTab, zDb);
488   assert( pTab );
489 
490 #ifndef SQLITE_OMIT_AUTHORIZATION
491   /* Invoke the authorization callback. */
492   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
493     return;
494   }
495 #endif
496 
497   /* If the default value for the new column was specified with a
498   ** literal NULL, then set pDflt to 0. This simplifies checking
499   ** for an SQL NULL default below.
500   */
501   if( pDflt && pDflt->op==TK_NULL ){
502     pDflt = 0;
503   }
504 
505   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
506   ** If there is a NOT NULL constraint, then the default value for the
507   ** column must not be NULL.
508   */
509   if( pCol->isPrimKey ){
510     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
511     return;
512   }
513   if( pNew->pIndex ){
514     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
515     return;
516   }
517   if( pCol->notNull && !pDflt ){
518     sqlite3ErrorMsg(pParse,
519         "Cannot add a NOT NULL column with default value NULL");
520     return;
521   }
522 
523   /* Ensure the default expression is something that sqlite3ValueFromExpr()
524   ** can handle (i.e. not CURRENT_TIME etc.)
525   */
526   if( pDflt ){
527     sqlite3_value *pVal;
528     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
529       db->mallocFailed = 1;
530       return;
531     }
532     if( !pVal ){
533       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
534       return;
535     }
536     sqlite3ValueFree(pVal);
537   }
538 
539   /* Modify the CREATE TABLE statement. */
540   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
541   if( zCol ){
542     char *zEnd = &zCol[pColDef->n-1];
543     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
544       *zEnd-- = '\0';
545     }
546     sqlite3NestedParse(pParse,
547         "UPDATE \"%w\".%s SET "
548           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
549         "WHERE type = 'table' AND name = %Q",
550       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
551       zTab
552     );
553     sqlite3DbFree(db, zCol);
554   }
555 
556   /* If the default value of the new column is NULL, then set the file
557   ** format to 2. If the default value of the new column is not NULL,
558   ** the file format becomes 3.
559   */
560   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
561 
562   /* Reload the schema of the modified table. */
563   reloadTableSchema(pParse, pTab, pTab->zName);
564 }
565 
566 /*
567 ** This function is called by the parser after the table-name in
568 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
569 ** pSrc is the full-name of the table being altered.
570 **
571 ** This routine makes a (partial) copy of the Table structure
572 ** for the table being altered and sets Parse.pNewTable to point
573 ** to it. Routines called by the parser as the column definition
574 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
575 ** the copy. The copy of the Table structure is deleted by tokenize.c
576 ** after parsing is finished.
577 **
578 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
579 ** coding the "ALTER TABLE ... ADD" statement.
580 */
581 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
582   Table *pNew;
583   Table *pTab;
584   Vdbe *v;
585   int iDb;
586   int i;
587   int nAlloc;
588   sqlite3 *db = pParse->db;
589 
590   /* Look up the table being altered. */
591   assert( pParse->pNewTable==0 );
592   assert( sqlite3BtreeHoldsAllMutexes(db) );
593   if( db->mallocFailed ) goto exit_begin_add_column;
594   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
595   if( !pTab ) goto exit_begin_add_column;
596 
597 #ifndef SQLITE_OMIT_VIRTUALTABLE
598   if( IsVirtual(pTab) ){
599     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
600     goto exit_begin_add_column;
601   }
602 #endif
603 
604   /* Make sure this is not an attempt to ALTER a view. */
605   if( pTab->pSelect ){
606     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
607     goto exit_begin_add_column;
608   }
609 
610   assert( pTab->addColOffset>0 );
611   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
612 
613   /* Put a copy of the Table struct in Parse.pNewTable for the
614   ** sqlite3AddColumn() function and friends to modify.  But modify
615   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
616   ** prefix, we insure that the name will not collide with an existing
617   ** table because user table are not allowed to have the "sqlite_"
618   ** prefix on their name.
619   */
620   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
621   if( !pNew ) goto exit_begin_add_column;
622   pParse->pNewTable = pNew;
623   pNew->nRef = 1;
624   pNew->dbMem = pTab->dbMem;
625   pNew->nCol = pTab->nCol;
626   assert( pNew->nCol>0 );
627   nAlloc = (((pNew->nCol-1)/8)*8)+8;
628   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
629   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
630   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
631   if( !pNew->aCol || !pNew->zName ){
632     db->mallocFailed = 1;
633     goto exit_begin_add_column;
634   }
635   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
636   for(i=0; i<pNew->nCol; i++){
637     Column *pCol = &pNew->aCol[i];
638     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
639     pCol->zColl = 0;
640     pCol->zType = 0;
641     pCol->pDflt = 0;
642     pCol->zDflt = 0;
643   }
644   pNew->pSchema = db->aDb[iDb].pSchema;
645   pNew->addColOffset = pTab->addColOffset;
646   pNew->nRef = 1;
647 
648   /* Begin a transaction and increment the schema cookie.  */
649   sqlite3BeginWriteOperation(pParse, 0, iDb);
650   v = sqlite3GetVdbe(pParse);
651   if( !v ) goto exit_begin_add_column;
652   sqlite3ChangeCookie(pParse, iDb);
653 
654 exit_begin_add_column:
655   sqlite3SrcListDelete(db, pSrc);
656   return;
657 }
658 #endif  /* SQLITE_ALTER_TABLE */
659