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