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