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