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