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.61 2009/06/03 11:25:07 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 int isVirtualRename = 0; /* True if this is a v-table 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) && pTab->pMod->pModule->xRename ){ 336 isVirtualRename = 1; 337 } 338 #endif 339 340 /* Begin a transaction and code the VerifyCookie for database iDb. 341 ** Then modify the schema cookie (since the ALTER TABLE modifies the 342 ** schema). Open a statement transaction if the table is a virtual 343 ** table. 344 */ 345 v = sqlite3GetVdbe(pParse); 346 if( v==0 ){ 347 goto exit_rename_table; 348 } 349 sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb); 350 sqlite3ChangeCookie(pParse, iDb); 351 352 /* If this is a virtual table, invoke the xRename() function if 353 ** one is defined. The xRename() callback will modify the names 354 ** of any resources used by the v-table implementation (including other 355 ** SQLite tables) that are identified by the name of the virtual table. 356 */ 357 #ifndef SQLITE_OMIT_VIRTUALTABLE 358 if( isVirtualRename ){ 359 int i = ++pParse->nMem; 360 sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0); 361 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pTab->pVtab, P4_VTAB); 362 } 363 #endif 364 365 /* figure out how many UTF-8 characters are in zName */ 366 zTabName = pTab->zName; 367 nTabName = sqlite3Utf8CharLen(zTabName, -1); 368 369 /* Modify the sqlite_master table to use the new table name. */ 370 sqlite3NestedParse(pParse, 371 "UPDATE %Q.%s SET " 372 #ifdef SQLITE_OMIT_TRIGGER 373 "sql = sqlite_rename_table(sql, %Q), " 374 #else 375 "sql = CASE " 376 "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" 377 "ELSE sqlite_rename_table(sql, %Q) END, " 378 #endif 379 "tbl_name = %Q, " 380 "name = CASE " 381 "WHEN type='table' THEN %Q " 382 "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " 383 "'sqlite_autoindex_' || %Q || substr(name,%d+18) " 384 "ELSE name END " 385 "WHERE tbl_name=%Q AND " 386 "(type='table' OR type='index' OR type='trigger');", 387 zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 388 #ifndef SQLITE_OMIT_TRIGGER 389 zName, 390 #endif 391 zName, nTabName, zTabName 392 ); 393 394 #ifndef SQLITE_OMIT_AUTOINCREMENT 395 /* If the sqlite_sequence table exists in this database, then update 396 ** it with the new table name. 397 */ 398 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ 399 sqlite3NestedParse(pParse, 400 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", 401 zDb, zName, pTab->zName); 402 } 403 #endif 404 405 #ifndef SQLITE_OMIT_TRIGGER 406 /* If there are TEMP triggers on this table, modify the sqlite_temp_master 407 ** table. Don't do this if the table being ALTERed is itself located in 408 ** the temp database. 409 */ 410 if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){ 411 sqlite3NestedParse(pParse, 412 "UPDATE sqlite_temp_master SET " 413 "sql = sqlite_rename_trigger(sql, %Q), " 414 "tbl_name = %Q " 415 "WHERE %s;", zName, zName, zWhere); 416 sqlite3DbFree(db, zWhere); 417 } 418 #endif 419 420 /* Drop and reload the internal table schema. */ 421 reloadTableSchema(pParse, pTab, zName); 422 423 exit_rename_table: 424 sqlite3SrcListDelete(db, pSrc); 425 sqlite3DbFree(db, zName); 426 } 427 428 429 /* 430 ** Generate code to make sure the file format number is at least minFormat. 431 ** The generated code will increase the file format number if necessary. 432 */ 433 void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){ 434 Vdbe *v; 435 v = sqlite3GetVdbe(pParse); 436 /* The VDBE should have been allocated before this routine is called. 437 ** If that allocation failed, we would have quit before reaching this 438 ** point */ 439 if( ALWAYS(v) ){ 440 int r1 = sqlite3GetTempReg(pParse); 441 int r2 = sqlite3GetTempReg(pParse); 442 int j1; 443 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); 444 sqlite3VdbeUsesBtree(v, iDb); 445 sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2); 446 j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1); 447 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2); 448 sqlite3VdbeJumpHere(v, j1); 449 sqlite3ReleaseTempReg(pParse, r1); 450 sqlite3ReleaseTempReg(pParse, r2); 451 } 452 } 453 454 /* 455 ** This function is called after an "ALTER TABLE ... ADD" statement 456 ** has been parsed. Argument pColDef contains the text of the new 457 ** column definition. 458 ** 459 ** The Table structure pParse->pNewTable was extended to include 460 ** the new column during parsing. 461 */ 462 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ 463 Table *pNew; /* Copy of pParse->pNewTable */ 464 Table *pTab; /* Table being altered */ 465 int iDb; /* Database number */ 466 const char *zDb; /* Database name */ 467 const char *zTab; /* Table name */ 468 char *zCol; /* Null-terminated column definition */ 469 Column *pCol; /* The new column */ 470 Expr *pDflt; /* Default value for the new column */ 471 sqlite3 *db; /* The database connection; */ 472 473 db = pParse->db; 474 if( pParse->nErr || db->mallocFailed ) return; 475 pNew = pParse->pNewTable; 476 assert( pNew ); 477 478 assert( sqlite3BtreeHoldsAllMutexes(db) ); 479 iDb = sqlite3SchemaToIndex(db, pNew->pSchema); 480 zDb = db->aDb[iDb].zName; 481 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ 482 pCol = &pNew->aCol[pNew->nCol-1]; 483 pDflt = pCol->pDflt; 484 pTab = sqlite3FindTable(db, zTab, zDb); 485 assert( pTab ); 486 487 #ifndef SQLITE_OMIT_AUTHORIZATION 488 /* Invoke the authorization callback. */ 489 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 490 return; 491 } 492 #endif 493 494 /* If the default value for the new column was specified with a 495 ** literal NULL, then set pDflt to 0. This simplifies checking 496 ** for an SQL NULL default below. 497 */ 498 if( pDflt && pDflt->op==TK_NULL ){ 499 pDflt = 0; 500 } 501 502 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. 503 ** If there is a NOT NULL constraint, then the default value for the 504 ** column must not be NULL. 505 */ 506 if( pCol->isPrimKey ){ 507 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); 508 return; 509 } 510 if( pNew->pIndex ){ 511 sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column"); 512 return; 513 } 514 if( pCol->notNull && !pDflt ){ 515 sqlite3ErrorMsg(pParse, 516 "Cannot add a NOT NULL column with default value NULL"); 517 return; 518 } 519 520 /* Ensure the default expression is something that sqlite3ValueFromExpr() 521 ** can handle (i.e. not CURRENT_TIME etc.) 522 */ 523 if( pDflt ){ 524 sqlite3_value *pVal; 525 if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){ 526 db->mallocFailed = 1; 527 return; 528 } 529 if( !pVal ){ 530 sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default"); 531 return; 532 } 533 sqlite3ValueFree(pVal); 534 } 535 536 /* Modify the CREATE TABLE statement. */ 537 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); 538 if( zCol ){ 539 char *zEnd = &zCol[pColDef->n-1]; 540 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ 541 *zEnd-- = '\0'; 542 } 543 sqlite3NestedParse(pParse, 544 "UPDATE \"%w\".%s SET " 545 "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " 546 "WHERE type = 'table' AND name = %Q", 547 zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1, 548 zTab 549 ); 550 sqlite3DbFree(db, zCol); 551 } 552 553 /* If the default value of the new column is NULL, then set the file 554 ** format to 2. If the default value of the new column is not NULL, 555 ** the file format becomes 3. 556 */ 557 sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2); 558 559 /* Reload the schema of the modified table. */ 560 reloadTableSchema(pParse, pTab, pTab->zName); 561 } 562 563 /* 564 ** This function is called by the parser after the table-name in 565 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 566 ** pSrc is the full-name of the table being altered. 567 ** 568 ** This routine makes a (partial) copy of the Table structure 569 ** for the table being altered and sets Parse.pNewTable to point 570 ** to it. Routines called by the parser as the column definition 571 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 572 ** the copy. The copy of the Table structure is deleted by tokenize.c 573 ** after parsing is finished. 574 ** 575 ** Routine sqlite3AlterFinishAddColumn() will be called to complete 576 ** coding the "ALTER TABLE ... ADD" statement. 577 */ 578 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ 579 Table *pNew; 580 Table *pTab; 581 Vdbe *v; 582 int iDb; 583 int i; 584 int nAlloc; 585 sqlite3 *db = pParse->db; 586 587 /* Look up the table being altered. */ 588 assert( pParse->pNewTable==0 ); 589 assert( sqlite3BtreeHoldsAllMutexes(db) ); 590 if( db->mallocFailed ) goto exit_begin_add_column; 591 pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase); 592 if( !pTab ) goto exit_begin_add_column; 593 594 #ifndef SQLITE_OMIT_VIRTUALTABLE 595 if( IsVirtual(pTab) ){ 596 sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); 597 goto exit_begin_add_column; 598 } 599 #endif 600 601 /* Make sure this is not an attempt to ALTER a view. */ 602 if( pTab->pSelect ){ 603 sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); 604 goto exit_begin_add_column; 605 } 606 607 assert( pTab->addColOffset>0 ); 608 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 609 610 /* Put a copy of the Table struct in Parse.pNewTable for the 611 ** sqlite3AddColumn() function and friends to modify. But modify 612 ** the name by adding an "sqlite_altertab_" prefix. By adding this 613 ** prefix, we insure that the name will not collide with an existing 614 ** table because user table are not allowed to have the "sqlite_" 615 ** prefix on their name. 616 */ 617 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); 618 if( !pNew ) goto exit_begin_add_column; 619 pParse->pNewTable = pNew; 620 pNew->nRef = 1; 621 pNew->dbMem = pTab->dbMem; 622 pNew->nCol = pTab->nCol; 623 assert( pNew->nCol>0 ); 624 nAlloc = (((pNew->nCol-1)/8)*8)+8; 625 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); 626 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); 627 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); 628 if( !pNew->aCol || !pNew->zName ){ 629 db->mallocFailed = 1; 630 goto exit_begin_add_column; 631 } 632 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); 633 for(i=0; i<pNew->nCol; i++){ 634 Column *pCol = &pNew->aCol[i]; 635 pCol->zName = sqlite3DbStrDup(db, pCol->zName); 636 pCol->zColl = 0; 637 pCol->zType = 0; 638 pCol->pDflt = 0; 639 pCol->zDflt = 0; 640 } 641 pNew->pSchema = db->aDb[iDb].pSchema; 642 pNew->addColOffset = pTab->addColOffset; 643 pNew->nRef = 1; 644 645 /* Begin a transaction and increment the schema cookie. */ 646 sqlite3BeginWriteOperation(pParse, 0, iDb); 647 v = sqlite3GetVdbe(pParse); 648 if( !v ) goto exit_begin_add_column; 649 sqlite3ChangeCookie(pParse, iDb); 650 651 exit_begin_add_column: 652 sqlite3SrcListDelete(db, pSrc); 653 return; 654 } 655 #endif /* SQLITE_ALTER_TABLE */ 656