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 ** Parameter zName is the name of a table that is about to be altered 25 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN). 26 ** If the table is a system table, this function leaves an error message 27 ** in pParse->zErr (system tables may not be altered) and returns non-zero. 28 ** 29 ** Or, if zName is not a system table, zero is returned. 30 */ 31 static int isAlterableTable(Parse *pParse, Table *pTab){ 32 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) 33 #ifndef SQLITE_OMIT_VIRTUALTABLE 34 || ( (pTab->tabFlags & TF_Shadow)!=0 35 && sqlite3ReadOnlyShadowTables(pParse->db) 36 ) 37 #endif 38 ){ 39 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName); 40 return 1; 41 } 42 return 0; 43 } 44 45 /* 46 ** Generate code to verify that the schemas of database zDb and, if 47 ** bTemp is not true, database "temp", can still be parsed. This is 48 ** called at the end of the generation of an ALTER TABLE ... RENAME ... 49 ** statement to ensure that the operation has not rendered any schema 50 ** objects unusable. 51 */ 52 static void renameTestSchema( 53 Parse *pParse, /* Parse context */ 54 const char *zDb, /* Name of db to verify schema of */ 55 int bTemp, /* True if this is the temp db */ 56 const char *zWhen /* "when" part of error message */ 57 ){ 58 pParse->colNamesSet = 1; 59 sqlite3NestedParse(pParse, 60 "SELECT 1 " 61 "FROM \"%w\"." DFLT_SCHEMA_TABLE " " 62 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 63 " AND sql NOT LIKE 'create virtual%%'" 64 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q)=NULL ", 65 zDb, 66 zDb, bTemp, zWhen 67 ); 68 69 if( bTemp==0 ){ 70 sqlite3NestedParse(pParse, 71 "SELECT 1 " 72 "FROM temp." DFLT_SCHEMA_TABLE " " 73 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 74 " AND sql NOT LIKE 'create virtual%%'" 75 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q)=NULL ", 76 zDb, zWhen 77 ); 78 } 79 } 80 81 /* 82 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for 83 ** the temp database as well. 84 */ 85 static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){ 86 Vdbe *v = pParse->pVdbe; 87 if( v ){ 88 sqlite3ChangeCookie(pParse, iDb); 89 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5); 90 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5); 91 } 92 } 93 94 /* 95 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 96 ** command. 97 */ 98 void sqlite3AlterRenameTable( 99 Parse *pParse, /* Parser context. */ 100 SrcList *pSrc, /* The table to rename. */ 101 Token *pName /* The new table name. */ 102 ){ 103 int iDb; /* Database that contains the table */ 104 char *zDb; /* Name of database iDb */ 105 Table *pTab; /* Table being renamed */ 106 char *zName = 0; /* NULL-terminated version of pName */ 107 sqlite3 *db = pParse->db; /* Database connection */ 108 int nTabName; /* Number of UTF-8 characters in zTabName */ 109 const char *zTabName; /* Original name of the table */ 110 Vdbe *v; 111 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ 112 u32 savedDbFlags; /* Saved value of db->mDbFlags */ 113 114 savedDbFlags = db->mDbFlags; 115 if( NEVER(db->mallocFailed) ) goto exit_rename_table; 116 assert( pSrc->nSrc==1 ); 117 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); 118 119 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 120 if( !pTab ) goto exit_rename_table; 121 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 122 zDb = db->aDb[iDb].zDbSName; 123 db->mDbFlags |= DBFLAG_PreferBuiltin; 124 125 /* Get a NULL terminated version of the new table name. */ 126 zName = sqlite3NameFromToken(db, pName); 127 if( !zName ) goto exit_rename_table; 128 129 /* Check that a table or index named 'zName' does not already exist 130 ** in database iDb. If so, this is an error. 131 */ 132 if( sqlite3FindTable(db, zName, zDb) 133 || sqlite3FindIndex(db, zName, zDb) 134 || sqlite3IsShadowTableOf(db, pTab, zName) 135 ){ 136 sqlite3ErrorMsg(pParse, 137 "there is already another table or index with this name: %s", zName); 138 goto exit_rename_table; 139 } 140 141 /* Make sure it is not a system table being altered, or a reserved name 142 ** that the table is being renamed to. 143 */ 144 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ 145 goto exit_rename_table; 146 } 147 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName) ){ 148 goto exit_rename_table; 149 } 150 151 #ifndef SQLITE_OMIT_VIEW 152 if( pTab->pSelect ){ 153 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); 154 goto exit_rename_table; 155 } 156 #endif 157 158 #ifndef SQLITE_OMIT_AUTHORIZATION 159 /* Invoke the authorization callback. */ 160 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 161 goto exit_rename_table; 162 } 163 #endif 164 165 #ifndef SQLITE_OMIT_VIRTUALTABLE 166 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 167 goto exit_rename_table; 168 } 169 if( IsVirtual(pTab) ){ 170 pVTab = sqlite3GetVTable(db, pTab); 171 if( pVTab->pVtab->pModule->xRename==0 ){ 172 pVTab = 0; 173 } 174 } 175 #endif 176 177 /* Begin a transaction for database iDb. Then modify the schema cookie 178 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(), 179 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the 180 ** nested SQL may raise an exception. */ 181 v = sqlite3GetVdbe(pParse); 182 if( v==0 ){ 183 goto exit_rename_table; 184 } 185 sqlite3MayAbort(pParse); 186 187 /* figure out how many UTF-8 characters are in zName */ 188 zTabName = pTab->zName; 189 nTabName = sqlite3Utf8CharLen(zTabName, -1); 190 191 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in 192 ** the schema to use the new table name. */ 193 sqlite3NestedParse(pParse, 194 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " 195 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) " 196 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase)" 197 "AND name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 198 , zDb, zDb, zTabName, zName, (iDb==1), zTabName 199 ); 200 201 /* Update the tbl_name and name columns of the sqlite_schema table 202 ** as required. */ 203 sqlite3NestedParse(pParse, 204 "UPDATE %Q." DFLT_SCHEMA_TABLE " SET " 205 "tbl_name = %Q, " 206 "name = CASE " 207 "WHEN type='table' THEN %Q " 208 "WHEN name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' " 209 " AND type='index' THEN " 210 "'sqlite_autoindex_' || %Q || substr(name,%d+18) " 211 "ELSE name END " 212 "WHERE tbl_name=%Q COLLATE nocase AND " 213 "(type='table' OR type='index' OR type='trigger');", 214 zDb, 215 zName, zName, zName, 216 nTabName, zTabName 217 ); 218 219 #ifndef SQLITE_OMIT_AUTOINCREMENT 220 /* If the sqlite_sequence table exists in this database, then update 221 ** it with the new table name. 222 */ 223 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ 224 sqlite3NestedParse(pParse, 225 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", 226 zDb, zName, pTab->zName); 227 } 228 #endif 229 230 /* If the table being renamed is not itself part of the temp database, 231 ** edit view and trigger definitions within the temp database 232 ** as required. */ 233 if( iDb!=1 ){ 234 sqlite3NestedParse(pParse, 235 "UPDATE sqlite_temp_schema SET " 236 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), " 237 "tbl_name = " 238 "CASE WHEN tbl_name=%Q COLLATE nocase AND " 239 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename') " 240 "THEN %Q ELSE tbl_name END " 241 "WHERE type IN ('view', 'trigger')" 242 , zDb, zTabName, zName, zTabName, zDb, zName); 243 } 244 245 /* If this is a virtual table, invoke the xRename() function if 246 ** one is defined. The xRename() callback will modify the names 247 ** of any resources used by the v-table implementation (including other 248 ** SQLite tables) that are identified by the name of the virtual table. 249 */ 250 #ifndef SQLITE_OMIT_VIRTUALTABLE 251 if( pVTab ){ 252 int i = ++pParse->nMem; 253 sqlite3VdbeLoadString(v, i, zName); 254 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); 255 } 256 #endif 257 258 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename); 259 renameTestSchema(pParse, zDb, iDb==1, "after rename"); 260 261 exit_rename_table: 262 sqlite3SrcListDelete(db, pSrc); 263 sqlite3DbFree(db, zName); 264 db->mDbFlags = savedDbFlags; 265 } 266 267 /* 268 ** Write code that will raise an error if the table described by 269 ** zDb and zTab is not empty. 270 */ 271 static void sqlite3ErrorIfNotEmpty( 272 Parse *pParse, /* Parsing context */ 273 const char *zDb, /* Schema holding the table */ 274 const char *zTab, /* Table to check for empty */ 275 const char *zErr /* Error message text */ 276 ){ 277 sqlite3NestedParse(pParse, 278 "SELECT raise(ABORT,%Q) FROM \"%w\".\"%w\"", 279 zErr, zDb, zTab 280 ); 281 } 282 283 /* 284 ** This function is called after an "ALTER TABLE ... ADD" statement 285 ** has been parsed. Argument pColDef contains the text of the new 286 ** column definition. 287 ** 288 ** The Table structure pParse->pNewTable was extended to include 289 ** the new column during parsing. 290 */ 291 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ 292 Table *pNew; /* Copy of pParse->pNewTable */ 293 Table *pTab; /* Table being altered */ 294 int iDb; /* Database number */ 295 const char *zDb; /* Database name */ 296 const char *zTab; /* Table name */ 297 char *zCol; /* Null-terminated column definition */ 298 Column *pCol; /* The new column */ 299 Expr *pDflt; /* Default value for the new column */ 300 sqlite3 *db; /* The database connection; */ 301 Vdbe *v; /* The prepared statement under construction */ 302 int r1; /* Temporary registers */ 303 304 db = pParse->db; 305 if( pParse->nErr || db->mallocFailed ) return; 306 pNew = pParse->pNewTable; 307 assert( pNew ); 308 309 assert( sqlite3BtreeHoldsAllMutexes(db) ); 310 iDb = sqlite3SchemaToIndex(db, pNew->pSchema); 311 zDb = db->aDb[iDb].zDbSName; 312 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ 313 pCol = &pNew->aCol[pNew->nCol-1]; 314 pDflt = pCol->pDflt; 315 pTab = sqlite3FindTable(db, zTab, zDb); 316 assert( pTab ); 317 318 #ifndef SQLITE_OMIT_AUTHORIZATION 319 /* Invoke the authorization callback. */ 320 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 321 return; 322 } 323 #endif 324 325 326 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE. 327 ** If there is a NOT NULL constraint, then the default value for the 328 ** column must not be NULL. 329 */ 330 if( pCol->colFlags & COLFLAG_PRIMKEY ){ 331 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); 332 return; 333 } 334 if( pNew->pIndex ){ 335 sqlite3ErrorMsg(pParse, 336 "Cannot add a UNIQUE column"); 337 return; 338 } 339 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){ 340 /* If the default value for the new column was specified with a 341 ** literal NULL, then set pDflt to 0. This simplifies checking 342 ** for an SQL NULL default below. 343 */ 344 assert( pDflt==0 || pDflt->op==TK_SPAN ); 345 if( pDflt && pDflt->pLeft->op==TK_NULL ){ 346 pDflt = 0; 347 } 348 if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){ 349 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 350 "Cannot add a REFERENCES column with non-NULL default value"); 351 } 352 if( pCol->notNull && !pDflt ){ 353 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 354 "Cannot add a NOT NULL column with default value NULL"); 355 } 356 357 358 /* Ensure the default expression is something that sqlite3ValueFromExpr() 359 ** can handle (i.e. not CURRENT_TIME etc.) 360 */ 361 if( pDflt ){ 362 sqlite3_value *pVal = 0; 363 int rc; 364 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); 365 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); 366 if( rc!=SQLITE_OK ){ 367 assert( db->mallocFailed == 1 ); 368 return; 369 } 370 if( !pVal ){ 371 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 372 "Cannot add a column with non-constant default"); 373 } 374 sqlite3ValueFree(pVal); 375 } 376 }else if( pCol->colFlags & COLFLAG_STORED ){ 377 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column"); 378 } 379 380 381 /* Modify the CREATE TABLE statement. */ 382 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n); 383 if( zCol ){ 384 char *zEnd = &zCol[pColDef->n-1]; 385 u32 savedDbFlags = db->mDbFlags; 386 while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){ 387 *zEnd-- = '\0'; 388 } 389 db->mDbFlags |= DBFLAG_PreferBuiltin; 390 /* substr() operations on characters, but addColOffset is in bytes. So we 391 ** have to use printf() to translate between these units: */ 392 sqlite3NestedParse(pParse, 393 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " 394 "sql = printf('%%.%ds, ',sql) || %Q" 395 " || substr(sql,1+length(printf('%%.%ds',sql))) " 396 "WHERE type = 'table' AND name = %Q", 397 zDb, pNew->addColOffset, zCol, pNew->addColOffset, 398 zTab 399 ); 400 sqlite3DbFree(db, zCol); 401 db->mDbFlags = savedDbFlags; 402 } 403 404 /* Make sure the schema version is at least 3. But do not upgrade 405 ** from less than 3 to 4, as that will corrupt any preexisting DESC 406 ** index. 407 */ 408 v = sqlite3GetVdbe(pParse); 409 if( v ){ 410 r1 = sqlite3GetTempReg(pParse); 411 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); 412 sqlite3VdbeUsesBtree(v, iDb); 413 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); 414 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); 415 VdbeCoverage(v); 416 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); 417 sqlite3ReleaseTempReg(pParse, r1); 418 } 419 420 /* Reload the table definition */ 421 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename); 422 } 423 424 /* 425 ** This function is called by the parser after the table-name in 426 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 427 ** pSrc is the full-name of the table being altered. 428 ** 429 ** This routine makes a (partial) copy of the Table structure 430 ** for the table being altered and sets Parse.pNewTable to point 431 ** to it. Routines called by the parser as the column definition 432 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 433 ** the copy. The copy of the Table structure is deleted by tokenize.c 434 ** after parsing is finished. 435 ** 436 ** Routine sqlite3AlterFinishAddColumn() will be called to complete 437 ** coding the "ALTER TABLE ... ADD" statement. 438 */ 439 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ 440 Table *pNew; 441 Table *pTab; 442 int iDb; 443 int i; 444 int nAlloc; 445 sqlite3 *db = pParse->db; 446 447 /* Look up the table being altered. */ 448 assert( pParse->pNewTable==0 ); 449 assert( sqlite3BtreeHoldsAllMutexes(db) ); 450 if( db->mallocFailed ) goto exit_begin_add_column; 451 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 452 if( !pTab ) goto exit_begin_add_column; 453 454 #ifndef SQLITE_OMIT_VIRTUALTABLE 455 if( IsVirtual(pTab) ){ 456 sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); 457 goto exit_begin_add_column; 458 } 459 #endif 460 461 /* Make sure this is not an attempt to ALTER a view. */ 462 if( pTab->pSelect ){ 463 sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); 464 goto exit_begin_add_column; 465 } 466 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ 467 goto exit_begin_add_column; 468 } 469 470 sqlite3MayAbort(pParse); 471 assert( pTab->addColOffset>0 ); 472 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 473 474 /* Put a copy of the Table struct in Parse.pNewTable for the 475 ** sqlite3AddColumn() function and friends to modify. But modify 476 ** the name by adding an "sqlite_altertab_" prefix. By adding this 477 ** prefix, we insure that the name will not collide with an existing 478 ** table because user table are not allowed to have the "sqlite_" 479 ** prefix on their name. 480 */ 481 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); 482 if( !pNew ) goto exit_begin_add_column; 483 pParse->pNewTable = pNew; 484 pNew->nTabRef = 1; 485 pNew->nCol = pTab->nCol; 486 assert( pNew->nCol>0 ); 487 nAlloc = (((pNew->nCol-1)/8)*8)+8; 488 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); 489 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc); 490 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); 491 if( !pNew->aCol || !pNew->zName ){ 492 assert( db->mallocFailed ); 493 goto exit_begin_add_column; 494 } 495 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol); 496 for(i=0; i<pNew->nCol; i++){ 497 Column *pCol = &pNew->aCol[i]; 498 pCol->zName = sqlite3DbStrDup(db, pCol->zName); 499 pCol->hName = sqlite3StrIHash(pCol->zName); 500 pCol->zColl = 0; 501 pCol->pDflt = 0; 502 } 503 pNew->pSchema = db->aDb[iDb].pSchema; 504 pNew->addColOffset = pTab->addColOffset; 505 pNew->nTabRef = 1; 506 507 exit_begin_add_column: 508 sqlite3SrcListDelete(db, pSrc); 509 return; 510 } 511 512 /* 513 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN 514 ** command. This function checks if the table is a view or virtual 515 ** table (columns of views or virtual tables may not be renamed). If so, 516 ** it loads an error message into pParse and returns non-zero. 517 ** 518 ** Or, if pTab is not a view or virtual table, zero is returned. 519 */ 520 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 521 static int isRealTable(Parse *pParse, Table *pTab, int bDrop){ 522 const char *zType = 0; 523 #ifndef SQLITE_OMIT_VIEW 524 if( pTab->pSelect ){ 525 zType = "view"; 526 } 527 #endif 528 #ifndef SQLITE_OMIT_VIRTUALTABLE 529 if( IsVirtual(pTab) ){ 530 zType = "virtual table"; 531 } 532 #endif 533 if( zType ){ 534 sqlite3ErrorMsg(pParse, "cannot %s %s \"%s\"", 535 (bDrop ? "drop column from" : "rename columns of"), 536 zType, pTab->zName 537 ); 538 return 1; 539 } 540 return 0; 541 } 542 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 543 # define isRealTable(x,y,z) (0) 544 #endif 545 546 /* 547 ** Handles the following parser reduction: 548 ** 549 ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew 550 */ 551 void sqlite3AlterRenameColumn( 552 Parse *pParse, /* Parsing context */ 553 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */ 554 Token *pOld, /* Name of column being changed */ 555 Token *pNew /* New column name */ 556 ){ 557 sqlite3 *db = pParse->db; /* Database connection */ 558 Table *pTab; /* Table being updated */ 559 int iCol; /* Index of column being renamed */ 560 char *zOld = 0; /* Old column name */ 561 char *zNew = 0; /* New column name */ 562 const char *zDb; /* Name of schema containing the table */ 563 int iSchema; /* Index of the schema */ 564 int bQuote; /* True to quote the new name */ 565 566 /* Locate the table to be altered */ 567 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 568 if( !pTab ) goto exit_rename_column; 569 570 /* Cannot alter a system table */ 571 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column; 572 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column; 573 574 /* Which schema holds the table to be altered */ 575 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema); 576 assert( iSchema>=0 ); 577 zDb = db->aDb[iSchema].zDbSName; 578 579 #ifndef SQLITE_OMIT_AUTHORIZATION 580 /* Invoke the authorization callback. */ 581 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 582 goto exit_rename_column; 583 } 584 #endif 585 586 /* Make sure the old name really is a column name in the table to be 587 ** altered. Set iCol to be the index of the column being renamed */ 588 zOld = sqlite3NameFromToken(db, pOld); 589 if( !zOld ) goto exit_rename_column; 590 for(iCol=0; iCol<pTab->nCol; iCol++){ 591 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zName, zOld) ) break; 592 } 593 if( iCol==pTab->nCol ){ 594 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zOld); 595 goto exit_rename_column; 596 } 597 598 /* Do the rename operation using a recursive UPDATE statement that 599 ** uses the sqlite_rename_column() SQL function to compute the new 600 ** CREATE statement text for the sqlite_schema table. 601 */ 602 sqlite3MayAbort(pParse); 603 zNew = sqlite3NameFromToken(db, pNew); 604 if( !zNew ) goto exit_rename_column; 605 assert( pNew->n>0 ); 606 bQuote = sqlite3Isquote(pNew->z[0]); 607 sqlite3NestedParse(pParse, 608 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " 609 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) " 610 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' " 611 " AND (type != 'index' OR tbl_name = %Q)" 612 " AND sql NOT LIKE 'create virtual%%'", 613 zDb, 614 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1, 615 pTab->zName 616 ); 617 618 sqlite3NestedParse(pParse, 619 "UPDATE temp." DFLT_SCHEMA_TABLE " SET " 620 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) " 621 "WHERE type IN ('trigger', 'view')", 622 zDb, pTab->zName, iCol, zNew, bQuote 623 ); 624 625 /* Drop and reload the database schema. */ 626 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename); 627 renameTestSchema(pParse, zDb, iSchema==1, "after rename"); 628 629 exit_rename_column: 630 sqlite3SrcListDelete(db, pSrc); 631 sqlite3DbFree(db, zOld); 632 sqlite3DbFree(db, zNew); 633 return; 634 } 635 636 /* 637 ** Each RenameToken object maps an element of the parse tree into 638 ** the token that generated that element. The parse tree element 639 ** might be one of: 640 ** 641 ** * A pointer to an Expr that represents an ID 642 ** * The name of a table column in Column.zName 643 ** 644 ** A list of RenameToken objects can be constructed during parsing. 645 ** Each new object is created by sqlite3RenameTokenMap(). 646 ** As the parse tree is transformed, the sqlite3RenameTokenRemap() 647 ** routine is used to keep the mapping current. 648 ** 649 ** After the parse finishes, renameTokenFind() routine can be used 650 ** to look up the actual token value that created some element in 651 ** the parse tree. 652 */ 653 struct RenameToken { 654 void *p; /* Parse tree element created by token t */ 655 Token t; /* The token that created parse tree element p */ 656 RenameToken *pNext; /* Next is a list of all RenameToken objects */ 657 }; 658 659 /* 660 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed 661 ** down into the Walker. 662 */ 663 typedef struct RenameCtx RenameCtx; 664 struct RenameCtx { 665 RenameToken *pList; /* List of tokens to overwrite */ 666 int nList; /* Number of tokens in pList */ 667 int iCol; /* Index of column being renamed */ 668 Table *pTab; /* Table being ALTERed */ 669 const char *zOld; /* Old column name */ 670 }; 671 672 #ifdef SQLITE_DEBUG 673 /* 674 ** This function is only for debugging. It performs two tasks: 675 ** 676 ** 1. Checks that pointer pPtr does not already appear in the 677 ** rename-token list. 678 ** 679 ** 2. Dereferences each pointer in the rename-token list. 680 ** 681 ** The second is most effective when debugging under valgrind or 682 ** address-sanitizer or similar. If any of these pointers no longer 683 ** point to valid objects, an exception is raised by the memory-checking 684 ** tool. 685 ** 686 ** The point of this is to prevent comparisons of invalid pointer values. 687 ** Even though this always seems to work, it is undefined according to the 688 ** C standard. Example of undefined comparison: 689 ** 690 ** sqlite3_free(x); 691 ** if( x==y ) ... 692 ** 693 ** Technically, as x no longer points into a valid object or to the byte 694 ** following a valid object, it may not be used in comparison operations. 695 */ 696 static void renameTokenCheckAll(Parse *pParse, void *pPtr){ 697 if( pParse->nErr==0 && pParse->db->mallocFailed==0 ){ 698 RenameToken *p; 699 u8 i = 0; 700 for(p=pParse->pRename; p; p=p->pNext){ 701 if( p->p ){ 702 assert( p->p!=pPtr ); 703 i += *(u8*)(p->p); 704 } 705 } 706 } 707 } 708 #else 709 # define renameTokenCheckAll(x,y) 710 #endif 711 712 /* 713 ** Remember that the parser tree element pPtr was created using 714 ** the token pToken. 715 ** 716 ** In other words, construct a new RenameToken object and add it 717 ** to the list of RenameToken objects currently being built up 718 ** in pParse->pRename. 719 ** 720 ** The pPtr argument is returned so that this routine can be used 721 ** with tail recursion in tokenExpr() routine, for a small performance 722 ** improvement. 723 */ 724 void *sqlite3RenameTokenMap(Parse *pParse, void *pPtr, Token *pToken){ 725 RenameToken *pNew; 726 assert( pPtr || pParse->db->mallocFailed ); 727 renameTokenCheckAll(pParse, pPtr); 728 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){ 729 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken)); 730 if( pNew ){ 731 pNew->p = pPtr; 732 pNew->t = *pToken; 733 pNew->pNext = pParse->pRename; 734 pParse->pRename = pNew; 735 } 736 } 737 738 return pPtr; 739 } 740 741 /* 742 ** It is assumed that there is already a RenameToken object associated 743 ** with parse tree element pFrom. This function remaps the associated token 744 ** to parse tree element pTo. 745 */ 746 void sqlite3RenameTokenRemap(Parse *pParse, void *pTo, void *pFrom){ 747 RenameToken *p; 748 renameTokenCheckAll(pParse, pTo); 749 for(p=pParse->pRename; p; p=p->pNext){ 750 if( p->p==pFrom ){ 751 p->p = pTo; 752 break; 753 } 754 } 755 } 756 757 /* 758 ** Walker callback used by sqlite3RenameExprUnmap(). 759 */ 760 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){ 761 Parse *pParse = pWalker->pParse; 762 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); 763 return WRC_Continue; 764 } 765 766 /* 767 ** Iterate through the Select objects that are part of WITH clauses attached 768 ** to select statement pSelect. 769 */ 770 static void renameWalkWith(Walker *pWalker, Select *pSelect){ 771 With *pWith = pSelect->pWith; 772 if( pWith ){ 773 int i; 774 for(i=0; i<pWith->nCte; i++){ 775 Select *p = pWith->a[i].pSelect; 776 NameContext sNC; 777 memset(&sNC, 0, sizeof(sNC)); 778 sNC.pParse = pWalker->pParse; 779 sqlite3SelectPrep(sNC.pParse, p, &sNC); 780 sqlite3WalkSelect(pWalker, p); 781 sqlite3RenameExprlistUnmap(pWalker->pParse, pWith->a[i].pCols); 782 } 783 } 784 } 785 786 /* 787 ** Unmap all tokens in the IdList object passed as the second argument. 788 */ 789 static void unmapColumnIdlistNames( 790 Parse *pParse, 791 IdList *pIdList 792 ){ 793 if( pIdList ){ 794 int ii; 795 for(ii=0; ii<pIdList->nId; ii++){ 796 sqlite3RenameTokenRemap(pParse, 0, (void*)pIdList->a[ii].zName); 797 } 798 } 799 } 800 801 /* 802 ** Walker callback used by sqlite3RenameExprUnmap(). 803 */ 804 static int renameUnmapSelectCb(Walker *pWalker, Select *p){ 805 Parse *pParse = pWalker->pParse; 806 int i; 807 if( pParse->nErr ) return WRC_Abort; 808 if( NEVER(p->selFlags & SF_View) ) return WRC_Prune; 809 if( ALWAYS(p->pEList) ){ 810 ExprList *pList = p->pEList; 811 for(i=0; i<pList->nExpr; i++){ 812 if( pList->a[i].zEName && pList->a[i].eEName==ENAME_NAME ){ 813 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName); 814 } 815 } 816 } 817 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */ 818 SrcList *pSrc = p->pSrc; 819 for(i=0; i<pSrc->nSrc; i++){ 820 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName); 821 if( sqlite3WalkExpr(pWalker, pSrc->a[i].pOn) ) return WRC_Abort; 822 unmapColumnIdlistNames(pParse, pSrc->a[i].pUsing); 823 } 824 } 825 826 renameWalkWith(pWalker, p); 827 return WRC_Continue; 828 } 829 830 /* 831 ** Remove all nodes that are part of expression pExpr from the rename list. 832 */ 833 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){ 834 u8 eMode = pParse->eParseMode; 835 Walker sWalker; 836 memset(&sWalker, 0, sizeof(Walker)); 837 sWalker.pParse = pParse; 838 sWalker.xExprCallback = renameUnmapExprCb; 839 sWalker.xSelectCallback = renameUnmapSelectCb; 840 pParse->eParseMode = PARSE_MODE_UNMAP; 841 sqlite3WalkExpr(&sWalker, pExpr); 842 pParse->eParseMode = eMode; 843 } 844 845 /* 846 ** Remove all nodes that are part of expression-list pEList from the 847 ** rename list. 848 */ 849 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){ 850 if( pEList ){ 851 int i; 852 Walker sWalker; 853 memset(&sWalker, 0, sizeof(Walker)); 854 sWalker.pParse = pParse; 855 sWalker.xExprCallback = renameUnmapExprCb; 856 sqlite3WalkExprList(&sWalker, pEList); 857 for(i=0; i<pEList->nExpr; i++){ 858 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) ){ 859 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName); 860 } 861 } 862 } 863 } 864 865 /* 866 ** Free the list of RenameToken objects given in the second argument 867 */ 868 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){ 869 RenameToken *pNext; 870 RenameToken *p; 871 for(p=pToken; p; p=pNext){ 872 pNext = p->pNext; 873 sqlite3DbFree(db, p); 874 } 875 } 876 877 /* 878 ** Search the Parse object passed as the first argument for a RenameToken 879 ** object associated with parse tree element pPtr. If found, return a pointer 880 ** to it. Otherwise, return NULL. 881 ** 882 ** If the second argument passed to this function is not NULL and a matching 883 ** RenameToken object is found, remove it from the Parse object and add it to 884 ** the list maintained by the RenameCtx object. 885 */ 886 static RenameToken *renameTokenFind( 887 Parse *pParse, 888 struct RenameCtx *pCtx, 889 void *pPtr 890 ){ 891 RenameToken **pp; 892 assert( pPtr!=0 ); 893 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){ 894 if( (*pp)->p==pPtr ){ 895 RenameToken *pToken = *pp; 896 if( pCtx ){ 897 *pp = pToken->pNext; 898 pToken->pNext = pCtx->pList; 899 pCtx->pList = pToken; 900 pCtx->nList++; 901 } 902 return pToken; 903 } 904 } 905 return 0; 906 } 907 908 /* 909 ** This is a Walker select callback. It does nothing. It is only required 910 ** because without a dummy callback, sqlite3WalkExpr() and similar do not 911 ** descend into sub-select statements. 912 */ 913 static int renameColumnSelectCb(Walker *pWalker, Select *p){ 914 if( p->selFlags & SF_View ) return WRC_Prune; 915 renameWalkWith(pWalker, p); 916 return WRC_Continue; 917 } 918 919 /* 920 ** This is a Walker expression callback. 921 ** 922 ** For every TK_COLUMN node in the expression tree, search to see 923 ** if the column being references is the column being renamed by an 924 ** ALTER TABLE statement. If it is, then attach its associated 925 ** RenameToken object to the list of RenameToken objects being 926 ** constructed in RenameCtx object at pWalker->u.pRename. 927 */ 928 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){ 929 RenameCtx *p = pWalker->u.pRename; 930 if( pExpr->op==TK_TRIGGER 931 && pExpr->iColumn==p->iCol 932 && pWalker->pParse->pTriggerTab==p->pTab 933 ){ 934 renameTokenFind(pWalker->pParse, p, (void*)pExpr); 935 }else if( pExpr->op==TK_COLUMN 936 && pExpr->iColumn==p->iCol 937 && p->pTab==pExpr->y.pTab 938 ){ 939 renameTokenFind(pWalker->pParse, p, (void*)pExpr); 940 } 941 return WRC_Continue; 942 } 943 944 /* 945 ** The RenameCtx contains a list of tokens that reference a column that 946 ** is being renamed by an ALTER TABLE statement. Return the "last" 947 ** RenameToken in the RenameCtx and remove that RenameToken from the 948 ** RenameContext. "Last" means the last RenameToken encountered when 949 ** the input SQL is parsed from left to right. Repeated calls to this routine 950 ** return all column name tokens in the order that they are encountered 951 ** in the SQL statement. 952 */ 953 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){ 954 RenameToken *pBest = pCtx->pList; 955 RenameToken *pToken; 956 RenameToken **pp; 957 958 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){ 959 if( pToken->t.z>pBest->t.z ) pBest = pToken; 960 } 961 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext); 962 *pp = pBest->pNext; 963 964 return pBest; 965 } 966 967 /* 968 ** An error occured while parsing or otherwise processing a database 969 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an 970 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the 971 ** sub-routine is currently stored in pParse->zErrMsg. This function 972 ** adds context to the error message and then stores it in pCtx. 973 */ 974 static void renameColumnParseError( 975 sqlite3_context *pCtx, 976 const char *zWhen, 977 sqlite3_value *pType, 978 sqlite3_value *pObject, 979 Parse *pParse 980 ){ 981 const char *zT = (const char*)sqlite3_value_text(pType); 982 const char *zN = (const char*)sqlite3_value_text(pObject); 983 char *zErr; 984 985 zErr = sqlite3_mprintf("error in %s %s%s%s: %s", 986 zT, zN, (zWhen[0] ? " " : ""), zWhen, 987 pParse->zErrMsg 988 ); 989 sqlite3_result_error(pCtx, zErr, -1); 990 sqlite3_free(zErr); 991 } 992 993 /* 994 ** For each name in the the expression-list pEList (i.e. each 995 ** pEList->a[i].zName) that matches the string in zOld, extract the 996 ** corresponding rename-token from Parse object pParse and add it 997 ** to the RenameCtx pCtx. 998 */ 999 static void renameColumnElistNames( 1000 Parse *pParse, 1001 RenameCtx *pCtx, 1002 ExprList *pEList, 1003 const char *zOld 1004 ){ 1005 if( pEList ){ 1006 int i; 1007 for(i=0; i<pEList->nExpr; i++){ 1008 char *zName = pEList->a[i].zEName; 1009 if( ALWAYS(pEList->a[i].eEName==ENAME_NAME) 1010 && ALWAYS(zName!=0) 1011 && 0==sqlite3_stricmp(zName, zOld) 1012 ){ 1013 renameTokenFind(pParse, pCtx, (void*)zName); 1014 } 1015 } 1016 } 1017 } 1018 1019 /* 1020 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) 1021 ** that matches the string in zOld, extract the corresponding rename-token 1022 ** from Parse object pParse and add it to the RenameCtx pCtx. 1023 */ 1024 static void renameColumnIdlistNames( 1025 Parse *pParse, 1026 RenameCtx *pCtx, 1027 IdList *pIdList, 1028 const char *zOld 1029 ){ 1030 if( pIdList ){ 1031 int i; 1032 for(i=0; i<pIdList->nId; i++){ 1033 char *zName = pIdList->a[i].zName; 1034 if( 0==sqlite3_stricmp(zName, zOld) ){ 1035 renameTokenFind(pParse, pCtx, (void*)zName); 1036 } 1037 } 1038 } 1039 } 1040 1041 1042 /* 1043 ** Parse the SQL statement zSql using Parse object (*p). The Parse object 1044 ** is initialized by this function before it is used. 1045 */ 1046 static int renameParseSql( 1047 Parse *p, /* Memory to use for Parse object */ 1048 const char *zDb, /* Name of schema SQL belongs to */ 1049 sqlite3 *db, /* Database handle */ 1050 const char *zSql, /* SQL to parse */ 1051 int bTemp /* True if SQL is from temp schema */ 1052 ){ 1053 int rc; 1054 char *zErr = 0; 1055 1056 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb); 1057 1058 /* Parse the SQL statement passed as the first argument. If no error 1059 ** occurs and the parse does not result in a new table, index or 1060 ** trigger object, the database must be corrupt. */ 1061 memset(p, 0, sizeof(Parse)); 1062 p->eParseMode = PARSE_MODE_RENAME; 1063 p->db = db; 1064 p->nQueryLoop = 1; 1065 rc = zSql ? sqlite3RunParser(p, zSql, &zErr) : SQLITE_NOMEM; 1066 assert( p->zErrMsg==0 ); 1067 assert( rc!=SQLITE_OK || zErr==0 ); 1068 p->zErrMsg = zErr; 1069 if( db->mallocFailed ) rc = SQLITE_NOMEM; 1070 if( rc==SQLITE_OK 1071 && p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0 1072 ){ 1073 rc = SQLITE_CORRUPT_BKPT; 1074 } 1075 1076 #ifdef SQLITE_DEBUG 1077 /* Ensure that all mappings in the Parse.pRename list really do map to 1078 ** a part of the input string. */ 1079 if( rc==SQLITE_OK ){ 1080 int nSql = sqlite3Strlen30(zSql); 1081 RenameToken *pToken; 1082 for(pToken=p->pRename; pToken; pToken=pToken->pNext){ 1083 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] ); 1084 } 1085 } 1086 #endif 1087 1088 db->init.iDb = 0; 1089 return rc; 1090 } 1091 1092 /* 1093 ** This function edits SQL statement zSql, replacing each token identified 1094 ** by the linked list pRename with the text of zNew. If argument bQuote is 1095 ** true, then zNew is always quoted first. If no error occurs, the result 1096 ** is loaded into context object pCtx as the result. 1097 ** 1098 ** Or, if an error occurs (i.e. an OOM condition), an error is left in 1099 ** pCtx and an SQLite error code returned. 1100 */ 1101 static int renameEditSql( 1102 sqlite3_context *pCtx, /* Return result here */ 1103 RenameCtx *pRename, /* Rename context */ 1104 const char *zSql, /* SQL statement to edit */ 1105 const char *zNew, /* New token text */ 1106 int bQuote /* True to always quote token */ 1107 ){ 1108 int nNew = sqlite3Strlen30(zNew); 1109 int nSql = sqlite3Strlen30(zSql); 1110 sqlite3 *db = sqlite3_context_db_handle(pCtx); 1111 int rc = SQLITE_OK; 1112 char *zQuot; 1113 char *zOut; 1114 int nQuot; 1115 1116 /* Set zQuot to point to a buffer containing a quoted copy of the 1117 ** identifier zNew. If the corresponding identifier in the original 1118 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to 1119 ** point to zQuot so that all substitutions are made using the 1120 ** quoted version of the new column name. */ 1121 zQuot = sqlite3MPrintf(db, "\"%w\"", zNew); 1122 if( zQuot==0 ){ 1123 return SQLITE_NOMEM; 1124 }else{ 1125 nQuot = sqlite3Strlen30(zQuot); 1126 } 1127 if( bQuote ){ 1128 zNew = zQuot; 1129 nNew = nQuot; 1130 } 1131 1132 /* At this point pRename->pList contains a list of RenameToken objects 1133 ** corresponding to all tokens in the input SQL that must be replaced 1134 ** with the new column name. All that remains is to construct and 1135 ** return the edited SQL string. */ 1136 assert( nQuot>=nNew ); 1137 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1); 1138 if( zOut ){ 1139 int nOut = nSql; 1140 memcpy(zOut, zSql, nSql); 1141 while( pRename->pList ){ 1142 int iOff; /* Offset of token to replace in zOut */ 1143 RenameToken *pBest = renameColumnTokenNext(pRename); 1144 1145 u32 nReplace; 1146 const char *zReplace; 1147 if( sqlite3IsIdChar(*pBest->t.z) ){ 1148 nReplace = nNew; 1149 zReplace = zNew; 1150 }else{ 1151 nReplace = nQuot; 1152 zReplace = zQuot; 1153 } 1154 1155 iOff = pBest->t.z - zSql; 1156 if( pBest->t.n!=nReplace ){ 1157 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], 1158 nOut - (iOff + pBest->t.n) 1159 ); 1160 nOut += nReplace - pBest->t.n; 1161 zOut[nOut] = '\0'; 1162 } 1163 memcpy(&zOut[iOff], zReplace, nReplace); 1164 sqlite3DbFree(db, pBest); 1165 } 1166 1167 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT); 1168 sqlite3DbFree(db, zOut); 1169 }else{ 1170 rc = SQLITE_NOMEM; 1171 } 1172 1173 sqlite3_free(zQuot); 1174 return rc; 1175 } 1176 1177 /* 1178 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming 1179 ** it was read from the schema of database zDb. Return SQLITE_OK if 1180 ** successful. Otherwise, return an SQLite error code and leave an error 1181 ** message in the Parse object. 1182 */ 1183 static int renameResolveTrigger(Parse *pParse){ 1184 sqlite3 *db = pParse->db; 1185 Trigger *pNew = pParse->pNewTrigger; 1186 TriggerStep *pStep; 1187 NameContext sNC; 1188 int rc = SQLITE_OK; 1189 1190 memset(&sNC, 0, sizeof(sNC)); 1191 sNC.pParse = pParse; 1192 assert( pNew->pTabSchema ); 1193 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, 1194 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName 1195 ); 1196 pParse->eTriggerOp = pNew->op; 1197 /* ALWAYS() because if the table of the trigger does not exist, the 1198 ** error would have been hit before this point */ 1199 if( ALWAYS(pParse->pTriggerTab) ){ 1200 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab); 1201 } 1202 1203 /* Resolve symbols in WHEN clause */ 1204 if( rc==SQLITE_OK && pNew->pWhen ){ 1205 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen); 1206 } 1207 1208 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){ 1209 if( pStep->pSelect ){ 1210 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC); 1211 if( pParse->nErr ) rc = pParse->rc; 1212 } 1213 if( rc==SQLITE_OK && pStep->zTarget ){ 1214 SrcList *pSrc = sqlite3TriggerStepSrc(pParse, pStep); 1215 if( pSrc ){ 1216 int i; 1217 for(i=0; i<pSrc->nSrc && rc==SQLITE_OK; i++){ 1218 SrcItem *p = &pSrc->a[i]; 1219 p->iCursor = pParse->nTab++; 1220 if( p->pSelect ){ 1221 sqlite3SelectPrep(pParse, p->pSelect, 0); 1222 sqlite3ExpandSubquery(pParse, p); 1223 assert( i>0 ); 1224 assert( pStep->pFrom->a[i-1].pSelect ); 1225 sqlite3SelectPrep(pParse, pStep->pFrom->a[i-1].pSelect, 0); 1226 }else{ 1227 p->pTab = sqlite3LocateTableItem(pParse, 0, p); 1228 if( p->pTab==0 ){ 1229 rc = SQLITE_ERROR; 1230 }else{ 1231 p->pTab->nTabRef++; 1232 rc = sqlite3ViewGetColumnNames(pParse, p->pTab); 1233 } 1234 } 1235 } 1236 sNC.pSrcList = pSrc; 1237 if( rc==SQLITE_OK && pStep->pWhere ){ 1238 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere); 1239 } 1240 if( rc==SQLITE_OK ){ 1241 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList); 1242 } 1243 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) ); 1244 if( pStep->pUpsert && rc==SQLITE_OK ){ 1245 Upsert *pUpsert = pStep->pUpsert; 1246 pUpsert->pUpsertSrc = pSrc; 1247 sNC.uNC.pUpsert = pUpsert; 1248 sNC.ncFlags = NC_UUpsert; 1249 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); 1250 if( rc==SQLITE_OK ){ 1251 ExprList *pUpsertSet = pUpsert->pUpsertSet; 1252 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet); 1253 } 1254 if( rc==SQLITE_OK ){ 1255 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere); 1256 } 1257 if( rc==SQLITE_OK ){ 1258 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); 1259 } 1260 sNC.ncFlags = 0; 1261 } 1262 sNC.pSrcList = 0; 1263 sqlite3SrcListDelete(db, pSrc); 1264 }else{ 1265 rc = SQLITE_NOMEM; 1266 } 1267 } 1268 } 1269 return rc; 1270 } 1271 1272 /* 1273 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr 1274 ** objects that are part of the trigger passed as the second argument. 1275 */ 1276 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){ 1277 TriggerStep *pStep; 1278 1279 /* Find tokens to edit in WHEN clause */ 1280 sqlite3WalkExpr(pWalker, pTrigger->pWhen); 1281 1282 /* Find tokens to edit in trigger steps */ 1283 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ 1284 sqlite3WalkSelect(pWalker, pStep->pSelect); 1285 sqlite3WalkExpr(pWalker, pStep->pWhere); 1286 sqlite3WalkExprList(pWalker, pStep->pExprList); 1287 if( pStep->pUpsert ){ 1288 Upsert *pUpsert = pStep->pUpsert; 1289 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget); 1290 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet); 1291 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere); 1292 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere); 1293 } 1294 if( pStep->pFrom ){ 1295 int i; 1296 for(i=0; i<pStep->pFrom->nSrc; i++){ 1297 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect); 1298 } 1299 } 1300 } 1301 } 1302 1303 /* 1304 ** Free the contents of Parse object (*pParse). Do not free the memory 1305 ** occupied by the Parse object itself. 1306 */ 1307 static void renameParseCleanup(Parse *pParse){ 1308 sqlite3 *db = pParse->db; 1309 Index *pIdx; 1310 if( pParse->pVdbe ){ 1311 sqlite3VdbeFinalize(pParse->pVdbe); 1312 } 1313 sqlite3DeleteTable(db, pParse->pNewTable); 1314 while( (pIdx = pParse->pNewIndex)!=0 ){ 1315 pParse->pNewIndex = pIdx->pNext; 1316 sqlite3FreeIndex(db, pIdx); 1317 } 1318 sqlite3DeleteTrigger(db, pParse->pNewTrigger); 1319 sqlite3DbFree(db, pParse->zErrMsg); 1320 renameTokenFree(db, pParse->pRename); 1321 sqlite3ParserReset(pParse); 1322 } 1323 1324 /* 1325 ** SQL function: 1326 ** 1327 ** sqlite_rename_column(zSql, iCol, bQuote, zNew, zTable, zOld) 1328 ** 1329 ** 0. zSql: SQL statement to rewrite 1330 ** 1. type: Type of object ("table", "view" etc.) 1331 ** 2. object: Name of object 1332 ** 3. Database: Database name (e.g. "main") 1333 ** 4. Table: Table name 1334 ** 5. iCol: Index of column to rename 1335 ** 6. zNew: New column name 1336 ** 7. bQuote: Non-zero if the new column name should be quoted. 1337 ** 8. bTemp: True if zSql comes from temp schema 1338 ** 1339 ** Do a column rename operation on the CREATE statement given in zSql. 1340 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol 1341 ** into zNew. The name should be quoted if bQuote is true. 1342 ** 1343 ** This function is used internally by the ALTER TABLE RENAME COLUMN command. 1344 ** It is only accessible to SQL created using sqlite3NestedParse(). It is 1345 ** not reachable from ordinary SQL passed into sqlite3_prepare(). 1346 */ 1347 static void renameColumnFunc( 1348 sqlite3_context *context, 1349 int NotUsed, 1350 sqlite3_value **argv 1351 ){ 1352 sqlite3 *db = sqlite3_context_db_handle(context); 1353 RenameCtx sCtx; 1354 const char *zSql = (const char*)sqlite3_value_text(argv[0]); 1355 const char *zDb = (const char*)sqlite3_value_text(argv[3]); 1356 const char *zTable = (const char*)sqlite3_value_text(argv[4]); 1357 int iCol = sqlite3_value_int(argv[5]); 1358 const char *zNew = (const char*)sqlite3_value_text(argv[6]); 1359 int bQuote = sqlite3_value_int(argv[7]); 1360 int bTemp = sqlite3_value_int(argv[8]); 1361 const char *zOld; 1362 int rc; 1363 Parse sParse; 1364 Walker sWalker; 1365 Index *pIdx; 1366 int i; 1367 Table *pTab; 1368 #ifndef SQLITE_OMIT_AUTHORIZATION 1369 sqlite3_xauth xAuth = db->xAuth; 1370 #endif 1371 1372 UNUSED_PARAMETER(NotUsed); 1373 if( zSql==0 ) return; 1374 if( zTable==0 ) return; 1375 if( zNew==0 ) return; 1376 if( iCol<0 ) return; 1377 sqlite3BtreeEnterAll(db); 1378 pTab = sqlite3FindTable(db, zTable, zDb); 1379 if( pTab==0 || iCol>=pTab->nCol ){ 1380 sqlite3BtreeLeaveAll(db); 1381 return; 1382 } 1383 zOld = pTab->aCol[iCol].zName; 1384 memset(&sCtx, 0, sizeof(sCtx)); 1385 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol); 1386 1387 #ifndef SQLITE_OMIT_AUTHORIZATION 1388 db->xAuth = 0; 1389 #endif 1390 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp); 1391 1392 /* Find tokens that need to be replaced. */ 1393 memset(&sWalker, 0, sizeof(Walker)); 1394 sWalker.pParse = &sParse; 1395 sWalker.xExprCallback = renameColumnExprCb; 1396 sWalker.xSelectCallback = renameColumnSelectCb; 1397 sWalker.u.pRename = &sCtx; 1398 1399 sCtx.pTab = pTab; 1400 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1401 if( sParse.pNewTable ){ 1402 Select *pSelect = sParse.pNewTable->pSelect; 1403 if( pSelect ){ 1404 pSelect->selFlags &= ~SF_View; 1405 sParse.rc = SQLITE_OK; 1406 sqlite3SelectPrep(&sParse, pSelect, 0); 1407 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); 1408 if( rc==SQLITE_OK ){ 1409 sqlite3WalkSelect(&sWalker, pSelect); 1410 } 1411 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1412 }else{ 1413 /* A regular table */ 1414 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName); 1415 FKey *pFKey; 1416 assert( sParse.pNewTable->pSelect==0 ); 1417 sCtx.pTab = sParse.pNewTable; 1418 if( bFKOnly==0 ){ 1419 renameTokenFind( 1420 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName 1421 ); 1422 if( sCtx.iCol<0 ){ 1423 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey); 1424 } 1425 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); 1426 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){ 1427 sqlite3WalkExprList(&sWalker, pIdx->aColExpr); 1428 } 1429 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){ 1430 sqlite3WalkExprList(&sWalker, pIdx->aColExpr); 1431 } 1432 } 1433 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1434 for(i=0; i<sParse.pNewTable->nCol; i++){ 1435 sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt); 1436 } 1437 #endif 1438 1439 for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1440 for(i=0; i<pFKey->nCol; i++){ 1441 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){ 1442 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]); 1443 } 1444 if( 0==sqlite3_stricmp(pFKey->zTo, zTable) 1445 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld) 1446 ){ 1447 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol); 1448 } 1449 } 1450 } 1451 } 1452 }else if( sParse.pNewIndex ){ 1453 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); 1454 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); 1455 }else{ 1456 /* A trigger */ 1457 TriggerStep *pStep; 1458 rc = renameResolveTrigger(&sParse); 1459 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1460 1461 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ 1462 if( pStep->zTarget ){ 1463 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb); 1464 if( pTarget==pTab ){ 1465 if( pStep->pUpsert ){ 1466 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet; 1467 renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld); 1468 } 1469 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld); 1470 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld); 1471 } 1472 } 1473 } 1474 1475 1476 /* Find tokens to edit in UPDATE OF clause */ 1477 if( sParse.pTriggerTab==pTab ){ 1478 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); 1479 } 1480 1481 /* Find tokens to edit in various expressions and selects */ 1482 renameWalkTrigger(&sWalker, sParse.pNewTrigger); 1483 } 1484 1485 assert( rc==SQLITE_OK ); 1486 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote); 1487 1488 renameColumnFunc_done: 1489 if( rc!=SQLITE_OK ){ 1490 if( sParse.zErrMsg ){ 1491 renameColumnParseError(context, "", argv[1], argv[2], &sParse); 1492 }else{ 1493 sqlite3_result_error_code(context, rc); 1494 } 1495 } 1496 1497 renameParseCleanup(&sParse); 1498 renameTokenFree(db, sCtx.pList); 1499 #ifndef SQLITE_OMIT_AUTHORIZATION 1500 db->xAuth = xAuth; 1501 #endif 1502 sqlite3BtreeLeaveAll(db); 1503 } 1504 1505 /* 1506 ** Walker expression callback used by "RENAME TABLE". 1507 */ 1508 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){ 1509 RenameCtx *p = pWalker->u.pRename; 1510 if( pExpr->op==TK_COLUMN && p->pTab==pExpr->y.pTab ){ 1511 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab); 1512 } 1513 return WRC_Continue; 1514 } 1515 1516 /* 1517 ** Walker select callback used by "RENAME TABLE". 1518 */ 1519 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){ 1520 int i; 1521 RenameCtx *p = pWalker->u.pRename; 1522 SrcList *pSrc = pSelect->pSrc; 1523 if( pSelect->selFlags & SF_View ) return WRC_Prune; 1524 if( pSrc==0 ){ 1525 assert( pWalker->pParse->db->mallocFailed ); 1526 return WRC_Abort; 1527 } 1528 for(i=0; i<pSrc->nSrc; i++){ 1529 SrcItem *pItem = &pSrc->a[i]; 1530 if( pItem->pTab==p->pTab ){ 1531 renameTokenFind(pWalker->pParse, p, pItem->zName); 1532 } 1533 } 1534 renameWalkWith(pWalker, pSelect); 1535 1536 return WRC_Continue; 1537 } 1538 1539 1540 /* 1541 ** This C function implements an SQL user function that is used by SQL code 1542 ** generated by the ALTER TABLE ... RENAME command to modify the definition 1543 ** of any foreign key constraints that use the table being renamed as the 1544 ** parent table. It is passed three arguments: 1545 ** 1546 ** 0: The database containing the table being renamed. 1547 ** 1. type: Type of object ("table", "view" etc.) 1548 ** 2. object: Name of object 1549 ** 3: The complete text of the schema statement being modified, 1550 ** 4: The old name of the table being renamed, and 1551 ** 5: The new name of the table being renamed. 1552 ** 6: True if the schema statement comes from the temp db. 1553 ** 1554 ** It returns the new schema statement. For example: 1555 ** 1556 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0) 1557 ** -> 'CREATE TABLE t1(a REFERENCES t3)' 1558 */ 1559 static void renameTableFunc( 1560 sqlite3_context *context, 1561 int NotUsed, 1562 sqlite3_value **argv 1563 ){ 1564 sqlite3 *db = sqlite3_context_db_handle(context); 1565 const char *zDb = (const char*)sqlite3_value_text(argv[0]); 1566 const char *zInput = (const char*)sqlite3_value_text(argv[3]); 1567 const char *zOld = (const char*)sqlite3_value_text(argv[4]); 1568 const char *zNew = (const char*)sqlite3_value_text(argv[5]); 1569 int bTemp = sqlite3_value_int(argv[6]); 1570 UNUSED_PARAMETER(NotUsed); 1571 1572 if( zInput && zOld && zNew ){ 1573 Parse sParse; 1574 int rc; 1575 int bQuote = 1; 1576 RenameCtx sCtx; 1577 Walker sWalker; 1578 1579 #ifndef SQLITE_OMIT_AUTHORIZATION 1580 sqlite3_xauth xAuth = db->xAuth; 1581 db->xAuth = 0; 1582 #endif 1583 1584 sqlite3BtreeEnterAll(db); 1585 1586 memset(&sCtx, 0, sizeof(RenameCtx)); 1587 sCtx.pTab = sqlite3FindTable(db, zOld, zDb); 1588 memset(&sWalker, 0, sizeof(Walker)); 1589 sWalker.pParse = &sParse; 1590 sWalker.xExprCallback = renameTableExprCb; 1591 sWalker.xSelectCallback = renameTableSelectCb; 1592 sWalker.u.pRename = &sCtx; 1593 1594 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); 1595 1596 if( rc==SQLITE_OK ){ 1597 int isLegacy = (db->flags & SQLITE_LegacyAlter); 1598 if( sParse.pNewTable ){ 1599 Table *pTab = sParse.pNewTable; 1600 1601 if( pTab->pSelect ){ 1602 if( isLegacy==0 ){ 1603 Select *pSelect = pTab->pSelect; 1604 NameContext sNC; 1605 memset(&sNC, 0, sizeof(sNC)); 1606 sNC.pParse = &sParse; 1607 1608 assert( pSelect->selFlags & SF_View ); 1609 pSelect->selFlags &= ~SF_View; 1610 sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC); 1611 if( sParse.nErr ){ 1612 rc = sParse.rc; 1613 }else{ 1614 sqlite3WalkSelect(&sWalker, pTab->pSelect); 1615 } 1616 } 1617 }else{ 1618 /* Modify any FK definitions to point to the new table. */ 1619 #ifndef SQLITE_OMIT_FOREIGN_KEY 1620 if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){ 1621 FKey *pFKey; 1622 for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1623 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){ 1624 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo); 1625 } 1626 } 1627 } 1628 #endif 1629 1630 /* If this is the table being altered, fix any table refs in CHECK 1631 ** expressions. Also update the name that appears right after the 1632 ** "CREATE [VIRTUAL] TABLE" bit. */ 1633 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){ 1634 sCtx.pTab = pTab; 1635 if( isLegacy==0 ){ 1636 sqlite3WalkExprList(&sWalker, pTab->pCheck); 1637 } 1638 renameTokenFind(&sParse, &sCtx, pTab->zName); 1639 } 1640 } 1641 } 1642 1643 else if( sParse.pNewIndex ){ 1644 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName); 1645 if( isLegacy==0 ){ 1646 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); 1647 } 1648 } 1649 1650 #ifndef SQLITE_OMIT_TRIGGER 1651 else{ 1652 Trigger *pTrigger = sParse.pNewTrigger; 1653 TriggerStep *pStep; 1654 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) 1655 && sCtx.pTab->pSchema==pTrigger->pTabSchema 1656 ){ 1657 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table); 1658 } 1659 1660 if( isLegacy==0 ){ 1661 rc = renameResolveTrigger(&sParse); 1662 if( rc==SQLITE_OK ){ 1663 renameWalkTrigger(&sWalker, pTrigger); 1664 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ 1665 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){ 1666 renameTokenFind(&sParse, &sCtx, pStep->zTarget); 1667 } 1668 } 1669 } 1670 } 1671 } 1672 #endif 1673 } 1674 1675 if( rc==SQLITE_OK ){ 1676 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote); 1677 } 1678 if( rc!=SQLITE_OK ){ 1679 if( sParse.zErrMsg ){ 1680 renameColumnParseError(context, "", argv[1], argv[2], &sParse); 1681 }else{ 1682 sqlite3_result_error_code(context, rc); 1683 } 1684 } 1685 1686 renameParseCleanup(&sParse); 1687 renameTokenFree(db, sCtx.pList); 1688 sqlite3BtreeLeaveAll(db); 1689 #ifndef SQLITE_OMIT_AUTHORIZATION 1690 db->xAuth = xAuth; 1691 #endif 1692 } 1693 1694 return; 1695 } 1696 1697 /* 1698 ** An SQL user function that checks that there are no parse or symbol 1699 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement. 1700 ** After an ALTER TABLE .. RENAME operation is performed and the schema 1701 ** reloaded, this function is called on each SQL statement in the schema 1702 ** to ensure that it is still usable. 1703 ** 1704 ** 0: Database name ("main", "temp" etc.). 1705 ** 1: SQL statement. 1706 ** 2: Object type ("view", "table", "trigger" or "index"). 1707 ** 3: Object name. 1708 ** 4: True if object is from temp schema. 1709 ** 5: "when" part of error message. 1710 ** 1711 ** Unless it finds an error, this function normally returns NULL. However, it 1712 ** returns integer value 1 if: 1713 ** 1714 ** * the SQL argument creates a trigger, and 1715 ** * the table that the trigger is attached to is in database zDb. 1716 */ 1717 static void renameTableTest( 1718 sqlite3_context *context, 1719 int NotUsed, 1720 sqlite3_value **argv 1721 ){ 1722 sqlite3 *db = sqlite3_context_db_handle(context); 1723 char const *zDb = (const char*)sqlite3_value_text(argv[0]); 1724 char const *zInput = (const char*)sqlite3_value_text(argv[1]); 1725 int bTemp = sqlite3_value_int(argv[4]); 1726 int isLegacy = (db->flags & SQLITE_LegacyAlter); 1727 char const *zWhen = (const char*)sqlite3_value_text(argv[5]); 1728 1729 #ifndef SQLITE_OMIT_AUTHORIZATION 1730 sqlite3_xauth xAuth = db->xAuth; 1731 db->xAuth = 0; 1732 #endif 1733 1734 UNUSED_PARAMETER(NotUsed); 1735 if( zDb && zInput ){ 1736 int rc; 1737 Parse sParse; 1738 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); 1739 if( rc==SQLITE_OK ){ 1740 if( isLegacy==0 && sParse.pNewTable && sParse.pNewTable->pSelect ){ 1741 NameContext sNC; 1742 memset(&sNC, 0, sizeof(sNC)); 1743 sNC.pParse = &sParse; 1744 sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, &sNC); 1745 if( sParse.nErr ) rc = sParse.rc; 1746 } 1747 1748 else if( sParse.pNewTrigger ){ 1749 if( isLegacy==0 ){ 1750 rc = renameResolveTrigger(&sParse); 1751 } 1752 if( rc==SQLITE_OK ){ 1753 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema); 1754 int i2 = sqlite3FindDbName(db, zDb); 1755 if( i1==i2 ) sqlite3_result_int(context, 1); 1756 } 1757 } 1758 } 1759 1760 if( rc!=SQLITE_OK && zWhen ){ 1761 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse); 1762 } 1763 renameParseCleanup(&sParse); 1764 } 1765 1766 #ifndef SQLITE_OMIT_AUTHORIZATION 1767 db->xAuth = xAuth; 1768 #endif 1769 } 1770 1771 /* 1772 ** The implementation of internal UDF sqlite_drop_column(). 1773 ** 1774 ** Arguments: 1775 ** 1776 ** argv[0]: An integer - the index of the schema containing the table 1777 ** argv[1]: CREATE TABLE statement to modify. 1778 ** argv[2]: An integer - the index of the column to remove. 1779 ** 1780 ** The value returned is a string containing the CREATE TABLE statement 1781 ** with column argv[2] removed. 1782 */ 1783 static void dropColumnFunc( 1784 sqlite3_context *context, 1785 int NotUsed, 1786 sqlite3_value **argv 1787 ){ 1788 sqlite3 *db = sqlite3_context_db_handle(context); 1789 int iSchema = sqlite3_value_int(argv[0]); 1790 const char *zSql = (const char*)sqlite3_value_text(argv[1]); 1791 int iCol = sqlite3_value_int(argv[2]); 1792 const char *zDb = db->aDb[iSchema].zDbSName; 1793 int rc; 1794 Parse sParse; 1795 RenameToken *pCol; 1796 Table *pTab; 1797 const char *zEnd; 1798 char *zNew = 0; 1799 1800 #ifndef SQLITE_OMIT_AUTHORIZATION 1801 sqlite3_xauth xAuth = db->xAuth; 1802 db->xAuth = 0; 1803 #endif 1804 1805 UNUSED_PARAMETER(NotUsed); 1806 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1); 1807 if( rc!=SQLITE_OK ) goto drop_column_done; 1808 pTab = sParse.pNewTable; 1809 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){ 1810 /* This can happen if the sqlite_schema table is corrupt */ 1811 rc = SQLITE_CORRUPT_BKPT; 1812 goto drop_column_done; 1813 } 1814 1815 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zName); 1816 if( iCol<pTab->nCol-1 ){ 1817 RenameToken *pEnd; 1818 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zName); 1819 zEnd = (const char*)pEnd->t.z; 1820 }else{ 1821 zEnd = (const char*)&zSql[pTab->addColOffset]; 1822 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--; 1823 } 1824 1825 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd); 1826 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT); 1827 sqlite3_free(zNew); 1828 1829 drop_column_done: 1830 renameParseCleanup(&sParse); 1831 #ifndef SQLITE_OMIT_AUTHORIZATION 1832 db->xAuth = xAuth; 1833 #endif 1834 if( rc!=SQLITE_OK ){ 1835 sqlite3_result_error_code(context, rc); 1836 } 1837 } 1838 1839 /* 1840 ** This function is called by the parser upon parsing an 1841 ** 1842 ** ALTER TABLE pSrc DROP COLUMN pName 1843 ** 1844 ** statement. Argument pSrc contains the possibly qualified name of the 1845 ** table being edited, and token pName the name of the column to drop. 1846 */ 1847 void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, Token *pName){ 1848 sqlite3 *db = pParse->db; /* Database handle */ 1849 Table *pTab; /* Table to modify */ 1850 int iDb; /* Index of db containing pTab in aDb[] */ 1851 const char *zDb; /* Database containing pTab ("main" etc.) */ 1852 char *zCol = 0; /* Name of column to drop */ 1853 int iCol; /* Index of column zCol in pTab->aCol[] */ 1854 1855 /* Look up the table being altered. */ 1856 assert( pParse->pNewTable==0 ); 1857 assert( sqlite3BtreeHoldsAllMutexes(db) ); 1858 if( NEVER(db->mallocFailed) ) goto exit_drop_column; 1859 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 1860 if( !pTab ) goto exit_drop_column; 1861 1862 /* Make sure this is not an attempt to ALTER a view, virtual table or 1863 ** system table. */ 1864 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column; 1865 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column; 1866 1867 /* Find the index of the column being dropped. */ 1868 zCol = sqlite3NameFromToken(db, pName); 1869 if( zCol==0 ){ 1870 assert( db->mallocFailed ); 1871 goto exit_drop_column; 1872 } 1873 iCol = sqlite3ColumnIndex(pTab, zCol); 1874 if( iCol<0 ){ 1875 sqlite3ErrorMsg(pParse, "no such column: \"%s\"", zCol); 1876 goto exit_drop_column; 1877 } 1878 1879 /* Do not allow the user to drop a PRIMARY KEY column or a column 1880 ** constrained by a UNIQUE constraint. */ 1881 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){ 1882 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"", 1883 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE", 1884 zCol 1885 ); 1886 goto exit_drop_column; 1887 } 1888 1889 /* Do not allow the number of columns to go to zero */ 1890 if( pTab->nCol<=1 ){ 1891 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol); 1892 goto exit_drop_column; 1893 } 1894 1895 /* Edit the sqlite_schema table */ 1896 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 1897 assert( iDb>=0 ); 1898 zDb = db->aDb[iDb].zDbSName; 1899 renameTestSchema(pParse, zDb, iDb==1, ""); 1900 sqlite3NestedParse(pParse, 1901 "UPDATE \"%w\"." DFLT_SCHEMA_TABLE " SET " 1902 "sql = sqlite_drop_column(%d, sql, %d) " 1903 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)" 1904 , zDb, iDb, iCol, pTab->zName 1905 ); 1906 1907 /* Drop and reload the database schema. */ 1908 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop); 1909 renameTestSchema(pParse, zDb, iDb==1, "after drop column"); 1910 1911 /* Edit rows of table on disk */ 1912 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){ 1913 int i; 1914 int addr; 1915 int reg; 1916 int regRec; 1917 Index *pPk = 0; 1918 int nField = 0; /* Number of non-virtual columns after drop */ 1919 int iCur; 1920 Vdbe *v = sqlite3GetVdbe(pParse); 1921 iCur = pParse->nTab++; 1922 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 1923 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 1924 reg = ++pParse->nMem; 1925 pParse->nMem += pTab->nCol; 1926 if( HasRowid(pTab) ){ 1927 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg); 1928 }else{ 1929 pPk = sqlite3PrimaryKeyIndex(pTab); 1930 } 1931 for(i=0; i<pTab->nCol; i++){ 1932 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 1933 int regOut; 1934 if( pPk ){ 1935 int iPos = sqlite3TableColumnToIndex(pPk, i); 1936 int iColPos = sqlite3TableColumnToIndex(pPk, iCol); 1937 regOut = reg+1+iPos-(iPos>iColPos); 1938 }else{ 1939 regOut = reg+1+nField; 1940 } 1941 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut); 1942 nField++; 1943 } 1944 } 1945 regRec = reg + pTab->nCol; 1946 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec); 1947 if( pPk ){ 1948 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol); 1949 }else{ 1950 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg); 1951 } 1952 1953 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v); 1954 sqlite3VdbeJumpHere(v, addr); 1955 } 1956 1957 exit_drop_column: 1958 sqlite3DbFree(db, zCol); 1959 sqlite3SrcListDelete(db, pSrc); 1960 } 1961 1962 /* 1963 ** Register built-in functions used to help implement ALTER TABLE 1964 */ 1965 void sqlite3AlterFunctions(void){ 1966 static FuncDef aAlterTableFuncs[] = { 1967 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc), 1968 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc), 1969 INTERNAL_FUNCTION(sqlite_rename_test, 6, renameTableTest), 1970 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc), 1971 }; 1972 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); 1973 } 1974 #endif /* SQLITE_ALTER_TABLE */ 1975