Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/src/alter.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / src / alter.c` 3187 lines ยท 103863 bytes Raw Blame History 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_Eponymous)!=0 35 || ( (pTab->tabFlags & TF_Shadow)!=0 36 && sqlite3ReadOnlyShadowTables(pParse->db) 37 ) 38 #endif 39 ){ 40 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName); 41 return 1; 42 } 43 return 0; 44 } 45 46 /* 47 ** Generate code to verify that the schemas of database zDb and, if 48 ** bTemp is not true, database "temp", can still be parsed. This is 49 ** called at the end of the generation of an ALTER TABLE ... RENAME ... 50 ** statement to ensure that the operation has not rendered any schema 51 ** objects unusable. 52 */ 53 static void renameTestSchema( 54 Parse *pParse, /* Parse context */ 55 const char *zDb, /* Name of db to verify schema of */ 56 int bTemp, /* True if this is the temp db */ 57 const char *zWhen, /* "when" part of error message */ 58 int bNoDQS /* Do not allow DQS in the schema */ 59 ){ 60 pParse->colNamesSet = 1; 61 sqlite3NestedParse(pParse, 62 "SELECT 1 " 63 "FROM \"%w\"." LEGACY_SCHEMA_TABLE " " 64 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 65 " AND sql NOT LIKE 'create virtual%%'" 66 " AND sqlite_rename_test(%Q, sql, type, name, %d, %Q, %d)=NULL ", 67 zDb, 68 zDb, bTemp, zWhen, bNoDQS 69 ); 70 71 if( bTemp==0 ){ 72 sqlite3NestedParse(pParse, 73 "SELECT 1 " 74 "FROM temp." LEGACY_SCHEMA_TABLE " " 75 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 76 " AND sql NOT LIKE 'create virtual%%'" 77 " AND sqlite_rename_test(%Q, sql, type, name, 1, %Q, %d)=NULL ", 78 zDb, zWhen, bNoDQS 79 ); 80 } 81 } 82 83 /* 84 ** Generate VM code to replace any double-quoted strings (but not double-quoted 85 ** identifiers) within the "sql" column of the sqlite_schema table in 86 ** database zDb with their single-quoted equivalents. If argument bTemp is 87 ** not true, similarly update all SQL statements in the sqlite_schema table 88 ** of the temp db. 89 */ 90 static void renameFixQuotes(Parse *pParse, const char *zDb, int bTemp){ 91 sqlite3NestedParse(pParse, 92 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE 93 " SET sql = sqlite_rename_quotefix(%Q, sql)" 94 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 95 " AND sql NOT LIKE 'create virtual%%'" , zDb, zDb 96 ); 97 if( bTemp==0 ){ 98 sqlite3NestedParse(pParse, 99 "UPDATE temp." LEGACY_SCHEMA_TABLE 100 " SET sql = sqlite_rename_quotefix('temp', sql)" 101 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X'" 102 " AND sql NOT LIKE 'create virtual%%'" 103 ); 104 } 105 } 106 107 /* 108 ** Generate code to reload the schema for database iDb. And, if iDb!=1, for 109 ** the temp database as well. 110 */ 111 static void renameReloadSchema(Parse *pParse, int iDb, u16 p5){ 112 Vdbe *v = pParse->pVdbe; 113 if( v ){ 114 sqlite3ChangeCookie(pParse, iDb); 115 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5); 116 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5); 117 } 118 } 119 120 /* 121 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 122 ** command. 123 */ 124 void sqlite3AlterRenameTable( 125 Parse *pParse, /* Parser context. */ 126 SrcList *pSrc, /* The table to rename. */ 127 Token *pName /* The new table name. */ 128 ){ 129 int iDb; /* Database that contains the table */ 130 char *zDb; /* Name of database iDb */ 131 Table *pTab; /* Table being renamed */ 132 char *zName = 0; /* NULL-terminated version of pName */ 133 sqlite3 *db = pParse->db; /* Database connection */ 134 int nTabName; /* Number of UTF-8 characters in zTabName */ 135 const char *zTabName; /* Original name of the table */ 136 Vdbe *v; 137 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */ 138 139 if( NEVER(db->mallocFailed) ) goto exit_rename_table; 140 assert( pSrc->nSrc==1 ); 141 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) ); 142 143 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 144 if( !pTab ) goto exit_rename_table; 145 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema); 146 zDb = db->aDb[iDb].zDbSName; 147 148 /* Get a NULL terminated version of the new table name. */ 149 zName = sqlite3NameFromToken(db, pName); 150 if( !zName ) goto exit_rename_table; 151 152 /* Check that a table or index named 'zName' does not already exist 153 ** in database iDb. If so, this is an error. 154 */ 155 if( sqlite3FindTable(db, zName, zDb) 156 || sqlite3FindIndex(db, zName, zDb) 157 || sqlite3IsShadowTableOf(db, pTab, zName) 158 ){ 159 sqlite3ErrorMsg(pParse, 160 "there is already another table or index with this name: %s", zName); 161 goto exit_rename_table; 162 } 163 164 /* Make sure it is not a system table being altered, or a reserved name 165 ** that the table is being renamed to. 166 */ 167 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ 168 goto exit_rename_table; 169 } 170 if( SQLITE_OK!=sqlite3CheckObjectName(pParse,zName,"table",zName,zDb) ){ 171 goto exit_rename_table; 172 } 173 174 #ifndef SQLITE_OMIT_VIEW 175 if( IsView(pTab) ){ 176 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName); 177 goto exit_rename_table; 178 } 179 #endif 180 181 #ifndef SQLITE_OMIT_AUTHORIZATION 182 /* Invoke the authorization callback. */ 183 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 184 goto exit_rename_table; 185 } 186 #endif 187 188 #ifndef SQLITE_OMIT_VIRTUALTABLE 189 if( sqlite3ViewGetColumnNames(pParse, pTab) ){ 190 goto exit_rename_table; 191 } 192 if( IsVirtual(pTab) ){ 193 pVTab = sqlite3GetVTable(db, pTab); 194 if( pVTab->pVtab->pModule->xRename==0 ){ 195 pVTab = 0; 196 } 197 } 198 #endif 199 200 /* Begin a transaction for database iDb. Then modify the schema cookie 201 ** (since the ALTER TABLE modifies the schema). Call sqlite3MayAbort(), 202 ** as the scalar functions (e.g. sqlite_rename_table()) invoked by the 203 ** nested SQL may raise an exception. */ 204 v = sqlite3GetVdbe(pParse); 205 if( v==0 ){ 206 goto exit_rename_table; 207 } 208 sqlite3MayAbort(pParse); 209 210 /* figure out how many UTF-8 characters are in zName */ 211 zTabName = pTab->zName; 212 nTabName = sqlite3Utf8CharLen(zTabName, -1); 213 214 /* Rewrite all CREATE TABLE, INDEX, TRIGGER or VIEW statements in 215 ** the schema to use the new table name, and update the tbl_name and 216 ** name columns as required. */ 217 sqlite3NestedParse(pParse, 218 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 219 "sql = CASE WHEN type='index' AND " 220 "name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' THEN sql " 221 "ELSE sqlite_rename_table(%Q, type, name, sql, %Q, %Q, %d) END, " 222 "tbl_name = CASE " 223 "WHEN tbl_name=%Q COLLATE nocase AND (type!='trigger' OR %d=0 OR " 224 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0)) " 225 "THEN %Q ELSE tbl_name END, " 226 "name = CASE " 227 "WHEN type='table' AND tbl_name=%Q COLLATE nocase THEN %Q " 228 "WHEN type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X' " 229 "THEN 'sqlite_autoindex_' || %Q || substr(name,%d+18) " 230 "ELSE name END " 231 "WHERE (type!='index' OR tbl_name=%Q COLLATE nocase) " 232 "AND (name NOT LIKE 'sqliteX_%%' ESCAPE 'X' " 233 "OR (type='index' AND name LIKE 'sqliteX_autoindex%%' ESCAPE 'X'))" 234 , zDb, 235 zDb, zTabName, zName, (iDb==1), 236 zTabName, (iDb==1), zDb, zName, 237 zTabName, zName, 238 zName, nTabName, 239 zTabName 240 ); 241 242 #ifndef SQLITE_OMIT_AUTOINCREMENT 243 /* If the sqlite_sequence table exists in this database, then update 244 ** it with the new table name. 245 */ 246 if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){ 247 sqlite3NestedParse(pParse, 248 "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q", 249 zDb, zName, pTab->zName); 250 } 251 #endif 252 253 /* If the table being renamed is not itself part of the temp database, 254 ** edit view and trigger definitions within the temp database 255 ** as required. */ 256 if( iDb!=1 ){ 257 sqlite3NestedParse(pParse, 258 "UPDATE sqlite_temp_schema SET " 259 "sql = sqlite_rename_table(%Q, type, name, sql, %Q, %Q, 1), " 260 "tbl_name = " 261 "CASE WHEN tbl_name=%Q COLLATE nocase AND " 262 " sqlite_rename_test(%Q, sql, type, name, 1, 'after rename', 0) " 263 "THEN %Q ELSE tbl_name END " 264 "WHERE type IN ('view', 'trigger')" 265 , zDb, zTabName, zName, zTabName, zDb, zName); 266 } 267 268 /* If this is a virtual table, invoke the xRename() function if 269 ** one is defined. The xRename() callback will modify the names 270 ** of any resources used by the v-table implementation (including other 271 ** SQLite tables) that are identified by the name of the virtual table. 272 */ 273 #ifndef SQLITE_OMIT_VIRTUALTABLE 274 if( pVTab ){ 275 int i = ++pParse->nMem; 276 sqlite3VdbeLoadString(v, i, zName); 277 sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB); 278 } 279 #endif 280 281 renameReloadSchema(pParse, iDb, INITFLAG_AlterRename); 282 renameTestSchema(pParse, zDb, iDb==1, "after rename", 0); 283 284 exit_rename_table: 285 sqlite3SrcListDelete(db, pSrc); 286 sqlite3DbFree(db, zName); 287 } 288 289 /* 290 ** Write code that will raise an error if the table described by 291 ** zDb and zTab is not empty. 292 */ 293 static void sqlite3ErrorIfNotEmpty( 294 Parse *pParse, /* Parsing context */ 295 const char *zDb, /* Schema holding the table */ 296 const char *zTab, /* Table to check for empty */ 297 const char *zErr /* Error message text */ 298 ){ 299 sqlite3NestedParse(pParse, 300 "SELECT sqlite_fail(%Q, 1) FROM \"%w\".\"%w\"", 301 zErr, zDb, zTab 302 ); 303 } 304 305 /* 306 ** zCol is a column name used in an ALTER TABLE DROP, ADD or RENAME COLUMN 307 ** operation. zOp identifies the specific operation - "drop", "add", "rename 308 ** to" or "rename from". pTab is the table being altered. 309 ** 310 ** If pTab has a rowid and zCol is a rowid alias, then SQLITE_ERROR is 311 ** returned and an error message left in pParse. Or, if zCol is not an alias 312 ** for "rowid" or pTab is not an intkey table, then SQLITE_OK is returned. 313 */ 314 static int isRowidAlias( 315 Parse *pParse, 316 Table *pTab, 317 const char *zCol, 318 const char *zOp 319 ){ 320 if( HasRowid(pTab) && sqlite3IsRowid(zCol) ){ 321 sqlite3ErrorMsg(pParse, "cannot %s rowid alias: %s", zOp, zCol); 322 return SQLITE_ERROR; 323 } 324 return SQLITE_OK; 325 } 326 327 328 329 /* 330 ** Buffer pFrag, which is nFrag bytes in size, contains a fragment of 331 ** SQL that will be inserted into a CREATE TABLE statement. If successful, this 332 ** function returns the size of the buffer in bytes not including any trailing 333 ** whitespace, semicolons, "--" style comments or unterminated C-style 334 ** comments. Or, if an OOM occurs, it returns 0 and sets db->mallocFailed to 335 ** true. 336 ** 337 ** Terminated C-style comments at the end are preserved. "--" style 338 ** comments and unterminated C-style comments are removed because otherwise 339 ** inserting pFrag[] into the middle of a larger SQL statement without a 340 ** comment terminator will mess up its syntax. 341 */ 342 static int alterRtrimFragment( 343 sqlite3 *db, /* used to record OOM error */ 344 const char *pFrag, /* Buffer containing SQL fragment */ 345 int nFrag /* Size of pFrag in bytes */ 346 ){ 347 u8 *zTmp = (u8*)sqlite3MPrintf(db, "%.*s", nFrag, pFrag); 348 int iOff = 0; 349 int iEnd = 0; 350 351 if( zTmp==0 ) return 0; 352 353 while( 1 ){ 354 int t = 0; 355 int nToken = sqlite3GetToken(&zTmp[iOff], &t); 356 if( t==TK_ILLEGAL ) break; 357 if( t==TK_COMMENT ){ 358 /* Ignore all but properly terminated C-style comments */ 359 if( zTmp[iOff]=='/' && nToken>=4 360 && zTmp[iOff+nToken-2]=='*' && zTmp[iOff+nToken-1]=='/' 361 ){ 362 iEnd = iOff+nToken; 363 } 364 }else if( t!=TK_SPACE && t!=TK_SEMI ){ 365 iEnd = iOff+nToken; 366 } 367 iOff += nToken; 368 } 369 370 sqlite3DbFree(db, zTmp); 371 return iEnd; 372 } 373 374 /* 375 ** This function is called after an "ALTER TABLE ... ADD" statement 376 ** has been parsed. Argument pColDef contains the text of the new 377 ** column definition. 378 ** 379 ** The Table structure pParse->pNewTable was extended to include 380 ** the new column during parsing. 381 */ 382 void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){ 383 Table *pNew; /* Copy of pParse->pNewTable */ 384 Table *pTab; /* Table being altered */ 385 int iDb; /* Database number */ 386 const char *zDb; /* Database name */ 387 const char *zTab; /* Table name */ 388 char *zCol; /* Null-terminated column definition */ 389 int nCol; /* Size of zCol in bytes */ 390 Column *pCol; /* The new column */ 391 Expr *pDflt; /* Default value for the new column */ 392 sqlite3 *db; /* The database connection; */ 393 Vdbe *v; /* The prepared statement under construction */ 394 int r1; /* Temporary registers */ 395 396 db = pParse->db; 397 assert( db->pParse==pParse ); 398 if( pParse->nErr ) return; 399 assert( db->mallocFailed==0 ); 400 pNew = pParse->pNewTable; 401 assert( pNew ); 402 403 assert( sqlite3BtreeHoldsAllMutexes(db) ); 404 iDb = sqlite3SchemaToIndex(db, pNew->pSchema); 405 zDb = db->aDb[iDb].zDbSName; 406 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */ 407 pCol = &pNew->aCol[pNew->nCol-1]; 408 pDflt = sqlite3ColumnExpr(pNew, pCol); 409 pTab = sqlite3FindTable(db, zTab, zDb); 410 assert( pTab ); 411 412 #ifndef SQLITE_OMIT_AUTHORIZATION 413 /* Invoke the authorization callback. */ 414 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 415 return; 416 } 417 #endif 418 419 420 /* Check that the new column is not specified as PRIMARY KEY or UNIQUE, 421 ** or a rowid alias. If there is a NOT NULL constraint, then the default 422 ** value for the column must not be NULL. 423 */ 424 if( pCol->colFlags & COLFLAG_PRIMKEY ){ 425 sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column"); 426 return; 427 } 428 if( pNew->pIndex ){ 429 sqlite3ErrorMsg(pParse, 430 "Cannot add a UNIQUE column"); 431 return; 432 } 433 if( isRowidAlias(pParse, pTab, pCol->zCnName, "add") ) return; 434 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){ 435 assert( pDflt==0 || pDflt->op==TK_SPAN ); 436 437 /* Ensure the default expression, if any, is something that 438 ** sqlite3ValueFromExpr() can handle (i.e. not CURRENT_TIME etc.). 439 ** If the default expression evaluates to NULL, then set pDflt to 440 ** 0. This simplifies the checks below. */ 441 if( pDflt ){ 442 sqlite3_value *pVal = 0; 443 int rc; 444 rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal); 445 assert( rc==SQLITE_OK || rc==SQLITE_NOMEM ); 446 if( rc!=SQLITE_OK ){ 447 assert( db->mallocFailed == 1 ); 448 return; 449 } 450 if( !pVal ){ 451 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 452 "Cannot add a column with non-constant default"); 453 }else if( sqlite3_value_type(pVal)==SQLITE_NULL ){ 454 pDflt = 0; 455 } 456 sqlite3ValueFree(pVal); 457 } 458 459 assert( IsOrdinaryTable(pNew) ); 460 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){ 461 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 462 "Cannot add a REFERENCES column with non-NULL default value"); 463 } 464 if( pCol->notNull && !pDflt ){ 465 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, 466 "Cannot add a NOT NULL column with default value NULL"); 467 } 468 469 }else if( pCol->colFlags & COLFLAG_STORED ){ 470 sqlite3ErrorIfNotEmpty(pParse, zDb, zTab, "cannot add a STORED column"); 471 } 472 473 474 /* Modify the CREATE TABLE statement. */ 475 nCol = alterRtrimFragment(db, (char*)pColDef->z, pColDef->n); 476 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, nCol); 477 if( zCol ){ 478 /* substr() operations on characters, but addColOffset is in bytes. So we 479 ** have to use printf() to translate between these units: */ 480 assert( IsOrdinaryTable(pTab) ); 481 assert( IsOrdinaryTable(pNew) ); 482 sqlite3NestedParse(pParse, 483 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 484 "sql = printf('%%.%ds, ',sql) || %Q" 485 " || substr(sql,1+length(printf('%%.%ds',sql))) " 486 "WHERE type = 'table' AND name = %Q", 487 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset, 488 zTab 489 ); 490 sqlite3DbFree(db, zCol); 491 } 492 493 v = sqlite3GetVdbe(pParse); 494 if( v ){ 495 /* Make sure the schema version is at least 3. But do not upgrade 496 ** from less than 3 to 4, as that will corrupt any preexisting DESC 497 ** index. 498 */ 499 r1 = sqlite3GetTempReg(pParse); 500 sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT); 501 sqlite3VdbeUsesBtree(v, iDb); 502 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2); 503 sqlite3VdbeAddOp2(v, OP_IfPos, r1, sqlite3VdbeCurrentAddr(v)+2); 504 VdbeCoverage(v); 505 sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, 3); 506 sqlite3ReleaseTempReg(pParse, r1); 507 508 /* Reload the table definition */ 509 renameReloadSchema(pParse, iDb, INITFLAG_AlterAdd); 510 511 /* Verify that constraints are still satisfied */ 512 if( pNew->pCheck!=0 513 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0) 514 || (pTab->tabFlags & TF_Strict)!=0 515 ){ 516 pParse->colNamesSet = 1; 517 sqlite3NestedParse(pParse, 518 "SELECT CASE WHEN quick_check GLOB 'CHECK*'" 519 " THEN sqlite_fail('CHECK constraint failed', 1)" 520 " WHEN quick_check GLOB 'non-* value in*'" 521 " THEN sqlite_fail('type mismatch on DEFAULT', 1)" 522 " ELSE sqlite_fail('NOT NULL constraint failed', 1)" 523 " END" 524 " FROM pragma_quick_check(%Q,%Q)" 525 " WHERE quick_check GLOB 'CHECK*'" 526 " OR quick_check GLOB 'NULL*'" 527 " OR quick_check GLOB 'non-* value in*'", 528 zTab, zDb 529 ); 530 } 531 } 532 } 533 534 /* 535 ** This function is called by the parser after the table-name in 536 ** an "ALTER TABLE ADD" statement is parsed. Argument 537 ** pSrc is the full-name of the table being altered. 538 ** 539 ** This routine makes a (partial) copy of the Table structure 540 ** for the table being altered and sets Parse.pNewTable to point 541 ** to it. Routines called by the parser as the column definition 542 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 543 ** the copy. The copy of the Table structure is deleted by tokenize.c 544 ** after parsing is finished. 545 ** 546 ** Routine sqlite3AlterFinishAddColumn() will be called to complete 547 ** coding the "ALTER TABLE ... ADD" statement. 548 */ 549 void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){ 550 Table *pNew; 551 Table *pTab; 552 int iDb; 553 int i; 554 int nAlloc; 555 sqlite3 *db = pParse->db; 556 557 /* Look up the table being altered. */ 558 assert( pParse->pNewTable==0 ); 559 assert( sqlite3BtreeHoldsAllMutexes(db) ); 560 if( NEVER(db->mallocFailed) ) goto exit_begin_add_column; 561 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 562 if( !pTab ) goto exit_begin_add_column; 563 564 #ifndef SQLITE_OMIT_VIRTUALTABLE 565 if( IsVirtual(pTab) ){ 566 sqlite3ErrorMsg(pParse, "virtual tables may not be altered"); 567 goto exit_begin_add_column; 568 } 569 #endif 570 571 /* Make sure this is not an attempt to ALTER a view. */ 572 if( IsView(pTab) ){ 573 sqlite3ErrorMsg(pParse, "Cannot add a column to a view"); 574 goto exit_begin_add_column; 575 } 576 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ){ 577 goto exit_begin_add_column; 578 } 579 580 sqlite3MayAbort(pParse); 581 assert( IsOrdinaryTable(pTab) ); 582 assert( pTab->u.tab.addColOffset>0 ); 583 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 584 585 /* Put a copy of the Table struct in Parse.pNewTable for the 586 ** sqlite3AddColumn() function and friends to modify. But modify 587 ** the name by adding an "sqlite_altertab_" prefix. By adding this 588 ** prefix, we insure that the name will not collide with an existing 589 ** table because user table are not allowed to have the "sqlite_" 590 ** prefix on their name. 591 */ 592 pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table)); 593 if( !pNew ) goto exit_begin_add_column; 594 pParse->pNewTable = pNew; 595 pNew->nTabRef = 1; 596 pNew->nCol = pTab->nCol; 597 assert( pNew->nCol>0 ); 598 nAlloc = (((pNew->nCol-1)/8)*8)+8; 599 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 ); 600 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*(u32)nAlloc); 601 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName); 602 if( !pNew->aCol || !pNew->zName ){ 603 assert( db->mallocFailed ); 604 goto exit_begin_add_column; 605 } 606 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*(size_t)pNew->nCol); 607 for(i=0; inCol; i++){ 608 Column *pCol = &pNew->aCol[i]; 609 pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName); 610 pCol->hName = sqlite3StrIHash(pCol->zCnName); 611 } 612 assert( IsOrdinaryTable(pNew) ); 613 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0); 614 pNew->pSchema = db->aDb[iDb].pSchema; 615 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset; 616 assert( pNew->nTabRef==1 ); 617 618 exit_begin_add_column: 619 sqlite3SrcListDelete(db, pSrc); 620 return; 621 } 622 623 /* 624 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN 625 ** command. This function checks if the table is a view or virtual 626 ** table (columns of views or virtual tables may not be renamed). If so, 627 ** it loads an error message into pParse and returns non-zero. 628 ** 629 ** Or, if pTab is not a view or virtual table, zero is returned. 630 */ 631 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) 632 static int isRealTable(Parse *pParse, Table *pTab, int iOp){ 633 const char *zType = 0; 634 #ifndef SQLITE_OMIT_VIEW 635 if( IsView(pTab) ){ 636 zType = "view"; 637 } 638 #endif 639 #ifndef SQLITE_OMIT_VIRTUALTABLE 640 if( IsVirtual(pTab) ){ 641 zType = "virtual table"; 642 } 643 #endif 644 if( zType ){ 645 const char *azMsg[] = { 646 "rename columns of", "drop column from", "edit constraints of" 647 }; 648 assert( iOp>=0 && iOpzName 651 ); 652 return 1; 653 } 654 return 0; 655 } 656 #else /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */ 657 # define isRealTable(x,y,z) (0) 658 #endif 659 660 /* 661 ** Handles the following parser reduction: 662 ** 663 ** cmd ::= ALTER TABLE pSrc RENAME COLUMN pOld TO pNew 664 */ 665 void sqlite3AlterRenameColumn( 666 Parse *pParse, /* Parsing context */ 667 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */ 668 Token *pOld, /* Name of column being changed */ 669 Token *pNew /* New column name */ 670 ){ 671 sqlite3 *db = pParse->db; /* Database connection */ 672 Table *pTab; /* Table being updated */ 673 int iCol; /* Index of column being renamed */ 674 char *zOld = 0; /* Old column name */ 675 char *zNew = 0; /* New column name */ 676 const char *zDb; /* Name of schema containing the table */ 677 int iSchema; /* Index of the schema */ 678 int bQuote; /* True to quote the new name */ 679 680 /* Locate the table to be altered */ 681 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 682 if( !pTab ) goto exit_rename_column; 683 684 /* Cannot alter a system table */ 685 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_rename_column; 686 if( SQLITE_OK!=isRealTable(pParse, pTab, 0) ) goto exit_rename_column; 687 688 /* Which schema holds the table to be altered */ 689 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema); 690 assert( iSchema>=0 ); 691 zDb = db->aDb[iSchema].zDbSName; 692 693 #ifndef SQLITE_OMIT_AUTHORIZATION 694 /* Invoke the authorization callback. */ 695 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){ 696 goto exit_rename_column; 697 } 698 #endif 699 700 /* Make sure the old name really is a column name in the table to be 701 ** altered. Set iCol to be the index of the column being renamed */ 702 zOld = sqlite3NameFromToken(db, pOld); 703 if( !zOld ) goto exit_rename_column; 704 iCol = sqlite3ColumnIndex(pTab, zOld); 705 if( iCol<0 ){ 706 sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pOld); 707 goto exit_rename_column; 708 } 709 710 /* Ensure the schema contains no double-quoted strings */ 711 renameTestSchema(pParse, zDb, iSchema==1, "", 0); 712 renameFixQuotes(pParse, zDb, iSchema==1); 713 714 /* Do the rename operation using a recursive UPDATE statement that 715 ** uses the sqlite_rename_column() SQL function to compute the new 716 ** CREATE statement text for the sqlite_schema table. 717 */ 718 sqlite3MayAbort(pParse); 719 zNew = sqlite3NameFromToken(db, pNew); 720 if( !zNew ) goto exit_rename_column; 721 if( isRowidAlias(pParse, pTab, zOld, "rename from") ) goto exit_rename_column; 722 if( isRowidAlias(pParse, pTab, zNew, "rename to") ) goto exit_rename_column; 723 assert( pNew->n>0 ); 724 bQuote = sqlite3Isquote(pNew->z[0]); 725 sqlite3NestedParse(pParse, 726 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 727 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, %d) " 728 "WHERE name NOT LIKE 'sqliteX_%%' ESCAPE 'X' " 729 " AND (type != 'index' OR tbl_name = %Q)", 730 zDb, 731 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1, 732 pTab->zName 733 ); 734 if( iSchema!=1 ){ 735 sqlite3NestedParse(pParse, 736 "UPDATE temp." LEGACY_SCHEMA_TABLE " SET " 737 "sql = sqlite_rename_column(sql, type, name, %Q, %Q, %d, %Q, %d, 1) " 738 "WHERE type IN ('trigger', 'view')", 739 zDb, pTab->zName, iCol, zNew, bQuote 740 ); 741 } 742 743 /* Drop and reload the database schema. */ 744 renameReloadSchema(pParse, iSchema, INITFLAG_AlterRename); 745 renameTestSchema(pParse, zDb, iSchema==1, "after rename", 1); 746 747 exit_rename_column: 748 sqlite3SrcListDelete(db, pSrc); 749 sqlite3DbFree(db, zOld); 750 sqlite3DbFree(db, zNew); 751 return; 752 } 753 754 /* 755 ** Each RenameToken object maps an element of the parse tree into 756 ** the token that generated that element. The parse tree element 757 ** might be one of: 758 ** 759 ** * A pointer to an Expr that represents an ID 760 ** * The name of a table column in Column.zName 761 ** 762 ** A list of RenameToken objects can be constructed during parsing. 763 ** Each new object is created by sqlite3RenameTokenMap(). 764 ** As the parse tree is transformed, the sqlite3RenameTokenRemap() 765 ** routine is used to keep the mapping current. 766 ** 767 ** After the parse finishes, renameTokenFind() routine can be used 768 ** to look up the actual token value that created some element in 769 ** the parse tree. 770 */ 771 struct RenameToken { 772 const void *p; /* Parse tree element created by token t */ 773 Token t; /* The token that created parse tree element p */ 774 RenameToken *pNext; /* Next is a list of all RenameToken objects */ 775 }; 776 777 /* 778 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed 779 ** down into the Walker. 780 */ 781 typedef struct RenameCtx RenameCtx; 782 struct RenameCtx { 783 RenameToken *pList; /* List of tokens to overwrite */ 784 int nList; /* Number of tokens in pList */ 785 int iCol; /* Index of column being renamed */ 786 Table *pTab; /* Table being ALTERed */ 787 const char *zOld; /* Old column name */ 788 }; 789 790 #ifdef SQLITE_DEBUG 791 /* 792 ** This function is only for debugging. It performs two tasks: 793 ** 794 ** 1. Checks that pointer pPtr does not already appear in the 795 ** rename-token list. 796 ** 797 ** 2. Dereferences each pointer in the rename-token list. 798 ** 799 ** The second is most effective when debugging under valgrind or 800 ** address-sanitizer or similar. If any of these pointers no longer 801 ** point to valid objects, an exception is raised by the memory-checking 802 ** tool. 803 ** 804 ** The point of this is to prevent comparisons of invalid pointer values. 805 ** Even though this always seems to work, it is undefined according to the 806 ** C standard. Example of undefined comparison: 807 ** 808 ** sqlite3_free(x); 809 ** if( x==y ) ... 810 ** 811 ** Technically, as x no longer points into a valid object or to the byte 812 ** following a valid object, it may not be used in comparison operations. 813 */ 814 static void renameTokenCheckAll(Parse *pParse, const void *pPtr){ 815 assert( pParse==pParse->db->pParse ); 816 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 ); 817 if( pParse->nErr==0 ){ 818 const RenameToken *p; 819 u32 i = 1; 820 for(p=pParse->pRename; p; p=p->pNext){ 821 if( p->p ){ 822 assert( p->p!=pPtr ); 823 i += *(u8*)(p->p) | 1; 824 } 825 } 826 assert( i>0 ); 827 } 828 } 829 #else 830 # define renameTokenCheckAll(x,y) 831 #endif 832 833 /* 834 ** Remember that the parser tree element pPtr was created using 835 ** the token pToken. 836 ** 837 ** In other words, construct a new RenameToken object and add it 838 ** to the list of RenameToken objects currently being built up 839 ** in pParse->pRename. 840 ** 841 ** The pPtr argument is returned so that this routine can be used 842 ** with tail recursion in tokenExpr() routine, for a small performance 843 ** improvement. 844 */ 845 const void *sqlite3RenameTokenMap( 846 Parse *pParse, 847 const void *pPtr, 848 const Token *pToken 849 ){ 850 RenameToken *pNew; 851 assert( pPtr || pParse->db->mallocFailed ); 852 renameTokenCheckAll(pParse, pPtr); 853 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){ 854 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken)); 855 if( pNew ){ 856 pNew->p = pPtr; 857 pNew->t = *pToken; 858 pNew->pNext = pParse->pRename; 859 pParse->pRename = pNew; 860 } 861 } 862 863 return pPtr; 864 } 865 866 /* 867 ** It is assumed that there is already a RenameToken object associated 868 ** with parse tree element pFrom. This function remaps the associated token 869 ** to parse tree element pTo. 870 */ 871 void sqlite3RenameTokenRemap(Parse *pParse, const void *pTo, const void *pFrom){ 872 RenameToken *p; 873 renameTokenCheckAll(pParse, pTo); 874 for(p=pParse->pRename; p; p=p->pNext){ 875 if( p->p==pFrom ){ 876 p->p = pTo; 877 break; 878 } 879 } 880 } 881 882 /* 883 ** Walker callback used by sqlite3RenameExprUnmap(). 884 */ 885 static int renameUnmapExprCb(Walker *pWalker, Expr *pExpr){ 886 Parse *pParse = pWalker->pParse; 887 sqlite3RenameTokenRemap(pParse, 0, (const void*)pExpr); 888 if( ExprUseYTab(pExpr) ){ 889 sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab); 890 } 891 return WRC_Continue; 892 } 893 894 /* 895 ** Iterate through the Select objects that are part of WITH clauses attached 896 ** to select statement pSelect. 897 */ 898 static void renameWalkWith(Walker *pWalker, Select *pSelect){ 899 With *pWith = pSelect->pWith; 900 if( pWith ){ 901 Parse *pParse = pWalker->pParse; 902 int i; 903 With *pCopy = 0; 904 assert( pWith->nCte>0 ); 905 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){ 906 /* Push a copy of the With object onto the with-stack. We use a copy 907 ** here as the original will be expanded and resolved (flags SF_Expanded 908 ** and SF_Resolved) below. And the parser code that uses the with-stack 909 ** fails if the Select objects on it have already been expanded and 910 ** resolved. */ 911 pCopy = sqlite3WithDup(pParse->db, pWith); 912 pCopy = sqlite3WithPush(pParse, pCopy, 1); 913 } 914 for(i=0; inCte; i++){ 915 Select *p = pWith->a[i].pSelect; 916 NameContext sNC; 917 memset(&sNC, 0, sizeof(sNC)); 918 sNC.pParse = pParse; 919 if( pCopy ) sqlite3SelectPrep(sNC.pParse, p, &sNC); 920 if( sNC.pParse->db->mallocFailed ) return; 921 sqlite3WalkSelect(pWalker, p); 922 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols); 923 } 924 if( pCopy && pParse->pWith==pCopy ){ 925 pParse->pWith = pCopy->pOuter; 926 } 927 } 928 } 929 930 /* 931 ** Unmap all tokens in the IdList object passed as the second argument. 932 */ 933 static void unmapColumnIdlistNames( 934 Parse *pParse, 935 const IdList *pIdList 936 ){ 937 int ii; 938 assert( pIdList!=0 ); 939 for(ii=0; iinId; ii++){ 940 sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName); 941 } 942 } 943 944 /* 945 ** Walker callback used by sqlite3RenameExprUnmap(). 946 */ 947 static int renameUnmapSelectCb(Walker *pWalker, Select *p){ 948 Parse *pParse = pWalker->pParse; 949 int i; 950 if( pParse->nErr ) return WRC_Abort; 951 testcase( p->selFlags & SF_View ); 952 testcase( p->selFlags & SF_CopyCte ); 953 if( p->selFlags & (SF_View|SF_CopyCte) ){ 954 return WRC_Prune; 955 } 956 if( ALWAYS(p->pEList) ){ 957 ExprList *pList = p->pEList; 958 for(i=0; inExpr; i++){ 959 if( pList->a[i].zEName && pList->a[i].fg.eEName==ENAME_NAME ){ 960 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName); 961 } 962 } 963 } 964 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */ 965 SrcList *pSrc = p->pSrc; 966 for(i=0; inSrc; i++){ 967 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName); 968 if( pSrc->a[i].fg.isUsing==0 ){ 969 sqlite3WalkExpr(pWalker, pSrc->a[i].u3.pOn); 970 }else{ 971 unmapColumnIdlistNames(pParse, pSrc->a[i].u3.pUsing); 972 } 973 } 974 } 975 976 renameWalkWith(pWalker, p); 977 return WRC_Continue; 978 } 979 980 /* 981 ** Remove all nodes that are part of expression pExpr from the rename list. 982 */ 983 void sqlite3RenameExprUnmap(Parse *pParse, Expr *pExpr){ 984 u8 eMode = pParse->eParseMode; 985 Walker sWalker; 986 memset(&sWalker, 0, sizeof(Walker)); 987 sWalker.pParse = pParse; 988 sWalker.xExprCallback = renameUnmapExprCb; 989 sWalker.xSelectCallback = renameUnmapSelectCb; 990 pParse->eParseMode = PARSE_MODE_UNMAP; 991 sqlite3WalkExpr(&sWalker, pExpr); 992 pParse->eParseMode = eMode; 993 } 994 995 /* 996 ** Remove all nodes that are part of expression-list pEList from the 997 ** rename list. 998 */ 999 void sqlite3RenameExprlistUnmap(Parse *pParse, ExprList *pEList){ 1000 if( pEList ){ 1001 int i; 1002 Walker sWalker; 1003 memset(&sWalker, 0, sizeof(Walker)); 1004 sWalker.pParse = pParse; 1005 sWalker.xExprCallback = renameUnmapExprCb; 1006 sqlite3WalkExprList(&sWalker, pEList); 1007 for(i=0; inExpr; i++){ 1008 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) ){ 1009 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName); 1010 } 1011 } 1012 } 1013 } 1014 1015 /* 1016 ** Free the list of RenameToken objects given in the second argument 1017 */ 1018 static void renameTokenFree(sqlite3 *db, RenameToken *pToken){ 1019 RenameToken *pNext; 1020 RenameToken *p; 1021 for(p=pToken; p; p=pNext){ 1022 pNext = p->pNext; 1023 sqlite3DbFree(db, p); 1024 } 1025 } 1026 1027 /* 1028 ** Search the Parse object passed as the first argument for a RenameToken 1029 ** object associated with parse tree element pPtr. If found, return a pointer 1030 ** to it. Otherwise, return NULL. 1031 ** 1032 ** If the second argument passed to this function is not NULL and a matching 1033 ** RenameToken object is found, remove it from the Parse object and add it to 1034 ** the list maintained by the RenameCtx object. 1035 */ 1036 static RenameToken *renameTokenFind( 1037 Parse *pParse, 1038 struct RenameCtx *pCtx, 1039 const void *pPtr 1040 ){ 1041 RenameToken **pp; 1042 if( NEVER(pPtr==0) ){ 1043 return 0; 1044 } 1045 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){ 1046 if( (*pp)->p==pPtr ){ 1047 RenameToken *pToken = *pp; 1048 if( pCtx ){ 1049 *pp = pToken->pNext; 1050 pToken->pNext = pCtx->pList; 1051 pCtx->pList = pToken; 1052 pCtx->nList++; 1053 } 1054 return pToken; 1055 } 1056 } 1057 return 0; 1058 } 1059 1060 /* 1061 ** This is a Walker select callback. It does nothing. It is only required 1062 ** because without a dummy callback, sqlite3WalkExpr() and similar do not 1063 ** descend into sub-select statements. 1064 */ 1065 static int renameColumnSelectCb(Walker *pWalker, Select *p){ 1066 if( p->selFlags & (SF_View|SF_CopyCte) ){ 1067 testcase( p->selFlags & SF_View ); 1068 testcase( p->selFlags & SF_CopyCte ); 1069 return WRC_Prune; 1070 } 1071 renameWalkWith(pWalker, p); 1072 return WRC_Continue; 1073 } 1074 1075 /* 1076 ** This is a Walker expression callback. 1077 ** 1078 ** For every TK_COLUMN node in the expression tree, search to see 1079 ** if the column being references is the column being renamed by an 1080 ** ALTER TABLE statement. If it is, then attach its associated 1081 ** RenameToken object to the list of RenameToken objects being 1082 ** constructed in RenameCtx object at pWalker->u.pRename. 1083 */ 1084 static int renameColumnExprCb(Walker *pWalker, Expr *pExpr){ 1085 RenameCtx *p = pWalker->u.pRename; 1086 if( pExpr->op==TK_TRIGGER 1087 && pExpr->iColumn==p->iCol 1088 && pWalker->pParse->pTriggerTab==p->pTab 1089 ){ 1090 renameTokenFind(pWalker->pParse, p, (void*)pExpr); 1091 }else if( pExpr->op==TK_COLUMN 1092 && pExpr->iColumn==p->iCol 1093 && ALWAYS(ExprUseYTab(pExpr)) 1094 && p->pTab==pExpr->y.pTab 1095 ){ 1096 renameTokenFind(pWalker->pParse, p, (void*)pExpr); 1097 } 1098 return WRC_Continue; 1099 } 1100 1101 /* 1102 ** The RenameCtx contains a list of tokens that reference a column that 1103 ** is being renamed by an ALTER TABLE statement. Return the "last" 1104 ** RenameToken in the RenameCtx and remove that RenameToken from the 1105 ** RenameContext. "Last" means the last RenameToken encountered when 1106 ** the input SQL is parsed from left to right. Repeated calls to this routine 1107 ** return all column name tokens in the order that they are encountered 1108 ** in the SQL statement. 1109 */ 1110 static RenameToken *renameColumnTokenNext(RenameCtx *pCtx){ 1111 RenameToken *pBest = pCtx->pList; 1112 RenameToken *pToken; 1113 RenameToken **pp; 1114 1115 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){ 1116 if( pToken->t.z>pBest->t.z ) pBest = pToken; 1117 } 1118 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext); 1119 *pp = pBest->pNext; 1120 1121 return pBest; 1122 } 1123 1124 /* 1125 ** Set the error message of the context passed as the first argument to 1126 ** the result of formatting zFmt using printf() style formatting. 1127 */ 1128 static void errorMPrintf(sqlite3_context *pCtx, const char *zFmt, ...){ 1129 sqlite3 *db = sqlite3_context_db_handle(pCtx); 1130 char *zErr = 0; 1131 va_list ap; 1132 va_start(ap, zFmt); 1133 zErr = sqlite3VMPrintf(db, zFmt, ap); 1134 va_end(ap); 1135 if( zErr ){ 1136 sqlite3_result_error(pCtx, zErr, -1); 1137 sqlite3DbFree(db, zErr); 1138 }else{ 1139 sqlite3_result_error_nomem(pCtx); 1140 } 1141 } 1142 1143 /* 1144 ** An error occurred while parsing or otherwise processing a database 1145 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an 1146 ** ALTER TABLE RENAME COLUMN program. The error message emitted by the 1147 ** sub-routine is currently stored in pParse->zErrMsg. This function 1148 ** adds context to the error message and then stores it in pCtx. 1149 */ 1150 static void renameColumnParseError( 1151 sqlite3_context *pCtx, 1152 const char *zWhen, 1153 sqlite3_value *pType, 1154 sqlite3_value *pObject, 1155 Parse *pParse 1156 ){ 1157 const char *zT = (const char*)sqlite3_value_text(pType); 1158 const char *zN = (const char*)sqlite3_value_text(pObject); 1159 char *zErr; 1160 1161 zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s", 1162 zT, zN, (zWhen[0] ? " " : ""), zWhen, 1163 pParse->zErrMsg 1164 ); 1165 sqlite3_result_error(pCtx, zErr, -1); 1166 sqlite3DbFree(pParse->db, zErr); 1167 } 1168 1169 /* 1170 ** For each name in the the expression-list pEList (i.e. each 1171 ** pEList->a[i].zName) that matches the string in zOld, extract the 1172 ** corresponding rename-token from Parse object pParse and add it 1173 ** to the RenameCtx pCtx. 1174 */ 1175 static void renameColumnElistNames( 1176 Parse *pParse, 1177 RenameCtx *pCtx, 1178 const ExprList *pEList, 1179 const char *zOld 1180 ){ 1181 if( pEList ){ 1182 int i; 1183 for(i=0; inExpr; i++){ 1184 const char *zName = pEList->a[i].zEName; 1185 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) 1186 && ALWAYS(zName!=0) 1187 && 0==sqlite3_stricmp(zName, zOld) 1188 ){ 1189 renameTokenFind(pParse, pCtx, (const void*)zName); 1190 } 1191 } 1192 } 1193 } 1194 1195 /* 1196 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName) 1197 ** that matches the string in zOld, extract the corresponding rename-token 1198 ** from Parse object pParse and add it to the RenameCtx pCtx. 1199 */ 1200 static void renameColumnIdlistNames( 1201 Parse *pParse, 1202 RenameCtx *pCtx, 1203 const IdList *pIdList, 1204 const char *zOld 1205 ){ 1206 if( pIdList ){ 1207 int i; 1208 for(i=0; inId; i++){ 1209 const char *zName = pIdList->a[i].zName; 1210 if( 0==sqlite3_stricmp(zName, zOld) ){ 1211 renameTokenFind(pParse, pCtx, (const void*)zName); 1212 } 1213 } 1214 } 1215 } 1216 1217 1218 /* 1219 ** Parse the SQL statement zSql using Parse object (*p). The Parse object 1220 ** is initialized by this function before it is used. 1221 */ 1222 static int renameParseSql( 1223 Parse *p, /* Memory to use for Parse object */ 1224 const char *zDb, /* Name of schema SQL belongs to */ 1225 sqlite3 *db, /* Database handle */ 1226 const char *zSql, /* SQL to parse */ 1227 int bTemp /* True if SQL is from temp schema */ 1228 ){ 1229 int rc; 1230 u64 flags; 1231 1232 sqlite3ParseObjectInit(p, db); 1233 if( zSql==0 ){ 1234 return SQLITE_NOMEM; 1235 } 1236 if( sqlite3StrNICmp(zSql,"CREATE ",7)!=0 ){ 1237 return SQLITE_CORRUPT_BKPT; 1238 } 1239 if( bTemp ){ 1240 db->init.iDb = 1; 1241 }else{ 1242 int iDb = sqlite3FindDbName(db, zDb); 1243 assert( iDb>=0 && iDb<=0xff ); 1244 db->init.iDb = (u8)iDb; 1245 } 1246 p->eParseMode = PARSE_MODE_RENAME; 1247 p->db = db; 1248 p->nQueryLoop = 1; 1249 flags = db->flags; 1250 testcase( (db->flags & SQLITE_Comments)==0 && strstr(zSql," /* ")!=0 ); 1251 db->flags |= SQLITE_Comments; 1252 rc = sqlite3RunParser(p, zSql); 1253 db->flags = flags; 1254 if( db->mallocFailed ) rc = SQLITE_NOMEM; 1255 if( rc==SQLITE_OK 1256 && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0) 1257 ){ 1258 rc = SQLITE_CORRUPT_BKPT; 1259 } 1260 1261 #ifdef SQLITE_DEBUG 1262 /* Ensure that all mappings in the Parse.pRename list really do map to 1263 ** a part of the input string. */ 1264 if( rc==SQLITE_OK ){ 1265 int nSql = sqlite3Strlen30(zSql); 1266 RenameToken *pToken; 1267 for(pToken=p->pRename; pToken; pToken=pToken->pNext){ 1268 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] ); 1269 } 1270 } 1271 #endif 1272 1273 db->init.iDb = 0; 1274 return rc; 1275 } 1276 1277 /* 1278 ** This function edits SQL statement zSql, replacing each token identified 1279 ** by the linked list pRename with the text of zNew. If argument bQuote is 1280 ** true, then zNew is always quoted first. If no error occurs, the result 1281 ** is loaded into context object pCtx as the result. 1282 ** 1283 ** Or, if an error occurs (i.e. an OOM condition), an error is left in 1284 ** pCtx and an SQLite error code returned. 1285 */ 1286 static int renameEditSql( 1287 sqlite3_context *pCtx, /* Return result here */ 1288 RenameCtx *pRename, /* Rename context */ 1289 const char *zSql, /* SQL statement to edit */ 1290 const char *zNew, /* New token text */ 1291 int bQuote /* True to always quote token */ 1292 ){ 1293 i64 nNew = sqlite3Strlen30(zNew); 1294 i64 nSql = sqlite3Strlen30(zSql); 1295 sqlite3 *db = sqlite3_context_db_handle(pCtx); 1296 int rc = SQLITE_OK; 1297 char *zQuot = 0; 1298 char *zOut; 1299 i64 nQuot = 0; 1300 char *zBuf1 = 0; 1301 char *zBuf2 = 0; 1302 1303 if( zNew ){ 1304 /* Set zQuot to point to a buffer containing a quoted copy of the 1305 ** identifier zNew. If the corresponding identifier in the original 1306 ** ALTER TABLE statement was quoted (bQuote==1), then set zNew to 1307 ** point to zQuot so that all substitutions are made using the 1308 ** quoted version of the new column name. */ 1309 zQuot = sqlite3MPrintf(db, "\"%w\" ", zNew); 1310 if( zQuot==0 ){ 1311 return SQLITE_NOMEM; 1312 }else{ 1313 nQuot = sqlite3Strlen30(zQuot)-1; 1314 } 1315 1316 assert( nQuot>=nNew && nSql>=0 && nNew>=0 ); 1317 zOut = sqlite3DbMallocZero(db, (u64)nSql + pRename->nList*(u64)nQuot + 1); 1318 }else{ 1319 assert( nSql>0 ); 1320 zOut = (char*)sqlite3DbMallocZero(db, (2*(u64)nSql + 1) * 3); 1321 if( zOut ){ 1322 zBuf1 = &zOut[nSql*2+1]; 1323 zBuf2 = &zOut[nSql*4+2]; 1324 } 1325 } 1326 1327 /* At this point pRename->pList contains a list of RenameToken objects 1328 ** corresponding to all tokens in the input SQL that must be replaced 1329 ** with the new column name, or with single-quoted versions of themselves. 1330 ** All that remains is to construct and return the edited SQL string. */ 1331 if( zOut ){ 1332 i64 nOut = nSql; 1333 assert( nSql>0 ); 1334 memcpy(zOut, zSql, (size_t)nSql); 1335 while( pRename->pList ){ 1336 int iOff; /* Offset of token to replace in zOut */ 1337 i64 nReplace; 1338 const char *zReplace; 1339 RenameToken *pBest = renameColumnTokenNext(pRename); 1340 1341 if( zNew ){ 1342 if( bQuote==0 && sqlite3IsIdChar(*(u8*)pBest->t.z) ){ 1343 nReplace = nNew; 1344 zReplace = zNew; 1345 }else{ 1346 nReplace = nQuot; 1347 zReplace = zQuot; 1348 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++; 1349 } 1350 }else{ 1351 /* Dequote the double-quoted token. Then requote it again, this time 1352 ** using single quotes. If the character immediately following the 1353 ** original token within the input SQL was a single quote ('), then 1354 ** add another space after the new, single-quoted version of the 1355 ** token. This is so that (SELECT "string"'alias') maps to 1356 ** (SELECT 'string' 'alias'), and not (SELECT 'string''alias'). */ 1357 memcpy(zBuf1, pBest->t.z, pBest->t.n); 1358 zBuf1[pBest->t.n] = 0; 1359 sqlite3Dequote(zBuf1); 1360 assert( nSql < 0x15555554 /* otherwise malloc would have failed */ ); 1361 sqlite3_snprintf((int)(nSql*2), zBuf2, "%Q%s", zBuf1, 1362 pBest->t.z[pBest->t.n]=='\'' ? " " : "" 1363 ); 1364 zReplace = zBuf2; 1365 nReplace = sqlite3Strlen30(zReplace); 1366 } 1367 1368 iOff = (int)(pBest->t.z - zSql); 1369 if( pBest->t.n!=nReplace ){ 1370 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n], 1371 nOut - (iOff + pBest->t.n) 1372 ); 1373 nOut += nReplace - pBest->t.n; 1374 zOut[nOut] = '\0'; 1375 } 1376 memcpy(&zOut[iOff], zReplace, nReplace); 1377 sqlite3DbFree(db, pBest); 1378 } 1379 1380 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT); 1381 sqlite3DbFree(db, zOut); 1382 }else{ 1383 rc = SQLITE_NOMEM; 1384 } 1385 1386 sqlite3_free(zQuot); 1387 return rc; 1388 } 1389 1390 /* 1391 ** Set all pEList->a[].fg.eEName fields in the expression-list to val. 1392 */ 1393 static void renameSetENames(ExprList *pEList, int val){ 1394 assert( val==ENAME_NAME || val==ENAME_TAB || val==ENAME_SPAN ); 1395 if( pEList ){ 1396 int i; 1397 for(i=0; inExpr; i++){ 1398 assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME ); 1399 pEList->a[i].fg.eEName = val&0x3; 1400 } 1401 } 1402 } 1403 1404 /* 1405 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming 1406 ** it was read from the schema of database zDb. Return SQLITE_OK if 1407 ** successful. Otherwise, return an SQLite error code and leave an error 1408 ** message in the Parse object. 1409 */ 1410 static int renameResolveTrigger(Parse *pParse){ 1411 sqlite3 *db = pParse->db; 1412 Trigger *pNew = pParse->pNewTrigger; 1413 TriggerStep *pStep; 1414 NameContext sNC; 1415 int rc = SQLITE_OK; 1416 1417 memset(&sNC, 0, sizeof(sNC)); 1418 sNC.pParse = pParse; 1419 assert( pNew->pTabSchema ); 1420 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table, 1421 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName 1422 ); 1423 pParse->eTriggerOp = pNew->op; 1424 /* ALWAYS() because if the table of the trigger does not exist, the 1425 ** error would have been hit before this point */ 1426 if( ALWAYS(pParse->pTriggerTab) ){ 1427 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab)!=0; 1428 } 1429 1430 /* Resolve symbols in WHEN clause */ 1431 if( rc==SQLITE_OK && pNew->pWhen ){ 1432 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen); 1433 } 1434 1435 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){ 1436 if( pStep->pSelect ){ 1437 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC); 1438 if( pParse->nErr ) rc = pParse->rc; 1439 } 1440 if( rc==SQLITE_OK && pStep->pSrc ){ 1441 SrcList *pSrc = sqlite3SrcListDup(db, pStep->pSrc, 0); 1442 if( pSrc ){ 1443 Select *pSel = sqlite3SelectNew( 1444 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0 1445 ); 1446 Upsert *pUpsert = 0; 1447 if( pSel==0 ){ 1448 pStep->pExprList = 0; 1449 pSrc = 0; 1450 rc = SQLITE_NOMEM; 1451 }else{ 1452 /* pStep->pExprList contains an expression-list used for an UPDATE 1453 ** statement. So the a[].zEName values are the RHS of the 1454 ** " = " clauses of the UPDATE statement. So, before 1455 ** running SelectPrep(), change all the eEName values in 1456 ** pStep->pExprList to ENAME_SPAN (from their current value of 1457 ** ENAME_NAME). This is to prevent any ids in ON() clauses that are 1458 ** part of pSrc from being incorrectly resolved against the 1459 ** a[].zEName values as if they were column aliases. */ 1460 renameSetENames(pStep->pExprList, ENAME_SPAN); 1461 sqlite3SelectPrep(pParse, pSel, 0); 1462 renameSetENames(pStep->pExprList, ENAME_NAME); 1463 rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK; 1464 assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList ); 1465 assert( pSrc==pSel->pSrc ); 1466 if( pStep->pExprList ) pSel->pEList = 0; 1467 pSel->pSrc = 0; 1468 sqlite3SelectDelete(db, pSel); 1469 } 1470 1471 sNC.pSrcList = pSrc; 1472 if( ALWAYS(pStep->pSrc) ){ 1473 int i; 1474 for(i=0; ipSrc->nSrc && rc==SQLITE_OK; i++){ 1475 SrcItem *p = &pStep->pSrc->a[i]; 1476 if( p->fg.isSubquery ){ 1477 assert( p->u4.pSubq!=0 ); 1478 sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0); 1479 } 1480 if( p->fg.isUsing==0 ){ 1481 rc = sqlite3ResolveExprNames(&sNC, p->u3.pOn); 1482 } 1483 } 1484 } 1485 if( db->mallocFailed ){ 1486 rc = SQLITE_NOMEM; 1487 } 1488 if( rc==SQLITE_OK && pStep->pWhere ){ 1489 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere); 1490 } 1491 if( rc==SQLITE_OK ){ 1492 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList); 1493 } 1494 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) ); 1495 for(pUpsert=pStep->pUpsert; 1496 pUpsert && rc==SQLITE_OK; 1497 pUpsert=pUpsert->pNextUpsert 1498 ){ 1499 pUpsert->pUpsertSrc = pSrc; 1500 sNC.uNC.pUpsert = pUpsert; 1501 sNC.ncFlags = NC_UUpsert; 1502 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget); 1503 if( rc==SQLITE_OK ){ 1504 ExprList *pUpsertSet = pUpsert->pUpsertSet; 1505 rc = sqlite3ResolveExprListNames(&sNC, pUpsertSet); 1506 } 1507 if( rc==SQLITE_OK ){ 1508 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere); 1509 } 1510 if( rc==SQLITE_OK ){ 1511 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere); 1512 } 1513 sNC.ncFlags = 0; 1514 } 1515 sNC.pSrcList = 0; 1516 sqlite3SrcListDelete(db, pSrc); 1517 }else{ 1518 rc = SQLITE_NOMEM; 1519 } 1520 } 1521 } 1522 return rc; 1523 } 1524 1525 /* 1526 ** Invoke sqlite3WalkExpr() or sqlite3WalkSelect() on all Select or Expr 1527 ** objects that are part of the trigger passed as the second argument. 1528 */ 1529 static void renameWalkTrigger(Walker *pWalker, Trigger *pTrigger){ 1530 TriggerStep *pStep; 1531 1532 /* Find tokens to edit in WHEN clause */ 1533 sqlite3WalkExpr(pWalker, pTrigger->pWhen); 1534 1535 /* Find tokens to edit in trigger steps */ 1536 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ 1537 Upsert *pUpsert = 0; 1538 sqlite3WalkSelect(pWalker, pStep->pSelect); 1539 sqlite3WalkExpr(pWalker, pStep->pWhere); 1540 sqlite3WalkExprList(pWalker, pStep->pExprList); 1541 for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){ 1542 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget); 1543 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet); 1544 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere); 1545 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere); 1546 } 1547 if( pStep->pSrc ){ 1548 int i; 1549 SrcList *pSrc = pStep->pSrc; 1550 for(i=0; inSrc; i++){ 1551 SrcItem *p = &pSrc->a[i]; 1552 if( p->fg.isSubquery ){ 1553 assert( p->u4.pSubq!=0 ); 1554 sqlite3WalkSelect(pWalker, p->u4.pSubq->pSelect); 1555 } 1556 if( p->fg.isUsing==0 ){ 1557 sqlite3WalkExpr(pWalker, p->u3.pOn); 1558 } 1559 } 1560 } 1561 } 1562 } 1563 1564 /* 1565 ** Free the contents of Parse object (*pParse). Do not free the memory 1566 ** occupied by the Parse object itself. 1567 */ 1568 static void renameParseCleanup(Parse *pParse){ 1569 sqlite3 *db = pParse->db; 1570 Index *pIdx; 1571 if( pParse->pVdbe ){ 1572 sqlite3VdbeFinalize(pParse->pVdbe); 1573 } 1574 sqlite3DeleteTable(db, pParse->pNewTable); 1575 while( (pIdx = pParse->pNewIndex)!=0 ){ 1576 pParse->pNewIndex = pIdx->pNext; 1577 sqlite3FreeIndex(db, pIdx); 1578 } 1579 sqlite3DeleteTrigger(db, pParse->pNewTrigger); 1580 sqlite3DbFree(db, pParse->zErrMsg); 1581 renameTokenFree(db, pParse->pRename); 1582 sqlite3ParseObjectReset(pParse); 1583 } 1584 1585 /* 1586 ** SQL function: 1587 ** 1588 ** sqlite_rename_column(SQL,TYPE,OBJ,DB,TABLE,COL,NEWNAME,QUOTE,TEMP) 1589 ** 1590 ** 0. zSql: SQL statement to rewrite 1591 ** 1. type: Type of object ("table", "view" etc.) 1592 ** 2. object: Name of object 1593 ** 3. Database: Database name (e.g. "main") 1594 ** 4. Table: Table name 1595 ** 5. iCol: Index of column to rename 1596 ** 6. zNew: New column name 1597 ** 7. bQuote: Non-zero if the new column name should be quoted. 1598 ** 8. bTemp: True if zSql comes from temp schema 1599 ** 1600 ** Do a column rename operation on the CREATE statement given in zSql. 1601 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol 1602 ** into zNew. The name should be quoted if bQuote is true. 1603 ** 1604 ** This function is used internally by the ALTER TABLE RENAME COLUMN command. 1605 ** It is only accessible to SQL created using sqlite3NestedParse(). It is 1606 ** not reachable from ordinary SQL passed into sqlite3_prepare() unless the 1607 ** SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test setting is enabled. 1608 */ 1609 static void renameColumnFunc( 1610 sqlite3_context *context, 1611 int NotUsed, 1612 sqlite3_value **argv 1613 ){ 1614 sqlite3 *db = sqlite3_context_db_handle(context); 1615 RenameCtx sCtx; 1616 const char *zSql = (const char*)sqlite3_value_text(argv[0]); 1617 const char *zDb = (const char*)sqlite3_value_text(argv[3]); 1618 const char *zTable = (const char*)sqlite3_value_text(argv[4]); 1619 int iCol = sqlite3_value_int(argv[5]); 1620 const char *zNew = (const char*)sqlite3_value_text(argv[6]); 1621 int bQuote = sqlite3_value_int(argv[7]); 1622 int bTemp = sqlite3_value_int(argv[8]); 1623 const char *zOld; 1624 int rc; 1625 Parse sParse; 1626 Walker sWalker; 1627 Index *pIdx; 1628 int i; 1629 Table *pTab; 1630 #ifndef SQLITE_OMIT_AUTHORIZATION 1631 sqlite3_xauth xAuth = db->xAuth; 1632 #endif 1633 1634 UNUSED_PARAMETER(NotUsed); 1635 if( zSql==0 ) return; 1636 if( zTable==0 ) return; 1637 if( zNew==0 ) return; 1638 if( iCol<0 ) return; 1639 sqlite3BtreeEnterAll(db); 1640 pTab = sqlite3FindTable(db, zTable, zDb); 1641 if( pTab==0 || iCol>=pTab->nCol ){ 1642 sqlite3BtreeLeaveAll(db); 1643 return; 1644 } 1645 zOld = pTab->aCol[iCol].zCnName; 1646 memset(&sCtx, 0, sizeof(sCtx)); 1647 sCtx.iCol = iCol; 1648 1649 #ifndef SQLITE_OMIT_AUTHORIZATION 1650 db->xAuth = 0; 1651 #endif 1652 rc = renameParseSql(&sParse, zDb, db, zSql, bTemp); 1653 1654 /* Find tokens that need to be replaced. */ 1655 memset(&sWalker, 0, sizeof(Walker)); 1656 sWalker.pParse = &sParse; 1657 sWalker.xExprCallback = renameColumnExprCb; 1658 sWalker.xSelectCallback = renameColumnSelectCb; 1659 sWalker.u.pRename = &sCtx; 1660 1661 sCtx.pTab = pTab; 1662 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1663 if( sParse.pNewTable ){ 1664 if( IsView(sParse.pNewTable) ){ 1665 Select *pSelect = sParse.pNewTable->u.view.pSelect; 1666 pSelect->selFlags &= ~(u32)SF_View; 1667 sParse.rc = SQLITE_OK; 1668 sqlite3SelectPrep(&sParse, pSelect, 0); 1669 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); 1670 if( rc==SQLITE_OK ){ 1671 sqlite3WalkSelect(&sWalker, pSelect); 1672 } 1673 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1674 }else if( IsOrdinaryTable(sParse.pNewTable) ){ 1675 /* A regular table */ 1676 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName); 1677 FKey *pFKey; 1678 sCtx.pTab = sParse.pNewTable; 1679 if( bFKOnly==0 ){ 1680 if( iColnCol ){ 1681 renameTokenFind( 1682 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName 1683 ); 1684 } 1685 if( iCol==sParse.pNewTable->iPKey ){ 1686 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey); 1687 } 1688 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); 1689 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){ 1690 sqlite3WalkExprList(&sWalker, pIdx->aColExpr); 1691 } 1692 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){ 1693 sqlite3WalkExprList(&sWalker, pIdx->aColExpr); 1694 } 1695 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 1696 for(i=0; inCol; i++){ 1697 Expr *pExpr = sqlite3ColumnExpr(sParse.pNewTable, 1698 &sParse.pNewTable->aCol[i]); 1699 sqlite3WalkExpr(&sWalker, pExpr); 1700 } 1701 #endif 1702 } 1703 1704 assert( IsOrdinaryTable(sParse.pNewTable) ); 1705 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1706 for(i=0; inCol; i++){ 1707 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){ 1708 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]); 1709 } 1710 if( 0==sqlite3_stricmp(pFKey->zTo, zTable) 1711 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld) 1712 ){ 1713 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol); 1714 } 1715 } 1716 } 1717 } 1718 }else if( sParse.pNewIndex ){ 1719 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); 1720 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); 1721 }else{ 1722 /* A trigger */ 1723 TriggerStep *pStep; 1724 rc = renameResolveTrigger(&sParse); 1725 if( rc!=SQLITE_OK ) goto renameColumnFunc_done; 1726 1727 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ 1728 if( pStep->pSrc ){ 1729 Table *pTarget = sqlite3LocateTableItem(&sParse, 0, &pStep->pSrc->a[0]); 1730 if( pTarget==pTab ){ 1731 Upsert *pUpsert = 0; 1732 for(pUpsert=pStep->pUpsert; pUpsert; pUpsert=pUpsert->pNextUpsert){ 1733 renameColumnElistNames(&sParse,&sCtx,pUpsert->pUpsertSet,zOld); 1734 } 1735 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld); 1736 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld); 1737 } 1738 } 1739 } 1740 1741 /* Find tokens to edit in UPDATE OF clause */ 1742 if( sParse.pTriggerTab==pTab ){ 1743 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); 1744 } 1745 1746 /* Find tokens to edit in various expressions and selects */ 1747 renameWalkTrigger(&sWalker, sParse.pNewTrigger); 1748 } 1749 1750 assert( rc==SQLITE_OK ); 1751 rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote); 1752 1753 renameColumnFunc_done: 1754 if( rc!=SQLITE_OK ){ 1755 if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){ 1756 sqlite3_result_value(context, argv[0]); 1757 }else if( sParse.zErrMsg ){ 1758 renameColumnParseError(context, "", argv[1], argv[2], &sParse); 1759 }else{ 1760 sqlite3_result_error_code(context, rc); 1761 } 1762 } 1763 1764 renameParseCleanup(&sParse); 1765 renameTokenFree(db, sCtx.pList); 1766 #ifndef SQLITE_OMIT_AUTHORIZATION 1767 db->xAuth = xAuth; 1768 #endif 1769 sqlite3BtreeLeaveAll(db); 1770 } 1771 1772 /* 1773 ** Walker expression callback used by "RENAME TABLE". 1774 */ 1775 static int renameTableExprCb(Walker *pWalker, Expr *pExpr){ 1776 RenameCtx *p = pWalker->u.pRename; 1777 if( pExpr->op==TK_COLUMN 1778 && ALWAYS(ExprUseYTab(pExpr)) 1779 && p->pTab==pExpr->y.pTab 1780 ){ 1781 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab); 1782 } 1783 return WRC_Continue; 1784 } 1785 1786 /* 1787 ** Walker select callback used by "RENAME TABLE". 1788 */ 1789 static int renameTableSelectCb(Walker *pWalker, Select *pSelect){ 1790 int i; 1791 RenameCtx *p = pWalker->u.pRename; 1792 SrcList *pSrc = pSelect->pSrc; 1793 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){ 1794 testcase( pSelect->selFlags & SF_View ); 1795 testcase( pSelect->selFlags & SF_CopyCte ); 1796 return WRC_Prune; 1797 } 1798 if( NEVER(pSrc==0) ){ 1799 assert( pWalker->pParse->db->mallocFailed ); 1800 return WRC_Abort; 1801 } 1802 for(i=0; inSrc; i++){ 1803 SrcItem *pItem = &pSrc->a[i]; 1804 if( pItem->pSTab==p->pTab ){ 1805 renameTokenFind(pWalker->pParse, p, pItem->zName); 1806 } 1807 } 1808 renameWalkWith(pWalker, pSelect); 1809 1810 return WRC_Continue; 1811 } 1812 1813 1814 #ifndef SQLITE_OMIT_TRIGGER 1815 /* 1816 ** Return the table that SrcItem pItem, which is part of the pSrc list of 1817 ** an INSERT, UPDATE or DELETE trigger step (the target table, or a table 1818 ** from the FROM clause of an UPDATE ... FROM), refers to. Or NULL if it 1819 ** does not refer to any existing table. 1820 */ 1821 static Table *renameTriggerSrcTab(sqlite3 *db, SrcItem *pItem){ 1822 const char *zDb; 1823 assert( pItem->fg.isSubquery==0 ); 1824 if( pItem->fg.fixedSchema ){ 1825 int iDb = sqlite3SchemaToIndex(db, pItem->u4.pSchema); 1826 zDb = db->aDb[iDb].zDbSName; 1827 }else{ 1828 zDb = pItem->u4.zDatabase; 1829 } 1830 return sqlite3FindTable(db, pItem->zName, zDb); 1831 } 1832 #endif 1833 1834 /* 1835 ** This C function implements an SQL user function that is used by SQL code 1836 ** generated by the ALTER TABLE ... RENAME command to modify the definition 1837 ** of any foreign key constraints that use the table being renamed as the 1838 ** parent table. It is passed three arguments: 1839 ** 1840 ** 0: The database containing the table being renamed. 1841 ** 1. type: Type of object ("table", "view" etc.) 1842 ** 2. object: Name of object 1843 ** 3: The complete text of the schema statement being modified, 1844 ** 4: The old name of the table being renamed, and 1845 ** 5: The new name of the table being renamed. 1846 ** 6: True if the schema statement comes from the temp db. 1847 ** 1848 ** It returns the new schema statement. For example: 1849 ** 1850 ** sqlite_rename_table('main', 'CREATE TABLE t1(a REFERENCES t2)','t2','t3',0) 1851 ** -> 'CREATE TABLE t1(a REFERENCES t3)' 1852 */ 1853 static void renameTableFunc( 1854 sqlite3_context *context, 1855 int NotUsed, 1856 sqlite3_value **argv 1857 ){ 1858 sqlite3 *db = sqlite3_context_db_handle(context); 1859 const char *zDb = (const char*)sqlite3_value_text(argv[0]); 1860 const char *zInput = (const char*)sqlite3_value_text(argv[3]); 1861 const char *zOld = (const char*)sqlite3_value_text(argv[4]); 1862 const char *zNew = (const char*)sqlite3_value_text(argv[5]); 1863 int bTemp = sqlite3_value_int(argv[6]); 1864 UNUSED_PARAMETER(NotUsed); 1865 1866 if( zInput && zOld && zNew ){ 1867 Parse sParse; 1868 int rc; 1869 int bQuote = 1; 1870 RenameCtx sCtx; 1871 Walker sWalker; 1872 1873 #ifndef SQLITE_OMIT_AUTHORIZATION 1874 sqlite3_xauth xAuth = db->xAuth; 1875 db->xAuth = 0; 1876 #endif 1877 1878 sqlite3BtreeEnterAll(db); 1879 1880 memset(&sCtx, 0, sizeof(RenameCtx)); 1881 sCtx.pTab = sqlite3FindTable(db, zOld, zDb); 1882 memset(&sWalker, 0, sizeof(Walker)); 1883 sWalker.pParse = &sParse; 1884 sWalker.xExprCallback = renameTableExprCb; 1885 sWalker.xSelectCallback = renameTableSelectCb; 1886 sWalker.u.pRename = &sCtx; 1887 1888 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); 1889 1890 if( rc==SQLITE_OK ){ 1891 int isLegacy = (db->flags & SQLITE_LegacyAlter); 1892 if( sParse.pNewTable ){ 1893 Table *pTab = sParse.pNewTable; 1894 1895 if( IsView(pTab) ){ 1896 if( isLegacy==0 ){ 1897 Select *pSelect = pTab->u.view.pSelect; 1898 NameContext sNC; 1899 memset(&sNC, 0, sizeof(sNC)); 1900 sNC.pParse = &sParse; 1901 1902 assert( pSelect->selFlags & SF_View ); 1903 pSelect->selFlags &= ~(u32)SF_View; 1904 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC); 1905 if( sParse.nErr ){ 1906 rc = sParse.rc; 1907 }else{ 1908 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect); 1909 } 1910 } 1911 }else{ 1912 /* Modify any FK definitions to point to the new table. */ 1913 #ifndef SQLITE_OMIT_FOREIGN_KEY 1914 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys)) 1915 && !IsVirtual(pTab) 1916 ){ 1917 FKey *pFKey; 1918 assert( IsOrdinaryTable(pTab) ); 1919 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){ 1920 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){ 1921 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo); 1922 } 1923 } 1924 } 1925 #endif 1926 1927 /* If this is the table being altered, fix any table refs in CHECK 1928 ** expressions. Also update the name that appears right after the 1929 ** "CREATE [VIRTUAL] TABLE" bit. */ 1930 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){ 1931 sCtx.pTab = pTab; 1932 if( isLegacy==0 ){ 1933 sqlite3WalkExprList(&sWalker, pTab->pCheck); 1934 } 1935 renameTokenFind(&sParse, &sCtx, pTab->zName); 1936 } 1937 } 1938 } 1939 1940 else if( sParse.pNewIndex ){ 1941 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName); 1942 if( isLegacy==0 ){ 1943 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); 1944 } 1945 } 1946 1947 #ifndef SQLITE_OMIT_TRIGGER 1948 else{ 1949 Trigger *pTrigger = sParse.pNewTrigger; 1950 TriggerStep *pStep; 1951 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) 1952 && sCtx.pTab->pSchema==pTrigger->pTabSchema 1953 ){ 1954 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table); 1955 } 1956 1957 if( isLegacy==0 ){ 1958 rc = renameResolveTrigger(&sParse); 1959 if( rc==SQLITE_OK ){ 1960 renameWalkTrigger(&sWalker, pTrigger); 1961 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ 1962 if( pStep->pSrc ){ 1963 int i; 1964 for(i=0; ipSrc->nSrc; i++){ 1965 SrcItem *p = &pStep->pSrc->a[i]; 1966 if( p->zName && renameTriggerSrcTab(db, p)==sCtx.pTab ){ 1967 renameTokenFind(&sParse, &sCtx, p->zName); 1968 } 1969 } 1970 } 1971 } 1972 } 1973 } 1974 } 1975 #endif 1976 } 1977 1978 if( rc==SQLITE_OK ){ 1979 rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote); 1980 } 1981 if( rc!=SQLITE_OK ){ 1982 if( rc==SQLITE_ERROR && sqlite3WritableSchema(db) ){ 1983 sqlite3_result_value(context, argv[3]); 1984 }else if( sParse.zErrMsg ){ 1985 renameColumnParseError(context, "", argv[1], argv[2], &sParse); 1986 }else{ 1987 sqlite3_result_error_code(context, rc); 1988 } 1989 } 1990 1991 renameParseCleanup(&sParse); 1992 renameTokenFree(db, sCtx.pList); 1993 sqlite3BtreeLeaveAll(db); 1994 #ifndef SQLITE_OMIT_AUTHORIZATION 1995 db->xAuth = xAuth; 1996 #endif 1997 } 1998 1999 return; 2000 } 2001 2002 static int renameQuotefixExprCb(Walker *pWalker, Expr *pExpr){ 2003 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){ 2004 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr); 2005 } 2006 return WRC_Continue; 2007 } 2008 2009 /* SQL function: sqlite_rename_quotefix(DB,SQL) 2010 ** 2011 ** Rewrite the DDL statement "SQL" so that any string literals that use 2012 ** double-quotes use single quotes instead. 2013 ** 2014 ** Two arguments must be passed: 2015 ** 2016 ** 0: Database name ("main", "temp" etc.). 2017 ** 1: SQL statement to edit. 2018 ** 2019 ** The returned value is the modified SQL statement. For example, given 2020 ** the database schema: 2021 ** 2022 ** CREATE TABLE t1(a, b, c); 2023 ** 2024 ** SELECT sqlite_rename_quotefix('main', 2025 ** 'CREATE VIEW v1 AS SELECT "a", "string" FROM t1' 2026 ** ); 2027 ** 2028 ** returns the string: 2029 ** 2030 ** CREATE VIEW v1 AS SELECT "a", 'string' FROM t1 2031 ** 2032 ** If there is a error in the input SQL, then raise an error, except 2033 ** if PRAGMA writable_schema=ON, then just return the input string 2034 ** unmodified following an error. 2035 */ 2036 static void renameQuotefixFunc( 2037 sqlite3_context *context, 2038 int NotUsed, 2039 sqlite3_value **argv 2040 ){ 2041 sqlite3 *db = sqlite3_context_db_handle(context); 2042 char const *zDb = (const char*)sqlite3_value_text(argv[0]); 2043 char const *zInput = (const char*)sqlite3_value_text(argv[1]); 2044 2045 #ifndef SQLITE_OMIT_AUTHORIZATION 2046 sqlite3_xauth xAuth = db->xAuth; 2047 db->xAuth = 0; 2048 #endif 2049 2050 sqlite3BtreeEnterAll(db); 2051 2052 UNUSED_PARAMETER(NotUsed); 2053 if( zDb && zInput ){ 2054 int rc; 2055 Parse sParse; 2056 rc = renameParseSql(&sParse, zDb, db, zInput, 0); 2057 2058 if( rc==SQLITE_OK ){ 2059 RenameCtx sCtx; 2060 Walker sWalker; 2061 2062 /* Walker to find tokens that need to be replaced. */ 2063 memset(&sCtx, 0, sizeof(RenameCtx)); 2064 memset(&sWalker, 0, sizeof(Walker)); 2065 sWalker.pParse = &sParse; 2066 sWalker.xExprCallback = renameQuotefixExprCb; 2067 sWalker.xSelectCallback = renameColumnSelectCb; 2068 sWalker.u.pRename = &sCtx; 2069 2070 if( sParse.pNewTable ){ 2071 if( IsView(sParse.pNewTable) ){ 2072 Select *pSelect = sParse.pNewTable->u.view.pSelect; 2073 pSelect->selFlags &= ~(u32)SF_View; 2074 sParse.rc = SQLITE_OK; 2075 sqlite3SelectPrep(&sParse, pSelect, 0); 2076 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); 2077 if( rc==SQLITE_OK ){ 2078 sqlite3WalkSelect(&sWalker, pSelect); 2079 } 2080 }else{ 2081 int i; 2082 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); 2083 #ifndef SQLITE_OMIT_GENERATED_COLUMNS 2084 for(i=0; inCol; i++){ 2085 sqlite3WalkExpr(&sWalker, 2086 sqlite3ColumnExpr(sParse.pNewTable, 2087 &sParse.pNewTable->aCol[i])); 2088 } 2089 #endif /* SQLITE_OMIT_GENERATED_COLUMNS */ 2090 } 2091 }else if( sParse.pNewIndex ){ 2092 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); 2093 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); 2094 }else{ 2095 #ifndef SQLITE_OMIT_TRIGGER 2096 rc = renameResolveTrigger(&sParse); 2097 if( rc==SQLITE_OK ){ 2098 renameWalkTrigger(&sWalker, sParse.pNewTrigger); 2099 } 2100 #endif /* SQLITE_OMIT_TRIGGER */ 2101 } 2102 2103 if( rc==SQLITE_OK ){ 2104 rc = renameEditSql(context, &sCtx, zInput, 0, 0); 2105 } 2106 renameTokenFree(db, sCtx.pList); 2107 } 2108 if( rc!=SQLITE_OK ){ 2109 if( sqlite3WritableSchema(db) && rc==SQLITE_ERROR ){ 2110 sqlite3_result_value(context, argv[1]); 2111 }else{ 2112 sqlite3_result_error_code(context, rc); 2113 } 2114 } 2115 renameParseCleanup(&sParse); 2116 } 2117 2118 #ifndef SQLITE_OMIT_AUTHORIZATION 2119 db->xAuth = xAuth; 2120 #endif 2121 2122 sqlite3BtreeLeaveAll(db); 2123 } 2124 2125 /* Function: sqlite_rename_test(DB,SQL,TYPE,NAME,ISTEMP,WHEN,DQS) 2126 ** 2127 ** An SQL user function that checks that there are no parse or symbol 2128 ** resolution problems in a CREATE TRIGGER|TABLE|VIEW|INDEX statement. 2129 ** After an ALTER TABLE .. RENAME operation is performed and the schema 2130 ** reloaded, this function is called on each SQL statement in the schema 2131 ** to ensure that it is still usable. 2132 ** 2133 ** 0: Database name ("main", "temp" etc.). 2134 ** 1: SQL statement. 2135 ** 2: Object type ("view", "table", "trigger" or "index"). 2136 ** 3: Object name. 2137 ** 4: True if object is from temp schema. 2138 ** 5: "when" part of error message. 2139 ** 6: True to disable the DQS quirk when parsing SQL. 2140 ** 2141 ** The return value is computed as follows: 2142 ** 2143 ** A. If an error is seen and not in PRAGMA writable_schema=ON mode, 2144 ** then raise the error. 2145 ** B. Else if a trigger is created and the the table that the trigger is 2146 ** attached to is in database zDb, then return 1. 2147 ** C. Otherwise return NULL. 2148 */ 2149 static void renameTableTest( 2150 sqlite3_context *context, 2151 int NotUsed, 2152 sqlite3_value **argv 2153 ){ 2154 sqlite3 *db = sqlite3_context_db_handle(context); 2155 char const *zDb = (const char*)sqlite3_value_text(argv[0]); 2156 char const *zInput = (const char*)sqlite3_value_text(argv[1]); 2157 int bTemp = sqlite3_value_int(argv[4]); 2158 int isLegacy = (db->flags & SQLITE_LegacyAlter); 2159 char const *zWhen = (const char*)sqlite3_value_text(argv[5]); 2160 int bNoDQS = sqlite3_value_int(argv[6]); 2161 2162 #ifndef SQLITE_OMIT_AUTHORIZATION 2163 sqlite3_xauth xAuth = db->xAuth; 2164 db->xAuth = 0; 2165 #endif 2166 2167 UNUSED_PARAMETER(NotUsed); 2168 2169 if( zDb && zInput ){ 2170 int rc; 2171 Parse sParse; 2172 u64 flags = db->flags; 2173 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL); 2174 rc = renameParseSql(&sParse, zDb, db, zInput, bTemp); 2175 db->flags = flags; 2176 if( rc==SQLITE_OK ){ 2177 if( isLegacy==0 && sParse.pNewTable && IsView(sParse.pNewTable) ){ 2178 NameContext sNC; 2179 memset(&sNC, 0, sizeof(sNC)); 2180 sNC.pParse = &sParse; 2181 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC); 2182 if( sParse.nErr ) rc = sParse.rc; 2183 } 2184 2185 else if( sParse.pNewTrigger ){ 2186 if( isLegacy==0 ){ 2187 rc = renameResolveTrigger(&sParse); 2188 } 2189 if( rc==SQLITE_OK ){ 2190 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema); 2191 int i2 = sqlite3FindDbName(db, zDb); 2192 if( i1==i2 ){ 2193 /* Handle output case B */ 2194 sqlite3_result_int(context, 1); 2195 } 2196 } 2197 } 2198 } 2199 2200 if( rc!=SQLITE_OK && zWhen && !sqlite3WritableSchema(db) ){ 2201 /* Output case A */ 2202 renameColumnParseError(context, zWhen, argv[2], argv[3],&sParse); 2203 } 2204 renameParseCleanup(&sParse); 2205 } 2206 2207 #ifndef SQLITE_OMIT_AUTHORIZATION 2208 db->xAuth = xAuth; 2209 #endif 2210 } 2211 2212 2213 /* 2214 ** Return the number of bytes until the end of the next non-whitespace and 2215 ** non-comment token. For the purpose of this function, a "(" token includes 2216 ** all of the bytes through and including the matching ")", or until the 2217 ** first illegal token, whichever comes first. 2218 ** 2219 ** Write the token type into *piToken. 2220 ** 2221 ** The value returned is the number of bytes in the token itself plus 2222 ** the number of bytes of leading whitespace and comments skipped plus 2223 ** all bytes through the next matching ")" if the token is TK_LP. 2224 ** 2225 ** Example: (Note: '.' used in place of '*' in the example z[] text) 2226 ** 2227 ** ,--------- *piToken := TK_RP 2228 ** v 2229 ** z[] = " /.comment./ --comment\n (two three four) five" 2230 ** | | 2231 ** |<-------------------------------------->| 2232 ** | 2233 ** `--- return value 2234 */ 2235 static int getConstraintToken(const u8 *z, int *piToken){ 2236 int iOff = 0; 2237 int t = 0; 2238 do { 2239 iOff += sqlite3GetToken(&z[iOff], &t); 2240 }while( t==TK_SPACE || t==TK_COMMENT ); 2241 2242 *piToken = t; 2243 2244 if( t==TK_LP ){ 2245 int nNest = 1; 2246 while( nNest>0 ){ 2247 iOff += sqlite3GetToken(&z[iOff], &t); 2248 if( t==TK_LP ){ 2249 nNest++; 2250 }else if( t==TK_RP ){ 2251 t = TK_LP; 2252 nNest--; 2253 }else if( t==TK_ILLEGAL ){ 2254 break; 2255 } 2256 } 2257 } 2258 2259 *piToken = t; 2260 return iOff; 2261 } 2262 2263 /* 2264 ** The implementation of internal UDF sqlite_drop_column(). 2265 ** 2266 ** Arguments: 2267 ** 2268 ** argv[0]: An integer - the index of the schema containing the table 2269 ** argv[1]: CREATE TABLE statement to modify. 2270 ** argv[2]: An integer - the index of the column to remove. 2271 ** 2272 ** The value returned is a string containing the CREATE TABLE statement 2273 ** with column argv[2] removed. 2274 */ 2275 static void dropColumnFunc( 2276 sqlite3_context *context, 2277 int NotUsed, 2278 sqlite3_value **argv 2279 ){ 2280 sqlite3 *db = sqlite3_context_db_handle(context); 2281 int iSchema = sqlite3_value_int(argv[0]); 2282 const char *zSql = (const char*)sqlite3_value_text(argv[1]); 2283 int iCol = sqlite3_value_int(argv[2]); 2284 const char *zDb = db->aDb[iSchema].zDbSName; 2285 int rc; 2286 Parse sParse; 2287 RenameToken *pCol; 2288 Table *pTab; 2289 const char *zEnd; 2290 char *zNew = 0; 2291 2292 #ifndef SQLITE_OMIT_AUTHORIZATION 2293 sqlite3_xauth xAuth = db->xAuth; 2294 db->xAuth = 0; 2295 #endif 2296 2297 UNUSED_PARAMETER(NotUsed); 2298 rc = renameParseSql(&sParse, zDb, db, zSql, iSchema==1); 2299 if( rc!=SQLITE_OK ) goto drop_column_done; 2300 pTab = sParse.pNewTable; 2301 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){ 2302 /* This can happen if the sqlite_schema table is corrupt */ 2303 rc = SQLITE_CORRUPT_BKPT; 2304 goto drop_column_done; 2305 } 2306 2307 if( iColnCol-1 ){ 2308 RenameToken *pEnd; 2309 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName); 2310 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName); 2311 zEnd = (const char*)pEnd->t.z; 2312 }else{ 2313 int eTok; 2314 assert( IsOrdinaryTable(pTab) ); 2315 assert( iCol!=0 ); 2316 /* Point pCol->t.z at the "," immediately preceding the definition of 2317 ** the column being dropped. To do this, start at the name of the 2318 ** previous column, and tokenize until the next ",". */ 2319 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol-1].zCnName); 2320 do { 2321 pCol->t.z += getConstraintToken((const u8*)pCol->t.z, &eTok); 2322 }while( eTok!=TK_COMMA ); 2323 pCol->t.z--; 2324 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset]; 2325 } 2326 2327 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd); 2328 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT); 2329 sqlite3_free(zNew); 2330 2331 drop_column_done: 2332 renameParseCleanup(&sParse); 2333 #ifndef SQLITE_OMIT_AUTHORIZATION 2334 db->xAuth = xAuth; 2335 #endif 2336 if( rc!=SQLITE_OK ){ 2337 sqlite3_result_error_code(context, rc); 2338 } 2339 } 2340 2341 /* 2342 ** This function is called by the parser upon parsing an 2343 ** 2344 ** ALTER TABLE pSrc DROP COLUMN pName 2345 ** 2346 ** statement. Argument pSrc contains the possibly qualified name of the 2347 ** table being edited, and token pName the name of the column to drop. 2348 */ 2349 void sqlite3AlterDropColumn(Parse *pParse, SrcList *pSrc, const Token *pName){ 2350 sqlite3 *db = pParse->db; /* Database handle */ 2351 Table *pTab; /* Table to modify */ 2352 int iDb; /* Index of db containing pTab in aDb[] */ 2353 const char *zDb; /* Database containing pTab ("main" etc.) */ 2354 char *zCol = 0; /* Name of column to drop */ 2355 int iCol; /* Index of column zCol in pTab->aCol[] */ 2356 2357 /* Look up the table being altered. */ 2358 assert( pParse->pNewTable==0 ); 2359 assert( sqlite3BtreeHoldsAllMutexes(db) ); 2360 if( NEVER(db->mallocFailed) ) goto exit_drop_column; 2361 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 2362 if( !pTab ) goto exit_drop_column; 2363 2364 /* Make sure this is not an attempt to ALTER a view, virtual table or 2365 ** system table. */ 2366 if( SQLITE_OK!=isAlterableTable(pParse, pTab) ) goto exit_drop_column; 2367 if( SQLITE_OK!=isRealTable(pParse, pTab, 1) ) goto exit_drop_column; 2368 2369 /* Find the index of the column being dropped. */ 2370 zCol = sqlite3NameFromToken(db, pName); 2371 if( zCol==0 ){ 2372 assert( db->mallocFailed ); 2373 goto exit_drop_column; 2374 } 2375 iCol = sqlite3ColumnIndex(pTab, zCol); 2376 if( iCol<0 ){ 2377 sqlite3ErrorMsg(pParse, "no such column: \"%T\"", pName); 2378 goto exit_drop_column; 2379 } 2380 if( isRowidAlias(pParse, pTab, zCol, "drop") ) goto exit_drop_column; 2381 2382 /* Do not allow the user to drop a PRIMARY KEY column or a column 2383 ** constrained by a UNIQUE constraint. */ 2384 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){ 2385 sqlite3ErrorMsg(pParse, "cannot drop %s column: \"%s\"", 2386 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE", 2387 zCol 2388 ); 2389 goto exit_drop_column; 2390 } 2391 2392 /* Do not allow the number of columns to go to zero */ 2393 if( pTab->nCol<=1 ){ 2394 sqlite3ErrorMsg(pParse, "cannot drop column \"%s\": no other columns exist",zCol); 2395 goto exit_drop_column; 2396 } 2397 2398 /* Edit the sqlite_schema table */ 2399 iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2400 assert( iDb>=0 ); 2401 zDb = db->aDb[iDb].zDbSName; 2402 #ifndef SQLITE_OMIT_AUTHORIZATION 2403 /* Invoke the authorization callback. */ 2404 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){ 2405 goto exit_drop_column; 2406 } 2407 #endif 2408 renameTestSchema(pParse, zDb, iDb==1, "", 0); 2409 renameFixQuotes(pParse, zDb, iDb==1); 2410 sqlite3NestedParse(pParse, 2411 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 2412 "sql = sqlite_drop_column(%d, sql, %d) " 2413 "WHERE (type=='table' AND tbl_name=%Q COLLATE nocase)" 2414 , zDb, iDb, iCol, pTab->zName 2415 ); 2416 2417 /* Drop and reload the database schema. */ 2418 renameReloadSchema(pParse, iDb, INITFLAG_AlterDrop); 2419 renameTestSchema(pParse, zDb, iDb==1, "after drop column", 1); 2420 2421 /* Edit rows of table on disk */ 2422 if( pParse->nErr==0 ){ 2423 Vdbe *v = sqlite3GetVdbe(pParse); 2424 sqlite3VdbeAddOp0(v, OP_DbLock); 2425 if( (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){ 2426 int i; 2427 int addr; 2428 int reg; 2429 int regRec; 2430 Index *pPk = 0; 2431 int nField = 0; /* Number of non-virtual columns after drop */ 2432 int iCur; 2433 iCur = pParse->nTab++; 2434 sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 2435 addr = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v); 2436 reg = ++pParse->nMem; 2437 if( HasRowid(pTab) ){ 2438 sqlite3VdbeAddOp2(v, OP_Rowid, iCur, reg); 2439 pParse->nMem += pTab->nCol; 2440 }else{ 2441 pPk = sqlite3PrimaryKeyIndex(pTab); 2442 pParse->nMem += pPk->nColumn; 2443 for(i=0; inKeyCol; i++){ 2444 sqlite3VdbeAddOp3(v, OP_Column, iCur, i, reg+i+1); 2445 } 2446 nField = pPk->nKeyCol; 2447 } 2448 regRec = ++pParse->nMem; 2449 for(i=0; inCol; i++){ 2450 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){ 2451 int regOut; 2452 if( pPk ){ 2453 int iPos = sqlite3TableColumnToIndex(pPk, i); 2454 int iColPos = sqlite3TableColumnToIndex(pPk, iCol); 2455 if( iPosnKeyCol ) continue; 2456 regOut = reg+1+iPos-(iPos>iColPos); 2457 }else{ 2458 regOut = reg+1+nField; 2459 } 2460 if( i==pTab->iPKey ){ 2461 sqlite3VdbeAddOp2(v, OP_Null, 0, regOut); 2462 }else{ 2463 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOut); 2464 assert( pParse->nErr 2465 || sqlite3VdbeGetOp(v,sqlite3VdbeCurrentAddr(v)-1)->opcode 2466 != OP_RealAffinity 2467 || pTab->aCol[i].affinity==SQLITE_AFF_REAL ); 2468 sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity); 2469 } 2470 nField++; 2471 } 2472 } 2473 if( nField==0 ){ 2474 /* dbsqlfuzz `5f09e7bcc78b4954d06bf9f2400d7715f48d1fef` */ 2475 pParse->nMem++; 2476 sqlite3VdbeAddOp2(v, OP_Null, 0, reg+1); 2477 nField = 1; 2478 } 2479 sqlite3VdbeAddOp3(v, OP_MakeRecord, reg+1, nField, regRec); 2480 if( pPk ){ 2481 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1,pPk->nKeyCol); 2482 }else{ 2483 sqlite3VdbeAddOp3(v, OP_Insert, iCur, regRec, reg); 2484 } 2485 sqlite3VdbeChangeP5(v, OPFLAG_SAVEPOSITION); 2486 2487 sqlite3VdbeAddOp2(v, OP_Next, iCur, addr+1); VdbeCoverage(v); 2488 sqlite3VdbeJumpHere(v, addr); 2489 } 2490 } 2491 2492 exit_drop_column: 2493 sqlite3DbFree(db, zCol); 2494 sqlite3SrcListDelete(db, pSrc); 2495 } 2496 2497 /* 2498 ** Return the number of bytes of leading whitespace/comments in string z[]. 2499 */ 2500 static int getWhitespace(const u8 *z){ 2501 int nRet = 0; 2502 while( 1 ){ 2503 int t = 0; 2504 int n = sqlite3GetToken(&z[nRet], &t); 2505 if( t!=TK_SPACE && t!=TK_COMMENT ) break; 2506 nRet += n; 2507 } 2508 return nRet; 2509 } 2510 2511 2512 /* 2513 ** Argument z points into the body of a constraint - specifically the 2514 ** second token of the constraint definition. For a named constraint, 2515 ** z points to the second token of the constraint definition. For an 2516 ** unnamed NOT NULL constraint, z points to the first byte past the NOT 2517 ** keyword. 2518 ** 2519 ** Argument eTok may be the token value of the first token of the constraint 2520 ** (e.g. TK_CHECK or TK_REFERENCES or TK_NOT) or zero. If it is either 2521 ** TK_REFERENCES or TK_FOREIGN, special parsing is enabled to find the 2522 ** end of the foreign-key constraint definition. If eTok is TK_NOT then 2523 ** special processing is enabled to find the end of a NOT NULL constraint 2524 ** including its optional ON CONFLICT clause. 2525 ** 2526 ** Return the number of bytes until the end of the constraint. 2527 */ 2528 static int getConstraint(const u8 *z, int eTok){ 2529 int iOff = 0; 2530 int t = 0; 2531 int t2 = 0; 2532 int prev = 0; 2533 2534 #ifndef SQLITE_OMIT_FOREIGN_KEY 2535 if( eTok==TK_FOREIGN ){ 2536 /* For a FOREIGN KEY constraint, use getConstraint() to parse everything 2537 ** up to the REFERENCES keyword. Then getConstraintToken() to consume 2538 ** the TK_REFERENCES token itself. Then fall through to the special 2539 ** handling for TK_REFERENCES below. */ 2540 iOff = getConstraint(z, 0); 2541 iOff += getConstraintToken(&z[iOff], &eTok); 2542 } 2543 2544 if( eTok==TK_REFERENCES ){ 2545 /* REFERENCES is followed by a table name. Gobble this up here in 2546 ** case the table name is a fallback token like TK_GENERATED. */ 2547 iOff += getConstraintToken(&z[iOff], &t); 2548 2549 /* If the table names is followed by a parenthesized list of columns, 2550 ** also skip that, lest the close ")" end the constraint in the 2551 ** while loop below. */ 2552 iOff += getWhitespace(&z[iOff]); 2553 if( z[iOff]=='(' ){ 2554 iOff += getConstraintToken(&z[iOff], &t); 2555 } 2556 } 2557 #endif 2558 2559 /* Now, the current constraint proceeds until the next occurence of one 2560 ** of the following tokens: 2561 ** 2562 ** CONSTRAINT, PRIMARY, NOT, UNIQUE, CHECK, DEFAULT, 2563 ** COLLATE, REFERENCES, FOREIGN, GENERATED, AS, RP, or COMMA 2564 ** 2565 ** Also exit the loop if ILLEGAL turns up. 2566 ** 2567 ** Exceptions: 2568 ** 2569 ** * For NOT NULL constraints, also terminate at DEFERRABLE 2570 ** 2571 ** * Do not terminate at DEFAULT if the previous token was SET 2572 */ 2573 while( 1 ){ 2574 int n = getConstraintToken(&z[iOff], &t); 2575 if( t==TK_CONSTRAINT || t==TK_PRIMARY || t==TK_UNIQUE 2576 || t==TK_CHECK || t==TK_COLLATE || t==TK_REFERENCES 2577 || (t==TK_DEFAULT && prev!=TK_SET) 2578 || t==TK_FOREIGN || t==TK_RP || t==TK_COMMA || t==TK_ILLEGAL 2579 || t==TK_AS || t==TK_GENERATED 2580 || (eTok==TK_NOT && t==TK_DEFERRABLE) 2581 ){ 2582 break; 2583 } 2584 if( t==TK_NOT 2585 && (eTok!=TK_REFERENCES 2586 || (getConstraintToken(&z[iOff+n],&t2), t2!=TK_DEFERRABLE)) 2587 ){ 2588 /* NOT ends the constraint unless eTok is TK_REFERENCES and the next 2589 ** token is DEFERRABLE */ 2590 break; 2591 } 2592 iOff += n; 2593 prev = t; 2594 } 2595 2596 return iOff; 2597 } 2598 2599 /* 2600 ** Compare two constraint names. 2601 ** 2602 ** Summary: *pRes := zQuote != zCmp 2603 ** 2604 ** Details: 2605 ** Compare the (possibly quoted) constraint name zQuote[0..nQuote-1] 2606 ** against zCmp[]. Write zero into *pRes if they are the same and 2607 ** non-zero if they differ. Normally return SQLITE_OK, except if there 2608 ** is an OOM, set the OOM error condition on ctx and return SQLITE_NOMEM. 2609 */ 2610 static int quotedCompare( 2611 sqlite3_context *ctx, /* Function context on which to report errors */ 2612 int t, /* Token type */ 2613 const u8 *zQuote, /* Possibly quoted text. Not zero-terminated. */ 2614 int nQuote, /* Length of zQuote in bytes */ 2615 const u8 *zCmp, /* Zero-terminated, unquoted name to compare against */ 2616 int *pRes /* OUT: Set to 0 if equal, non-zero if unequal */ 2617 ){ 2618 char *zCopy = 0; /* De-quoted, zero-terminated copy of zQuote[] */ 2619 2620 if( t==TK_ILLEGAL ){ 2621 *pRes = 1; 2622 return SQLITE_OK; 2623 } 2624 zCopy = sqlite3MallocZero(nQuote+1); 2625 if( zCopy==0 ){ 2626 sqlite3_result_error_nomem(ctx); 2627 return SQLITE_NOMEM_BKPT; 2628 } 2629 memcpy(zCopy, zQuote, nQuote); 2630 sqlite3Dequote(zCopy); 2631 *pRes = sqlite3_stricmp((const char*)zCopy, (const char*)zCmp); 2632 sqlite3_free(zCopy); 2633 return SQLITE_OK; 2634 } 2635 2636 /* 2637 ** zSql[] is a CREATE TABLE statement, supposedly. Find the offset 2638 ** into zSql[] of the first character past the first "(" and write 2639 ** that offset into *piOff and return SQLITE_OK. Or, if not found, 2640 ** set the SQLITE_CORRUPT error code and return SQLITE_ERROR. 2641 */ 2642 static int skipCreateTable(sqlite3_context *ctx, const u8 *zSql, int *piOff){ 2643 int iOff = 0; 2644 2645 if( zSql==0 ) return SQLITE_ERROR; 2646 2647 /* Jump past the "CREATE TABLE" bit. */ 2648 while( 1 ){ 2649 int t = 0; 2650 iOff += sqlite3GetToken(&zSql[iOff], &t); 2651 if( t==TK_LP ) break; 2652 if( t==TK_ILLEGAL ){ 2653 sqlite3_result_error_code(ctx, SQLITE_CORRUPT_BKPT); 2654 return SQLITE_ERROR; 2655 } 2656 } 2657 2658 *piOff = iOff; 2659 return SQLITE_OK; 2660 } 2661 2662 /* 2663 ** Internal SQL function sqlite3_drop_constraint(): Given an input 2664 ** CREATE TABLE statement, return a revised CREATE TABLE statement 2665 ** with a constraint removed. Two forms, depending on the datatype 2666 ** of argv[2]: 2667 ** 2668 ** sqlite_drop_constraint(SQL, INT) -- Omit NOT NULL from the INT-th column 2669 ** sqlite_drop_constraint(SQL, TEXT) -- OMIT constraint with name TEXT 2670 ** 2671 ** In the first case, the left-most column is 0. 2672 */ 2673 static void dropConstraintFunc( 2674 sqlite3_context *ctx, 2675 int NotUsed, 2676 sqlite3_value **argv 2677 ){ 2678 const u8 *zSql = sqlite3_value_text(argv[0]); 2679 const u8 *zCons = 0; 2680 int iNotNull = -1; 2681 int ii; 2682 int iOff = 0; 2683 int iStart = 0; 2684 int iEnd = 0; 2685 char *zNew = 0; 2686 int t = 0; 2687 sqlite3 *db; 2688 UNUSED_PARAMETER(NotUsed); 2689 2690 if( zSql==0 ) return; 2691 2692 /* Jump past the "CREATE TABLE" bit. */ 2693 if( skipCreateTable(ctx, zSql, &iOff) ) return; 2694 2695 if( sqlite3_value_type(argv[1])==SQLITE_INTEGER ){ 2696 iNotNull = sqlite3_value_int(argv[1]); 2697 }else{ 2698 zCons = sqlite3_value_text(argv[1]); 2699 } 2700 2701 /* Search for the named constraint within column definitions. */ 2702 for(ii=0; iEnd==0; ii++){ 2703 2704 /* Now parse the column or table constraint definition. Search 2705 ** for the token CONSTRAINT if this is a DROP CONSTRAINT command, or 2706 ** NOT in the right column if this is a DROP NOT NULL. */ 2707 while( 1 ){ 2708 iStart = iOff; 2709 iOff += getConstraintToken(&zSql[iOff], &t); 2710 if( t==TK_CONSTRAINT && (zCons || iNotNull==ii) ){ 2711 /* Check if this is the constraint we are searching for. */ 2712 int nTok = 0; 2713 int cmp = 1; 2714 2715 /* Skip past any whitespace. */ 2716 iOff += getWhitespace(&zSql[iOff]); 2717 2718 /* Compare the next token - which may be quoted - with the name of 2719 ** the constraint being dropped. */ 2720 nTok = getConstraintToken(&zSql[iOff], &t); 2721 if( zCons ){ 2722 if( quotedCompare(ctx, t, &zSql[iOff], nTok, zCons, &cmp) ) return; 2723 } 2724 iOff += nTok; 2725 2726 /* The next token is usually the first token of the constraint 2727 ** definition. This is enough to tell the type of the constraint - 2728 ** TK_NOT means it is a NOT NULL, TK_CHECK a CHECK constraint etc. 2729 ** 2730 ** There is also the chance that the next token is TK_CONSTRAINT 2731 ** (or TK_DEFAULT or TK_COLLATE), for example if a table has been 2732 ** created as follows: 2733 ** 2734 ** CREATE TABLE t1(cols, CONSTRAINT one CONSTRAINT two NOT NULL); 2735 ** 2736 ** In this case, allow the "CONSTRAINT one" bit to be dropped by 2737 ** this command if that is what is requested, or to advance to 2738 ** the next iteration of the loop with &zSql[iOff] still pointing 2739 ** to the CONSTRAINT keyword. */ 2740 nTok = getConstraintToken(&zSql[iOff], &t); 2741 if( t==TK_CONSTRAINT || t==TK_DEFAULT || t==TK_COLLATE 2742 || t==TK_COMMA || t==TK_RP || t==TK_GENERATED || t==TK_AS 2743 ){ 2744 t = TK_CHECK; 2745 }else{ 2746 iOff += nTok; 2747 iOff += getConstraint(&zSql[iOff], t); 2748 } 2749 2750 if( cmp==0 || (iNotNull>=0 && t==TK_NOT) ){ 2751 if( t!=TK_NOT && t!=TK_CHECK && t!=TK_REFERENCES && t!=TK_FOREIGN ){ 2752 errorMPrintf(ctx, "constraint may not be dropped: %s", zCons); 2753 return; 2754 } 2755 iEnd = iOff; 2756 break; 2757 } 2758 2759 }else if( t==TK_NOT && iNotNull==ii ){ 2760 int t2; 2761 (void)getConstraintToken(zSql+iOff, &t2); 2762 if( t2==TK_NULL ){ 2763 iEnd = iOff + getConstraint(zSql+iOff, TK_NOT); 2764 break; 2765 } 2766 }else if( t==TK_RP || t==TK_ILLEGAL ){ 2767 iEnd = -1; 2768 break; 2769 }else if( t==TK_COMMA ){ 2770 break; 2771 } 2772 } 2773 } 2774 2775 /* If the constraint has not been found it is an error. */ 2776 if( iEnd<=0 ){ 2777 if( zCons ){ 2778 errorMPrintf(ctx, "no such constraint: %s", zCons); 2779 }else{ 2780 /* SQLite follows postgres in that a DROP NOT NULL on a column that is 2781 ** not NOT NULL is not an error. So just return the original SQL here. */ 2782 sqlite3_result_text(ctx, (const char*)zSql, -1, SQLITE_TRANSIENT); 2783 } 2784 }else{ 2785 2786 /* Figure out if an extra space should be inserted after the constraint 2787 ** is removed. And if an additional comma preceding the constraint 2788 ** should be removed. */ 2789 const char *zSpace = " "; 2790 iEnd += getWhitespace(&zSql[iEnd]); 2791 sqlite3GetToken(&zSql[iEnd], &t); 2792 if( t==TK_RP || t==TK_COMMA ){ 2793 zSpace = ""; 2794 if( zSql[iStart-1]==',' ) iStart--; 2795 } 2796 2797 db = sqlite3_context_db_handle(ctx); 2798 zNew = sqlite3MPrintf(db, "%.*s%s%s", iStart, zSql, zSpace, &zSql[iEnd]); 2799 sqlite3_result_text(ctx, zNew, -1, SQLITE_DYNAMIC); 2800 } 2801 } 2802 2803 /* 2804 ** Internal SQL function: 2805 ** 2806 ** sqlite_add_constraint(SQL, CONSTRAINT-TEXT, ICOL) 2807 ** 2808 ** SQL is a CREATE TABLE statement. Return a modified version of 2809 ** SQL that adds CONSTRAINT-TEXT at the end of the ICOL-th column 2810 ** definition. (The left-most column defintion is 0.) 2811 */ 2812 static void addConstraintFunc( 2813 sqlite3_context *ctx, 2814 int NotUsed, 2815 sqlite3_value **argv 2816 ){ 2817 const u8 *zSql = sqlite3_value_text(argv[0]); 2818 const char *zCons = (const char*)sqlite3_value_text(argv[1]); 2819 int iCol = sqlite3_value_int(argv[2]); 2820 int iOff = 0; 2821 int ii; 2822 sqlite3_str *pNew; 2823 int t = 0; 2824 UNUSED_PARAMETER(NotUsed); 2825 2826 if( skipCreateTable(ctx, zSql, &iOff) ) return; 2827 2828 for(ii=0; ii<=iCol || (iCol<0 && t!=TK_RP); ii++){ 2829 iOff += getConstraintToken(&zSql[iOff], &t); 2830 while( 1 ){ 2831 int nTok = getConstraintToken(&zSql[iOff], &t); 2832 if( t==TK_COMMA || t==TK_RP ) break; 2833 if( t==TK_ILLEGAL ){ 2834 sqlite3_result_error_code(ctx, SQLITE_CORRUPT_BKPT); 2835 return; 2836 } 2837 iOff += nTok; 2838 } 2839 } 2840 2841 iOff += getWhitespace(&zSql[iOff]); 2842 2843 pNew = sqlite3_str_new(sqlite3_context_db_handle(ctx)); 2844 sqlite3_str_append(pNew, (const char*)zSql, iOff); 2845 if( iCol<0 ) sqlite3_str_append(pNew, ",", 1); 2846 sqlite3_str_appendf(pNew, " %s%s", zCons, &zSql[iOff]); 2847 sqlite3_result_str(ctx, pNew, SQLITE_FINISH); 2848 } 2849 2850 /* 2851 ** Find a column named pCol in table pTab. If successful, set output 2852 ** parameter *piCol to the index of the column in the table and return 2853 ** SQLITE_OK. Otherwise, set *piCol to -1 and return an SQLite error 2854 ** code. 2855 */ 2856 static int alterFindCol(Parse *pParse, Table *pTab, Token *pCol, int *piCol){ 2857 sqlite3 *db = pParse->db; 2858 char *zName = sqlite3NameFromToken(db, pCol); 2859 int rc = SQLITE_NOMEM; 2860 int iCol = -1; 2861 2862 if( zName ){ 2863 iCol = sqlite3ColumnIndex(pTab, zName); 2864 if( iCol<0 ){ 2865 sqlite3ErrorMsg(pParse, "no such column: %s", zName); 2866 rc = SQLITE_ERROR; 2867 }else{ 2868 rc = SQLITE_OK; 2869 } 2870 } 2871 2872 #ifndef SQLITE_OMIT_AUTHORIZATION 2873 if( rc==SQLITE_OK ){ 2874 const char *zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName; 2875 const char *zCol = pTab->aCol[iCol].zCnName; 2876 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){ 2877 pTab = 0; 2878 } 2879 } 2880 #endif 2881 2882 sqlite3DbFree(db, zName); 2883 *piCol = iCol; 2884 return rc; 2885 } 2886 2887 2888 /* 2889 ** Find the table named by the first entry in source list pSrc. If successful, 2890 ** return a pointer to the Table structure and set output variable (*pzDb) 2891 ** to point to the name of the database containin the table (i.e. "main", 2892 ** "temp" or the name of an attached database). 2893 ** 2894 ** If the table cannot be located, return NULL. The value of the two output 2895 ** parameters is undefined in this case. 2896 */ 2897 static Table *alterFindTable( 2898 Parse *pParse, /* Parsing context */ 2899 SrcList *pSrc, /* Name of the table to look for */ 2900 int *piDb, /* OUT: write the iDb here */ 2901 const char **pzDb, /* OUT: write name of schema here */ 2902 int bAuth /* Do ALTER TABLE authorization checks if true */ 2903 ){ 2904 sqlite3 *db = pParse->db; 2905 Table *pTab = 0; 2906 assert( sqlite3BtreeHoldsAllMutexes(db) ); 2907 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]); 2908 if( pTab ){ 2909 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema); 2910 *pzDb = db->aDb[iDb].zDbSName; 2911 *piDb = iDb; 2912 2913 if( SQLITE_OK!=isRealTable(pParse, pTab, 2) 2914 || SQLITE_OK!=isAlterableTable(pParse, pTab) 2915 ){ 2916 pTab = 0; 2917 } 2918 } 2919 #ifndef SQLITE_OMIT_AUTHORIZATION 2920 if( pTab && bAuth ){ 2921 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, *pzDb, pTab->zName, 0) ){ 2922 pTab = 0; 2923 } 2924 } 2925 #endif 2926 sqlite3SrcListDelete(db, pSrc); 2927 return pTab; 2928 } 2929 2930 /* 2931 ** Generate bytecode for one of: 2932 ** 2933 ** (1) ALTER TABLE pSrc DROP CONSTRAINT pCons 2934 ** (2) ALTER TABLE pSrc ALTER pCol DROP NOT NULL 2935 ** 2936 ** One of pCons and pCol must be NULL and the other non-null. 2937 */ 2938 void sqlite3AlterDropConstraint( 2939 Parse *pParse, /* Parsing context */ 2940 SrcList *pSrc, /* The table being altered */ 2941 Token *pCons, /* Name of the constraint to drop */ 2942 Token *pCol /* Name of the column from which to remove the NOT NULL */ 2943 ){ 2944 sqlite3 *db = pParse->db; 2945 Table *pTab = 0; 2946 int iDb = 0; 2947 const char *zDb = 0; 2948 char *zArg = 0; 2949 2950 assert( (pCol==0)!=(pCons==0) ); 2951 assert( pSrc->nSrc==1 ); 2952 pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, pCons!=0); 2953 if( !pTab ) return; 2954 2955 if( pCons ){ 2956 char *z = sqlite3NameFromToken(db, pCons); 2957 zArg = sqlite3MPrintf(db, "%Q", z); 2958 sqlite3DbFree(db, z); 2959 }else{ 2960 int iCol; 2961 if( alterFindCol(pParse, pTab, pCol, &iCol) ) return; 2962 zArg = sqlite3MPrintf(db, "%d", iCol); 2963 } 2964 2965 /* Edit the SQL for the named table. */ 2966 sqlite3NestedParse(pParse, 2967 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 2968 "sql = sqlite_drop_constraint(sql, %s) " 2969 "WHERE type='table' AND tbl_name=%Q COLLATE nocase" 2970 , zDb, zArg, pTab->zName 2971 ); 2972 sqlite3DbFree(db, zArg); 2973 2974 /* Finally, reload the database schema. */ 2975 renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); 2976 } 2977 2978 /* 2979 ** The implementation of SQL function sqlite_fail(MSG). This takes a single 2980 ** argument, and returns it as an error message with the error code set to 2981 ** SQLITE_CONSTRAINT. 2982 */ 2983 static void failConstraintFunc( 2984 sqlite3_context *ctx, 2985 int NotUsed, 2986 sqlite3_value **argv 2987 ){ 2988 const char *zText = (const char*)sqlite3_value_text(argv[0]); 2989 int err = sqlite3_value_int(argv[1]); 2990 (void)NotUsed; 2991 sqlite3_result_error(ctx, zText, -1); 2992 sqlite3_result_error_code(ctx, err); 2993 } 2994 2995 /* 2996 ** Prepare a statement of the form: 2997 ** 2998 ** ALTER TABLE pSrc ALTER pCol SET NOT NULL 2999 */ 3000 void sqlite3AlterSetNotNull( 3001 Parse *pParse, /* Parsing context */ 3002 SrcList *pSrc, /* Name of the table being altered */ 3003 Token *pCol, /* Name of the column to add a NOT NULL constraint to */ 3004 Token *pFirst /* The NOT token of the NOT NULL constraint text */ 3005 ){ 3006 Table *pTab = 0; 3007 int iCol = 0; 3008 int iDb = 0; 3009 const char *zDb = 0; 3010 const char *pCons = 0; 3011 int nCons = 0; 3012 3013 /* Look up the table being altered. */ 3014 assert( pSrc->nSrc==1 ); 3015 pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, 0); 3016 if( !pTab ) return; 3017 3018 /* Find the column being altered. */ 3019 if( alterFindCol(pParse, pTab, pCol, &iCol) ){ 3020 return; 3021 } 3022 3023 /* Find the length in bytes of the constraint definition */ 3024 pCons = pFirst->z; 3025 nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons); 3026 3027 /* Search for a constraint violation. Throw an exception if one is found. */ 3028 sqlite3NestedParse(pParse, 3029 "SELECT sqlite_fail('constraint failed', %d) " 3030 "FROM %Q.%Q AS x WHERE x.%.*s IS NULL", 3031 SQLITE_CONSTRAINT, zDb, pTab->zName, (int)pCol->n, pCol->z 3032 ); 3033 3034 /* Edit the SQL for the named table. */ 3035 sqlite3NestedParse(pParse, 3036 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 3037 "sql = sqlite_add_constraint(sqlite_drop_constraint(sql, %d), %.*Q, %d) " 3038 "WHERE type='table' AND tbl_name=%Q COLLATE nocase" 3039 , zDb, iCol, nCons, pCons, iCol, pTab->zName 3040 ); 3041 3042 /* Finally, reload the database schema. */ 3043 renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); 3044 } 3045 3046 /* 3047 ** Implementation of internal SQL function: 3048 ** 3049 ** sqlite_find_constraint(SQL, CONSTRAINT-NAME) 3050 ** 3051 ** This function returns true if the SQL passed as the first argument is a 3052 ** CREATE TABLE that contains a constraint with the name CONSTRAINT-NAME, 3053 ** or false otherwise. 3054 */ 3055 static void findConstraintFunc( 3056 sqlite3_context *ctx, 3057 int NotUsed, 3058 sqlite3_value **argv 3059 ){ 3060 const u8 *zSql = 0; 3061 const u8 *zCons = 0; 3062 int iOff = 0; 3063 int t = 0; 3064 3065 (void)NotUsed; 3066 zSql = sqlite3_value_text(argv[0]); 3067 zCons = sqlite3_value_text(argv[1]); 3068 3069 if( zSql==0 || zCons==0 ) return; 3070 while( t!=TK_LP && t!=TK_ILLEGAL ){ 3071 iOff += sqlite3GetToken(&zSql[iOff], &t); 3072 } 3073 3074 while( 1 ){ 3075 iOff += getConstraintToken(&zSql[iOff], &t); 3076 if( t==TK_CONSTRAINT ){ 3077 int nTok = 0; 3078 int cmp = 0; 3079 iOff += getWhitespace(&zSql[iOff]); 3080 nTok = getConstraintToken(&zSql[iOff], &t); 3081 if( quotedCompare(ctx, t, &zSql[iOff], nTok, zCons, &cmp) ) return; 3082 if( cmp==0 ){ 3083 sqlite3_result_int(ctx, 1); 3084 return; 3085 } 3086 }else if( t==TK_ILLEGAL ){ 3087 break; 3088 } 3089 } 3090 3091 sqlite3_result_int(ctx, 0); 3092 } 3093 3094 /* 3095 ** Generate bytecode to implement: 3096 ** 3097 ** ALTER TABLE pSrc ADD [CONSTRAINT pName] CHECK(pExpr) 3098 ** 3099 ** Any "ON CONFLICT" text that occurs after the "CHECK(...)", up 3100 ** until pParse->sLastToken, is included as part of the new constraint. 3101 */ 3102 void sqlite3AlterAddConstraint( 3103 Parse *pParse, /* Parse context */ 3104 SrcList *pSrc, /* Table to add constraint to */ 3105 Token *pFirst, /* First token of new constraint */ 3106 Token *pName, /* Name of new constraint. NULL if name omitted. */ 3107 const char *zExpr, /* Text of CHECK expression */ 3108 int nExpr, /* Size of pExpr in bytes */ 3109 Expr *pExpr /* The parsed CHECK expression */ 3110 ){ 3111 Table *pTab = 0; /* Table identified by pSrc */ 3112 int iDb = 0; /* Which schema does pTab live in */ 3113 const char *zDb = 0; /* Name of the schema in which pTab lives */ 3114 const char *pCons = 0; /* Text of the constraint */ 3115 int nCons; /* Bytes of text to use from pCons[] */ 3116 int rc; /* Result from error checking pExpr */ 3117 3118 /* Look up the table being altered. */ 3119 assert( pSrc->nSrc==1 ); 3120 pTab = alterFindTable(pParse, pSrc, &iDb, &zDb, 1); 3121 if( !pTab ){ 3122 sqlite3ExprDelete(pParse->db, pExpr); 3123 return; 3124 } 3125 3126 /* Verify that the new CHECK constraint does not contain any 3127 ** internal-use-only function. Forum post 2026-05-10T01:11:28Z 3128 */ 3129 rc = sqlite3ResolveSelfReference(pParse, pTab, NC_IsCheck, pExpr, 0); 3130 sqlite3ExprDelete(pParse->db, pExpr); 3131 if( rc ) return; 3132 3133 /* If this new constraint has a name, check that it is not a duplicate of 3134 ** an existing constraint. It is an error if it is. */ 3135 if( pName ){ 3136 char *zName = sqlite3NameFromToken(pParse->db, pName); 3137 3138 sqlite3NestedParse(pParse, 3139 "SELECT sqlite_fail('constraint %q already exists', %d) " 3140 "FROM \"%w\"." LEGACY_SCHEMA_TABLE " " 3141 "WHERE type='table' AND tbl_name=%Q COLLATE nocase " 3142 "AND sqlite_find_constraint(sql, %Q)", 3143 zName, SQLITE_ERROR, zDb, pTab->zName, zName 3144 ); 3145 sqlite3DbFree(pParse->db, zName); 3146 } 3147 3148 /* Search for a constraint violation. Throw an exception if one is found. */ 3149 sqlite3NestedParse(pParse, 3150 "SELECT sqlite_fail('constraint failed', %d) " 3151 "FROM %Q.%Q WHERE (%.*s) IS FALSE", 3152 SQLITE_CONSTRAINT, zDb, pTab->zName, nExpr, zExpr 3153 ); 3154 3155 /* Edit the SQL for the named table. */ 3156 pCons = pFirst->z; 3157 nCons = alterRtrimFragment(pParse->db, pCons, pParse->sLastToken.z - pCons); 3158 3159 sqlite3NestedParse(pParse, 3160 "UPDATE \"%w\"." LEGACY_SCHEMA_TABLE " SET " 3161 "sql = sqlite_add_constraint(sql, %.*Q, -1) " 3162 "WHERE type='table' AND tbl_name=%Q COLLATE nocase" 3163 , zDb, nCons, pCons, pTab->zName 3164 ); 3165 3166 /* Finally, reload the database schema. */ 3167 renameReloadSchema(pParse, iDb, INITFLAG_AlterDropCons); 3168 } 3169 3170 /* 3171 ** Register built-in functions used to help implement ALTER TABLE 3172 */ 3173 void sqlite3AlterFunctions(void){ 3174 static FuncDef aAlterTableFuncs[] = { 3175 INTERNAL_FUNCTION(sqlite_rename_column, 9, renameColumnFunc), 3176 INTERNAL_FUNCTION(sqlite_rename_table, 7, renameTableFunc), 3177 INTERNAL_FUNCTION(sqlite_rename_test, 7, renameTableTest), 3178 INTERNAL_FUNCTION(sqlite_drop_column, 3, dropColumnFunc), 3179 INTERNAL_FUNCTION(sqlite_rename_quotefix,2, renameQuotefixFunc), 3180 INTERNAL_FUNCTION(sqlite_drop_constraint,2, dropConstraintFunc), 3181 INTERNAL_FUNCTION(sqlite_fail, 2, failConstraintFunc), 3182 INTERNAL_FUNCTION(sqlite_add_constraint, 3, addConstraintFunc), 3183 INTERNAL_FUNCTION(sqlite_find_constraint,2, findConstraintFunc) 3184 }; 3185 sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs)); 3186 } 3187 #endif /* SQLITE_ALTER_TABLE */