1/*- 2 * See the file LICENSE for redistribution information. 3 * 4 * Copyright (c) 2002,2008 Oracle. All rights reserved. 5 * 6 * $Id: Database.java,v 12.11 2008/04/02 13:43:38 bschmeck Exp $ 7 */ 8 9package com.sleepycat.db; 10 11import com.sleepycat.db.internal.Db; 12import com.sleepycat.db.internal.DbConstants; 13import com.sleepycat.db.internal.DbSequence; 14import com.sleepycat.db.internal.Dbc; 15 16/** 17A database handle. 18<p> 19Database attributes are specified in the {@link com.sleepycat.db.DatabaseConfig DatabaseConfig} class. 20<p> 21Database handles are free-threaded unless opened in an environment 22that is not free-threaded. 23<p> 24To open an existing database with default attributes: 25<blockquote><pre> 26 Environment env = new Environment(home, null); 27 Database myDatabase = env.openDatabase(null, "mydatabase", null); 28</pre></blockquote> 29To create a transactional database that supports duplicates: 30<blockquote><pre> 31 DatabaseConfig dbConfig = new DatabaseConfig(); 32 dbConfig.setTransactional(true); 33 dbConfig.setAllowCreate(true); 34 dbConfig.setSortedDuplicates(true); 35 Database newlyCreateDb = env.openDatabase(txn, "mydatabase", dbConfig); 36</pre></blockquote> 37*/ 38public class Database { 39 Db db; 40 private int autoCommitFlag; 41 int rmwFlag; 42 43 /* package */ 44 Database(final Db db) 45 throws DatabaseException { 46 47 this.db = db; 48 db.wrapper = this; 49 this.autoCommitFlag = 50 db.get_transactional() ? DbConstants.DB_AUTO_COMMIT : 0; 51 rmwFlag = ((db.get_env().get_open_flags() & 52 DbConstants.DB_INIT_LOCK) != 0) ? DbConstants.DB_RMW : 0; 53 } 54 55 /** 56 Open a database. 57<p> 58The database is represented by the file and database parameters. 59<p> 60The currently supported database file formats (or <em>access 61methods</em>) are Btree, Hash, Queue, and Recno. The Btree format is a 62representation of a sorted, balanced tree structure. The Hash format 63is an extensible, dynamic hashing scheme. The Queue format supports 64fast access to fixed-length records accessed sequentially or by logical 65record number. The Recno format supports fixed- or variable-length 66records, accessed sequentially or by logical record number, and 67optionally backed by a flat text file. 68<p> 69Storage and retrieval are based on key/data pairs; see {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} 70for more information. 71<p> 72Opening a database is a relatively expensive operation, and maintaining 73a set of open databases will normally be preferable to repeatedly 74opening and closing the database for each new query. 75<p> 76In-memory databases never intended to be preserved on disk may be 77created by setting both the fileName and databaseName parameters to 78null. Note that in-memory databases can only ever be shared by sharing 79the single database handle that created them, in circumstances where 80doing so is safe. The environment variable <code>TMPDIR</code> may 81be used as a directory in which to create temporary backing files. 82<p> 83@param filename 84The name of an underlying file that will be used to back the database. 85On Windows platforms, this argument will be interpreted as a UTF-8 86string, which is equivalent to ASCII for Latin characters. 87<p> 88@param databaseName 89An optional parameter that allows applications to have multiple 90databases in a single file. Although no databaseName parameter needs 91to be specified, it is an error to attempt to open a second database in 92a physical file that was not initially created using a databaseName 93parameter. Further, the databaseName parameter is not supported by the 94Queue format. 95<p> 96@param config The database open attributes. If null, default attributes are used. 97 */ 98 public Database(final String filename, 99 final String databaseName, 100 final DatabaseConfig config) 101 throws DatabaseException, java.io.FileNotFoundException { 102 103 this(DatabaseConfig.checkNull(config).openDatabase(null, null, 104 filename, databaseName)); 105 // Set up dbenv.wrapper 106 new Environment(db.get_env()); 107 } 108 109 /** 110 Flush any cached database information to disk and discard the database 111handle. 112<p> 113The database handle should not be closed while any other handle that 114refers to it is not yet closed; for example, database handles should not 115be closed while cursor handles into the database remain open, or 116transactions that include operations on the database have not yet been 117committed or aborted. Specifically, this includes {@link com.sleepycat.db.Cursor Cursor} and 118{@link com.sleepycat.db.Transaction Transaction} handles. 119<p> 120Because key/data pairs are cached in memory, failing to sync the file 121with the {@link com.sleepycat.db.Database#close Database.close} or {@link com.sleepycat.db.Database#sync Database.sync} methods 122may result in inconsistent or lost information. 123<p> 124When multiple threads are using the {@link com.sleepycat.db.Database Database} handle 125concurrently, only a single thread may call this method. 126<p> 127The database handle may not be accessed again after this method is 128called, regardless of the method's success or failure. 129<p> 130When called on a database that is the primary database for a secondary 131index, the primary database should be closed only after all secondary 132indices which reference it have been closed. 133@param noSync 134Do not flush cached information to disk. The noSync parameter is a 135dangerous option. It should be set only if the application is doing 136logging (with transactions) so that the database is recoverable after a 137system or application crash, or if the database is always generated from 138scratch after any system or application crash. 139<b> 140It is important to understand that flushing cached information to disk 141only minimizes the window of opportunity for corrupted data. 142<p> 143</b> 144Although unlikely, it is possible for database corruption to happen if 145a system or application crash occurs while writing data to the database. 146To ensure that database corruption never occurs, applications must 147either: use transactions and logging with automatic recovery; use 148logging and application-specific recovery; or edit a copy of the 149database, and once all applications using the database have successfully 150called this method, atomically replace the original database with the 151updated copy. 152<p> 153<p> 154@throws DatabaseException if a failure occurs. 155 */ 156 public void close(final boolean noSync) 157 throws DatabaseException { 158 159 db.close(noSync ? DbConstants.DB_NOSYNC : 0); 160 } 161 162 /** 163 Flush any cached database information to disk and discard the database 164handle. 165<p> 166The database handle should not be closed while any other handle that 167refers to it is not yet closed; for example, database handles should not 168be closed while cursor handles into the database remain open, or 169transactions that include operations on the database have not yet been 170committed or aborted. Specifically, this includes {@link com.sleepycat.db.Cursor Cursor} and 171{@link com.sleepycat.db.Transaction Transaction} handles. 172<p> 173Because key/data pairs are cached in memory, failing to sync the file 174with the {@link com.sleepycat.db.Database#close Database.close} or {@link com.sleepycat.db.Database#sync Database.sync} methods 175may result in inconsistent or lost information. 176<p> 177When multiple threads are using the {@link com.sleepycat.db.Database Database} handle 178concurrently, only a single thread may call this method. 179<p> 180The database handle may not be accessed again after this method is 181called, regardless of the method's success or failure. 182<p> 183When called on a database that is the primary database for a secondary 184index, the primary database should be closed only after all secondary 185indices which reference it have been closed. 186<p> 187<p> 188@throws DatabaseException if a failure occurs. 189 */ 190 public void close() 191 throws DatabaseException { 192 193 close(false); 194 } 195 196 /** 197 Compact a Btree or Recno database or returns unused Btree, 198 Hash or Recno database pages to the underlying filesystem. 199 @param txn 200 If the operation is part of an application-specified transaction, the txnid 201 parameter is a transaction handle returned from {@link 202 Environment#beginTransaction}, otherwise <code>null</code>. 203 If no transaction handle is specified, but the operation occurs in a 204 transactional database, the operation will be implicitly transaction 205 protected using multiple transactions. Transactions will be comitted at 206 points to avoid holding much of the tree locked. 207 Any deadlocks encountered will be cause the operation to retried from 208 the point of the last commit. 209 @param start 210 If not <code>null</code>, the <code>start</code> parameter is the starting 211 point for compaction in a Btree or Recno database. Compaction will start 212 at the smallest key greater than or equal to the specified key. If 213 <code>null</code>, compaction will start at the beginning of the database. 214 @param stop 215 If not <code>null</code>, the <code>stop</code> parameter is the stopping 216 point for compaction in a Btree or Recno database. Compaction will stop at 217 the page with the smallest key greater than the specified key. If 218 <code>null</code>, compaction will stop at the end of the database. 219 @param end 220 If not <code>null</code>, the <code>end</code> parameter will be filled in 221 with the key marking the end of the compaction operation in a Btree or 222 Recno database. It is generally the first key of the page where processing 223 stopped. 224 @param config The compaction operation attributes. If null, default attributes are used. 225 **/ 226 public CompactStats compact(final Transaction txn, 227 final DatabaseEntry start, 228 final DatabaseEntry stop, 229 final DatabaseEntry end, 230 CompactConfig config) 231 throws DatabaseException { 232 233 config = CompactConfig.checkNull(config); 234 CompactStats compact = new CompactStats(config.getFillPercent(), 235 config.getTimeout(), config.getMaxPages()); 236 db.compact((txn == null) ? null : txn.txn, 237 start, stop, compact, config.getFlags(), end); 238 return compact; 239 } 240 241 /** 242 Return a cursor into the database. 243 <p> 244 @param txn 245 To use a cursor for writing to a transactional database, an explicit 246 transaction must be specified. For read-only access to a transactional 247 database, the transaction may be null. For a non-transactional database, 248 the transaction must be null. 249 <p> 250 To transaction-protect cursor operations, cursors must be opened and closed 251 within the context of a transaction, and the txn parameter specifies the 252 transaction context in which the cursor will be used. 253 <p> 254 @param config 255 The cursor attributes. If null, default attributes are used. 256 <p> 257 @return 258 A database cursor. 259 <p> 260 @throws DatabaseException if a failure occurs. 261 */ 262 public Cursor openCursor(final Transaction txn, CursorConfig config) 263 throws DatabaseException { 264 265 return new Cursor(this, CursorConfig.checkNull(config).openCursor( 266 db, (txn == null) ? null : txn.txn), config); 267 } 268 269 /** 270 Open a sequence in the database. 271 <p> 272 @param txn 273 For a transactional database, an explicit transaction may be specified, or 274 null may be specified to use auto-commit. For a non-transactional 275 database, null must be specified. 276 <p> 277 @param key 278 The key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} of the sequence. 279 <p> 280 @param config 281 The sequence attributes. If null, default attributes are used. 282 <p> 283 @return 284 A sequence handle. 285 <p> 286 @throws DatabaseException if a failure occurs. 287 */ 288 public Sequence openSequence(final Transaction txn, 289 final DatabaseEntry key, 290 final SequenceConfig config) 291 throws DatabaseException { 292 293 return new Sequence(SequenceConfig.checkNull(config).openSequence( 294 db, (txn == null) ? null : txn.txn, key), config); 295 } 296 297 /** 298 Remove the sequence from the database. This method should not be called if 299 there are open handles on this sequence. 300 <p> 301 @param txn 302 For a transactional database, an explicit transaction may be specified, or 303 null may be specified to use auto-commit. For a non-transactional 304 database, null must be specified. 305 <p> 306 @param key 307 The key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} of the sequence. 308 <p> 309 @param config 310 The sequence attributes. If null, default attributes are used. 311 */ 312 public void removeSequence(final Transaction txn, 313 final DatabaseEntry key, 314 SequenceConfig config) 315 throws DatabaseException { 316 317 config = SequenceConfig.checkNull(config); 318 final DbSequence seq = config.openSequence( 319 db, (txn == null) ? null : txn.txn, key); 320 seq.remove((txn == null) ? null : txn.txn, 321 (txn == null && db.get_transactional()) ? 322 DbConstants.DB_AUTO_COMMIT | (config.getAutoCommitNoSync() ? 323 DbConstants.DB_TXN_NOSYNC : 0) : 0); 324 } 325 326 /** 327Return the database's underlying file name. 328<p> 329This method may be called at any time during the life of the application. 330<p> 331@return 332The database's underlying file name. 333 */ 334 public String getDatabaseFile() 335 throws DatabaseException { 336 337 return db.get_filename(); 338 } 339 340 /** 341Return the database name. 342<p> 343This method may be called at any time during the life of the application. 344<p> 345@return 346The database name. 347 */ 348 public String getDatabaseName() 349 throws DatabaseException { 350 351 return db.get_dbname(); 352 } 353 354 /** 355 Return this Database object's configuration. 356 <p> 357 This may differ from the configuration used to open this object if 358 the database existed previously. 359 <p> 360 @return 361 This Database object's configuration. 362 <p> 363 <p> 364@throws DatabaseException if a failure occurs. 365 */ 366 public DatabaseConfig getConfig() 367 throws DatabaseException { 368 369 return new DatabaseConfig(db); 370 } 371 372 /** 373 Change the settings in an existing database handle. 374 <p> 375 @param config The environment attributes. If null, default attributes are used. 376 <p> 377 <p> 378@throws IllegalArgumentException if an invalid parameter was specified. 379<p> 380@throws DatabaseException if a failure occurs. 381 */ 382 public void setConfig(DatabaseConfig config) 383 throws DatabaseException { 384 385 config.configureDatabase(db, getConfig()); 386 } 387 388 /** 389Return the {@link com.sleepycat.db.Environment Environment} handle for the database environment 390 underlying the {@link com.sleepycat.db.Database Database}. 391<p> 392This method may be called at any time during the life of the application. 393<p> 394@return 395The {@link com.sleepycat.db.Environment Environment} handle for the database environment 396 underlying the {@link com.sleepycat.db.Database Database}. 397<p> 398<p> 399@throws DatabaseException if a failure occurs. 400 */ 401 public Environment getEnvironment() 402 throws DatabaseException { 403 404 return db.get_env().wrapper; 405 } 406 407 /** 408Return the handle for the cache file underlying the database. 409<p> 410This method may be called at any time during the life of the application. 411<p> 412@return 413The handle for the cache file underlying the database. 414<p> 415<p> 416@throws DatabaseException if a failure occurs. 417 */ 418 public CacheFile getCacheFile() 419 throws DatabaseException { 420 421 return new CacheFile(db.get_mpf()); 422 } 423 424 /** 425 <p> 426Append the key/data pair to the end of the database. 427<p> 428The underlying database must be a Queue or Recno database. The record 429number allocated to the record is returned in the key parameter. 430<p> 431There is a minor behavioral difference between the Recno and Queue 432access methods this method. If a transaction enclosing this method 433aborts, the record number may be decremented (and later reallocated by 434a subsequent operation) in the Recno access method, but will not be 435decremented or reallocated in the Queue access method. 436<p> 437It may be useful to modify the stored data based on the generated key. 438If a callback function is specified using {@link com.sleepycat.db.DatabaseConfig#setRecordNumberAppender DatabaseConfig.setRecordNumberAppender}, it will be called after the record number has 439been selected, but before the data has been stored. 440<p> 441@param txn 442For a transactional database, an explicit transaction may be specified, or null 443may be specified to use auto-commit. For a non-transactional database, null 444must be specified. 445<p> 446@param key the key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} operated on. 447<p> 448@param data the data {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} stored. 449<p> 450<p> 451<p> 452@throws DeadlockException if the operation was selected to resolve a 453deadlock. 454<p> 455@throws DatabaseException if a failure occurs. 456 */ 457 public OperationStatus append(final Transaction txn, 458 final DatabaseEntry key, 459 final DatabaseEntry data) 460 throws DatabaseException { 461 462 return OperationStatus.fromInt( 463 db.put((txn == null) ? null : txn.txn, key, data, 464 DbConstants.DB_APPEND | ((txn == null) ? autoCommitFlag : 0))); 465 } 466 467 /** 468 Return the record number and data from the available record closest to 469the head of the queue, and delete the record. The record number will be 470returned in the <code>key</code> parameter, and the data will be returned 471in the <code>data</code> parameter. A record is available if it is not 472deleted and is not currently locked. The underlying database must be 473of type Queue for this method to be called. 474<p> 475@param txn 476For a transactional database, an explicit transaction may be specified to 477transaction-protect the operation, or null may be specified to perform the 478operation without transaction protection. For a non-transactional database, 479null must be specified. 480@param key the key 481returned as output. Its byte array does not need to be initialized by the 482caller. 483@param data the data 484returned as output. Its byte array does not need to be initialized by the 485caller. 486@param wait 487if there is no record available, this parameter determines whether the 488method waits for one to become available, or returns immediately with 489status <code>NOTFOUND</code>. 490<p> 491@return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if no matching key/data pair is 492found; {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the database is a Queue or Recno database and the specified key exists, but was never explicitly created by the application or was later deleted; otherwise, {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 493<p> 494<p> 495@throws DeadlockException if the operation was selected to resolve a 496deadlock. 497<p> 498@throws IllegalArgumentException if an invalid parameter was specified. 499<p> 500@throws DatabaseException if a failure occurs. 501 */ 502 public OperationStatus consume(final Transaction txn, 503 final DatabaseEntry key, 504 final DatabaseEntry data, 505 final boolean wait) 506 throws DatabaseException { 507 508 return OperationStatus.fromInt( 509 db.get((txn == null) ? null : txn.txn, 510 key, data, 511 (wait ? DbConstants.DB_CONSUME_WAIT : DbConstants.DB_CONSUME) | 512 ((txn == null) ? autoCommitFlag : 0))); 513 } 514 515 /** 516 Remove key/data pairs from the database. 517 <p> 518 The key/data pair associated with the specified key is discarded 519 from the database. In the presence of duplicate key values, all 520 records associated with the designated key will be discarded. 521 <p> 522 The key/data pair is also deleted from any associated secondary 523 databases. 524 <p> 525 @param txn 526For a transactional database, an explicit transaction may be specified, or null 527may be specified to use auto-commit. For a non-transactional database, null 528must be specified. 529 <p> 530 @param key the key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} operated on. 531 <p> 532 @return 533 The method will return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if the 534 specified key is not found in the database; 535 The method will return {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the 536 database is a Queue or Recno database and the specified key exists, 537 but was never explicitly created by the application or was later 538 deleted; 539 otherwise the method will return {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 540 <p> 541 <p> 542@throws DeadlockException if the operation was selected to resolve a 543deadlock. 544<p> 545@throws DatabaseException if a failure occurs. 546 */ 547 public OperationStatus delete(final Transaction txn, 548 final DatabaseEntry key) 549 throws DatabaseException { 550 551 return OperationStatus.fromInt( 552 db.del((txn == null) ? null : txn.txn, key, 553 ((txn == null) ? autoCommitFlag : 0))); 554 } 555 556 /** 557 Checks if the specified key appears in the database. 558<p> 559@param txn 560For a transactional database, an explicit transaction may be specified to 561transaction-protect the operation, or null may be specified to perform the 562operation without transaction protection. For a non-transactional database, 563null must be specified. 564<p> 565@param key the key 566used as input. It must be initialized with a non-null byte array by the 567caller. 568<p> 569@return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if no matching key/data pair is 570found; {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the database is a Queue or Recno database and the specified key exists, but was never explicitly created by the application or was later deleted; otherwise, {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 571<p> 572<p> 573@throws DeadlockException if the operation was selected to resolve a 574deadlock. 575<p> 576@throws IllegalArgumentException if an invalid parameter was specified. 577<p> 578@throws DatabaseException if a failure occurs. 579 */ 580 public OperationStatus exists(final Transaction txn, 581 final DatabaseEntry key) 582 throws DatabaseException { 583 584 return OperationStatus.fromInt( 585 db.exists((txn == null) ? null : txn.txn, key, 586 ((txn == null) ? autoCommitFlag : 0))); 587 } 588 589 /** 590 Retrieves the key/data pair with the given key. If the matching key has 591duplicate values, the first data item in the set of duplicates is returned. 592Retrieval of duplicates requires the use of {@link Cursor} operations. 593<p> 594@param txn 595For a transactional database, an explicit transaction may be specified to 596transaction-protect the operation, or null may be specified to perform the 597operation without transaction protection. For a non-transactional database, 598null must be specified. 599<p> 600@param key the key 601used as input. It must be initialized with a non-null byte array by the 602caller. 603<p> 604<p> 605@param data the data 606returned as output. Its byte array does not need to be initialized by the 607caller. 608<p> 609@param lockMode the locking attributes; if null, default attributes are used. 610<p> 611@return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if no matching key/data pair is 612found; {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the database is a Queue or Recno database and the specified key exists, but was never explicitly created by the application or was later deleted; otherwise, {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 613<p> 614<p> 615@throws DeadlockException if the operation was selected to resolve a 616deadlock. 617<p> 618@throws IllegalArgumentException if an invalid parameter was specified. 619<p> 620@throws DatabaseException if a failure occurs. 621 */ 622 public OperationStatus get(final Transaction txn, 623 final DatabaseEntry key, 624 final DatabaseEntry data, 625 final LockMode lockMode) 626 throws DatabaseException { 627 628 return OperationStatus.fromInt( 629 db.get((txn == null) ? null : txn.txn, 630 key, data, 631 LockMode.getFlag(lockMode) | 632 ((data == null) ? 0 : data.getMultiFlag()))); 633 } 634 635 /** 636 Return an estimate of the proportion of keys in the database less 637 than, equal to, and greater than the specified key. 638 <p> 639 The underlying database must be of type Btree. 640 <p> 641 This method does not retain the locks it acquires for the life of 642 the transaction, so estimates are not repeatable. 643 <p> 644 @param key 645 The key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} being compared. 646 <p> 647 @param txn 648For a transactional database, an explicit transaction may be specified to 649transaction-protect the operation, or null may be specified to perform the 650operation without transaction protection. For a non-transactional database, 651null must be specified. 652 <p> 653 @return 654 An estimate of the proportion of keys in the database less than, 655 equal to, and greater than the specified key. 656 <p> 657 <p> 658@throws DeadlockException if the operation was selected to resolve a 659deadlock. 660<p> 661@throws DatabaseException if a failure occurs. 662 */ 663 public KeyRange getKeyRange(final Transaction txn, 664 final DatabaseEntry key) 665 throws DatabaseException { 666 667 final KeyRange range = new KeyRange(); 668 db.key_range((txn == null) ? null : txn.txn, key, range, 0); 669 return range; 670 } 671 672 /** 673 Retrieves the key/data pair with the given key and data value, that is, both 674the key and data items must match. 675<p> 676@param txn 677For a transactional database, an explicit transaction may be specified to 678transaction-protect the operation, or null may be specified to perform the 679operation without transaction protection. For a non-transactional database, 680null must be specified. 681@param key the key 682used as input. It must be initialized with a non-null byte array by the 683caller. 684@param data the data 685used as input. It must be initialized with a non-null byte array by the 686caller. 687<p> 688@param lockMode the locking attributes; if null, default attributes are used. 689<p> 690@return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if no matching key/data pair is 691found; {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the database is a Queue or Recno database and the specified key exists, but was never explicitly created by the application or was later deleted; otherwise, {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 692<p> 693<p> 694@throws DeadlockException if the operation was selected to resolve a 695deadlock. 696<p> 697@throws IllegalArgumentException if an invalid parameter was specified. 698<p> 699@throws DatabaseException if a failure occurs. 700 */ 701 public OperationStatus getSearchBoth(final Transaction txn, 702 final DatabaseEntry key, 703 final DatabaseEntry data, 704 final LockMode lockMode) 705 throws DatabaseException { 706 707 return OperationStatus.fromInt( 708 db.get((txn == null) ? null : txn.txn, 709 key, data, 710 DbConstants.DB_GET_BOTH | 711 LockMode.getFlag(lockMode) | 712 ((data == null) ? 0 : data.getMultiFlag()))); 713 } 714 715 /** 716 Retrieves the key/data pair associated with the specific numbered record of the database. 717<p> 718The data field of the specified key must be a byte array containing a 719record number, as described in {@link com.sleepycat.db.DatabaseEntry DatabaseEntry}. This determines 720the record to be retrieved. 721<p> 722For this method to be called, the underlying database must be of type 723Btree, and it must have been configured to support record numbers. 724<p> 725If this method fails for any reason, the position of the cursor will be 726unchanged. 727@throws NullPointerException if a DatabaseEntry parameter is null or 728does not contain a required non-null byte array. 729<p> 730@throws DeadlockException if the operation was selected to resolve a 731deadlock. 732<p> 733@throws IllegalArgumentException if an invalid parameter was specified. 734<p> 735@throws DatabaseException if a failure occurs. 736<p> 737@param key the key 738returned as output. Its byte array does not need to be initialized by the 739caller. 740@param data the data 741returned as output. Multiple results can be retrieved by passing an object 742that is a subclass of {@link com.sleepycat.db.MultipleEntry MultipleEntry}, otherwise its byte array does not 743need to be initialized by the caller. 744@param lockMode the locking attributes; if null, default attributes are used. 745@return {@link com.sleepycat.db.OperationStatus#NOTFOUND OperationStatus.NOTFOUND} if no matching key/data pair is 746found; {@link com.sleepycat.db.OperationStatus#KEYEMPTY OperationStatus.KEYEMPTY} if the database is a Queue or Recno database and the specified key exists, but was never explicitly created by the application or was later deleted; otherwise, {@link com.sleepycat.db.OperationStatus#SUCCESS OperationStatus.SUCCESS}. 747 */ 748 public OperationStatus getSearchRecordNumber(final Transaction txn, 749 final DatabaseEntry key, 750 final DatabaseEntry data, 751 final LockMode lockMode) 752 throws DatabaseException { 753 754 return OperationStatus.fromInt( 755 db.get((txn == null) ? null : txn.txn, 756 key, data, 757 DbConstants.DB_SET_RECNO | 758 LockMode.getFlag(lockMode) | 759 ((data == null) ? 0 : data.getMultiFlag()))); 760 } 761 762 /** 763 <p> 764Store the key/data pair into the database. 765<p> 766If the key already appears in the database and duplicates are not 767configured, the existing key/data pair will be replaced. If the key 768already appears in the database and sorted duplicates are configured, 769the new data value is inserted at the correct sorted location. 770If the key already appears in the database and unsorted duplicates are 771configured, the new data value is appended at the end of the duplicate 772set. 773<p> 774@param txn 775For a transactional database, an explicit transaction may be specified, or null 776may be specified to use auto-commit. For a non-transactional database, null 777must be specified. 778<p> 779@param key the key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} operated on. 780<p> 781@param data the data {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} stored. 782<p> 783<p> 784<p> 785@throws DeadlockException if the operation was selected to resolve a 786deadlock. 787<p> 788@throws DatabaseException if a failure occurs. 789 */ 790 public OperationStatus put(final Transaction txn, 791 final DatabaseEntry key, 792 final DatabaseEntry data) 793 throws DatabaseException { 794 795 return OperationStatus.fromInt( 796 db.put((txn == null) ? null : txn.txn, 797 key, data, 798 ((txn == null) ? autoCommitFlag : 0))); 799 } 800 801 /** 802 <p> 803Store the key/data pair into the database if it does not already appear 804in the database. 805<p> 806This method may only be called if the underlying database has been 807configured to support sorted duplicates. 808(This method may not be specified to the Queue or Recno access methods.) 809<p> 810@param txn 811For a transactional database, an explicit transaction may be specified, or null 812may be specified to use auto-commit. For a non-transactional database, null 813must be specified. 814<p> 815@param key the key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} operated on. 816<p> 817@param data the data {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} stored. 818<p> 819@return 820If the key/data pair already appears in the database, this method will 821return {@link com.sleepycat.db.OperationStatus#KEYEXIST OperationStatus.KEYEXIST}. 822<p> 823<p> 824@throws DeadlockException if the operation was selected to resolve a 825deadlock. 826<p> 827@throws DatabaseException if a failure occurs. 828 */ 829 public OperationStatus putNoDupData(final Transaction txn, 830 final DatabaseEntry key, 831 final DatabaseEntry data) 832 throws DatabaseException { 833 834 return OperationStatus.fromInt( 835 db.put((txn == null) ? null : txn.txn, 836 key, data, 837 DbConstants.DB_NODUPDATA | 838 ((txn == null) ? autoCommitFlag : 0))); 839 } 840 841 /** 842 <p> 843Store the key/data pair into the database if the key does not already 844appear in the database. 845<p> 846This method will fail if the key already exists in the database, even 847if the database supports duplicates. 848<p> 849@param txn 850For a transactional database, an explicit transaction may be specified, or null 851may be specified to use auto-commit. For a non-transactional database, null 852must be specified. 853<p> 854@param key the key {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} operated on. 855<p> 856@param data the data {@link com.sleepycat.db.DatabaseEntry DatabaseEntry} stored. 857<p> 858@return 859If the key already appears in the database, this method will return 860{@link com.sleepycat.db.OperationStatus#KEYEXIST OperationStatus.KEYEXIST}. 861<p> 862<p> 863@throws DeadlockException if the operation was selected to resolve a 864deadlock. 865<p> 866@throws DatabaseException if a failure occurs. 867 */ 868 public OperationStatus putNoOverwrite(final Transaction txn, 869 final DatabaseEntry key, 870 final DatabaseEntry data) 871 throws DatabaseException { 872 873 return OperationStatus.fromInt( 874 db.put((txn == null) ? null : txn.txn, 875 key, data, 876 DbConstants.DB_NOOVERWRITE | 877 ((txn == null) ? autoCommitFlag : 0))); 878 } 879 880 /** 881 Creates a specialized join cursor for use in performing equality or 882 natural joins on secondary indices. 883 <p> 884 Each cursor in the <code>cursors</code> array must have been 885 initialized to refer to the key on which the underlying database should 886 be joined. Typically, this initialization is done by calling 887 {@link Cursor#getSearchKey Cursor.getSearchKey}. 888 <p> 889 Once the cursors have been passed to this method, they should not be 890 accessed or modified until the newly created join cursor has been 891 closed, or else inconsistent results may be returned. However, the 892 position of the cursors will not be changed by this method or by the 893 methods of the join cursor. 894 <p> 895 @param cursors an array of cursors associated with this primary 896 database. 897 <p> 898 @param config The join attributes. If null, default attributes are used. 899 <p> 900 @return 901 a specialized cursor that returns the results of the equality join 902 operation. 903 <p> 904 @throws DatabaseException if a failure occurs. 905 <p> 906 @see JoinCursor 907 */ 908 public JoinCursor join(final Cursor[] cursors, JoinConfig config) 909 throws DatabaseException { 910 911 config = JoinConfig.checkNull(config); 912 913 final Dbc[] dbcList = new Dbc[cursors.length]; 914 for (int i = 0; i < cursors.length; i++) 915 dbcList[i] = (cursors[i] == null) ? null : cursors[i].dbc; 916 917 return new JoinCursor(this, 918 db.join(dbcList, config.getFlags()), config); 919 } 920 921 /** 922 Empty the database, discarding all records it contains. 923 <p> 924 When called on a database configured with secondary indices, this 925 method truncates the primary database and all secondary indices. If 926 configured to return a count of the records discarded, the returned 927 count is the count of records discarded from the primary database. 928 <p> 929 It is an error to call this method on a database with open cursors. 930 <p> 931 @param txn 932 For a transactional database, an explicit transaction may be specified, or 933 null may be specified to use auto-commit. For a non-transactional 934 database, null must be specified. 935 <p> 936 @param countRecords 937 If true, count and return the number of records discarded. 938 <p> 939 @return 940 The number of records discarded, or -1 if returnCount is false. 941 <p> 942 @throws DeadlockException if the operation was selected to resolve a 943 deadlock. 944 <p> 945 @throws DatabaseException if a failure occurs. 946 */ 947 public int truncate(final Transaction txn, boolean countRecords) 948 throws DatabaseException { 949 950 // XXX: implement countRecords in C 951 int count = db.truncate((txn == null) ? null : txn.txn, 952 ((txn == null) ? autoCommitFlag : 0)); 953 954 return countRecords ? count : -1; 955 } 956 957 /** 958 Return database statistics. 959 <p> 960 If this method has not been configured to avoid expensive operations 961 (using the {@link com.sleepycat.db.StatsConfig#setFast StatsConfig.setFast} method), it will access 962 some of or all the pages in the database, incurring a severe 963 performance penalty as well as possibly flushing the underlying 964 buffer pool. 965 <p> 966 In the presence of multiple threads or processes accessing an active 967 database, the information returned by this method may be out-of-date. 968 <p> 969 If the database was not opened read-only and this method was not 970 configured using the {@link com.sleepycat.db.StatsConfig#setFast StatsConfig.setFast} method, cached 971 key and record numbers will be updated after the statistical 972 information has been gathered. 973 <p> 974 @param txn 975 For a transactional database, an explicit transaction may be specified to 976 transaction-protect the operation, or null may be specified to perform the 977 operation without transaction protection. For a non-transactional 978 database, null must be specified. 979 <p> 980 @param config 981 The statistics returned; if null, default statistics are returned. 982 <p> 983 @return 984 Database statistics. 985 <p> 986 @throws DeadlockException if the operation was selected to resolve a 987 deadlock. 988 <p> 989 @throws DatabaseException if a failure occurs. 990 */ 991 public DatabaseStats getStats(final Transaction txn, StatsConfig config) 992 throws DatabaseException { 993 994 return (DatabaseStats)db.stat((txn == null) ? null : txn.txn, 995 StatsConfig.checkNull(config).getFlags()); 996 } 997 998 /** 999 <p> 1000Remove a database. 1001<p> 1002If no database is specified, the underlying file specified is removed. 1003<p> 1004Applications should never remove databases with open {@link com.sleepycat.db.Database Database} 1005handles, or in the case of removing a file, when any database in the 1006file has an open handle. For example, some architectures do not permit 1007the removal of files with open system handles. On these architectures, 1008attempts to remove databases currently in use by any thread of control 1009in the system may fail. 1010<p> 1011If the database was opened within a database environment, the 1012environment variable DB_HOME may be used as the path of the database 1013environment home. 1014<p> 1015This method is affected by any database directory specified with 1016{@link com.sleepycat.db.EnvironmentConfig#addDataDir EnvironmentConfig.addDataDir}, or by setting the "set_data_dir" 1017string in the database environment's DB_CONFIG file. 1018<p> 1019The {@link com.sleepycat.db.Database Database} handle may not be accessed 1020again after this method is called, regardless of this method's success 1021or failure. 1022<p> 1023@param fileName 1024The physical file which contains the database to be removed. 1025On Windows platforms, this argument will be interpreted as a UTF-8 1026string, which is equivalent to ASCII for Latin characters. 1027<p> 1028@param databaseName 1029The database to be removed. 1030<p> 1031@param config The database remove attributes. If null, default attributes are used. 1032<p> 1033<p> 1034@throws DatabaseException if a failure occurs. 1035 */ 1036 public static void remove(final String fileName, 1037 final String databaseName, 1038 DatabaseConfig config) 1039 throws DatabaseException, java.io.FileNotFoundException { 1040 1041 final Db db = DatabaseConfig.checkNull(config).createDatabase(null); 1042 db.remove(fileName, databaseName, 0); 1043 } 1044 1045 /** 1046 <p> 1047Rename a database. 1048<p> 1049If no database name is specified, the underlying file specified is 1050renamed, incidentally renaming all of the databases it contains. 1051<p> 1052Applications should never rename databases that are currently in use. 1053If an underlying file is being renamed and logging is currently enabled 1054in the database environment, no database in the file may be open when 1055this method is called. In particular, some architectures do not permit 1056renaming files with open handles. On these architectures, attempts to 1057rename databases that are currently in use by any thread of control in 1058the system may fail. 1059<p> 1060If the database was opened within a database environment, the 1061environment variable DB_HOME may be used as the path of the database 1062environment home. 1063<p> 1064This method is affected by any database directory specified with 1065{@link com.sleepycat.db.EnvironmentConfig#addDataDir EnvironmentConfig.addDataDir}, or by setting the "set_data_dir" 1066string in the database environment's DB_CONFIG file. 1067<p> 1068The {@link com.sleepycat.db.Database Database} handle may not be accessed 1069again after this method is called, regardless of this method's success 1070or failure. 1071<p> 1072@param fileName 1073The physical file which contains the database to be renamed. 1074On Windows platforms, this argument will be interpreted as a UTF-8 1075string, which is equivalent to ASCII for Latin characters. 1076<p> 1077@param oldDatabaseName 1078The database to be renamed. 1079<p> 1080@param newDatabaseName 1081The new name of the database or file. 1082<p> 1083@param config The database rename attributes. If null, default attributes are used. 1084<p> 1085<p> 1086@throws DatabaseException if a failure occurs. 1087 */ 1088 public static void rename(final String fileName, 1089 final String oldDatabaseName, 1090 final String newDatabaseName, 1091 DatabaseConfig config) 1092 throws DatabaseException, java.io.FileNotFoundException { 1093 1094 final Db db = DatabaseConfig.checkNull(config).createDatabase(null); 1095 db.rename(fileName, oldDatabaseName, newDatabaseName, 0); 1096 } 1097 1098 /** 1099 Flush any cached information to disk. 1100 <p> 1101 If the database is in memory only, this method has no effect and 1102 will always succeed. 1103 <p> 1104 <b>It is important to understand that flushing cached information to 1105 disk only minimizes the window of opportunity for corrupted data.</b> 1106 <p> 1107 Although unlikely, it is possible for database corruption to happen 1108 if a system or application crash occurs while writing data to the 1109 database. To ensure that database corruption never occurs, 1110 applications must either: use transactions and logging with 1111 automatic recovery; use logging and application-specific recovery; 1112 or edit a copy of the database, and once all applications using the 1113 database have successfully closed the copy of the database, 1114 atomically replace the original database with the updated copy. 1115 <p> 1116 <p> 1117@throws DatabaseException if a failure occurs. 1118 */ 1119 public void sync() 1120 throws DatabaseException { 1121 1122 db.sync(0); 1123 } 1124 1125 /** 1126 Upgrade all of the databases included in the specified file. 1127 <p> 1128 If no upgrade is necessary, always returns success. 1129 <p> 1130 <b> 1131 Database upgrades are done in place and are destructive. For example, 1132 if pages need to be allocated and no disk space is available, the 1133 database may be left corrupted. Backups should be made before databases 1134 are upgraded. 1135 </b> 1136 <p> 1137 <b> 1138 The following information is only meaningful when upgrading databases 1139 from releases before the Berkeley DB 3.1 release: 1140 </b> 1141 <p> 1142 As part of the upgrade from the Berkeley DB 3.0 release to the 3.1 1143 release, the on-disk format of duplicate data items changed. To 1144 correctly upgrade the format requires applications to specify 1145 whether duplicate data items in the database are sorted or not. 1146 Configuring the database object to support sorted duplicates by the 1147 {@link com.sleepycat.db.DatabaseConfig#setSortedDuplicates DatabaseConfig.setSortedDuplicates} method informs this 1148 method that the duplicates are sorted; otherwise they are assumed 1149 to be unsorted. Incorrectly specifying this configuration 1150 information may lead to database corruption. 1151 <p> 1152 Further, because this method upgrades a physical file (including all 1153 the databases it contains), it is not possible to use this method 1154 to upgrade files in which some of the databases it includes have 1155 sorted duplicate data items, and some of the databases it includes 1156 have unsorted duplicate data items. If the file does not have more 1157 than a single database, if the databases do not support duplicate 1158 data items, or if all of the databases that support duplicate data 1159 items support the same style of duplicates (either sorted or 1160 unsorted), this method will work correctly as long as the duplicate 1161 configuration is correctly specified. Otherwise, the file cannot 1162 be upgraded using this method; it must be upgraded manually by 1163 dumping and reloading the databases. 1164 <p> 1165 Unlike all other database operations, upgrades may only be done on 1166 a system with the same byte-order as the database. 1167 <p> 1168 @param fileName 1169 The physical file containing the databases to be upgraded. 1170 <p> 1171 <p> 1172@throws DatabaseException if a failure occurs. 1173 */ 1174 public static void upgrade(final String fileName, 1175 DatabaseConfig config) 1176 throws DatabaseException, java.io.FileNotFoundException { 1177 1178 final Db db = DatabaseConfig.checkNull(config).createDatabase(null); 1179 db.upgrade(fileName, 1180 config.getSortedDuplicates() ? DbConstants.DB_DUPSORT : 0); 1181 db.close(0); 1182 } 1183 1184 /** 1185 Return if all of the databases in a file are uncorrupted. 1186 <p> 1187 This method optionally outputs the databases' key/data pairs to a 1188 file stream. 1189 <p> 1190 <b> 1191 This method does not perform any locking, even in database 1192 environments are configured with a locking subsystem. As such, it 1193 should only be used on files that are not being modified by another 1194 thread of control. 1195 </b> 1196 <p> 1197 This method may not be called after the database is opened. 1198 <p> 1199 If the database was opened within a database environment, the 1200environment variable DB_HOME may be used as the path of the database 1201environment home. 1202<p> 1203This method is affected by any database directory specified with 1204{@link com.sleepycat.db.EnvironmentConfig#addDataDir EnvironmentConfig.addDataDir}, or by setting the "set_data_dir" 1205string in the database environment's DB_CONFIG file. 1206 <p> 1207 The {@link com.sleepycat.db.Database Database} handle may not be accessed 1208again after this method is called, regardless of this method's success 1209or failure. 1210 <p> 1211 @param fileName 1212 The physical file in which the databases to be verified are found. 1213 <p> 1214 @param databaseName 1215 The database in the file on which the database checks for btree and 1216 duplicate sort order and for hashing are to be performed. This 1217 parameter should be set to null except when the operation has been 1218 been configured by {@link com.sleepycat.db.VerifyConfig#setOrderCheckOnly VerifyConfig.setOrderCheckOnly}. 1219 <p> 1220 @param dumpStream 1221 An optional file stream to which the databases' key/data pairs are 1222 written. This parameter should be set to null except when the 1223 operation has been been configured by {@link com.sleepycat.db.VerifyConfig#setSalvage VerifyConfig.setSalvage}. 1224 <p> 1225 @param verifyConfig The verify operation attributes. If null, default attributes are used. 1226 <p> 1227 @param dbConfig The database attributes. If null, default attributes are used. 1228 <p> 1229 @return 1230 True, if all of the databases in the file are uncorrupted. If this 1231 method returns false, and the operation was configured by 1232 {@link com.sleepycat.db.VerifyConfig#setSalvage VerifyConfig.setSalvage}, all of the key/data pairs in the 1233 file may not have been successfully output. 1234 <p> 1235 <p> 1236@throws DatabaseException if a failure occurs. 1237 */ 1238 public static boolean verify(final String fileName, 1239 final String databaseName, 1240 final java.io.PrintStream dumpStream, 1241 VerifyConfig verifyConfig, 1242 DatabaseConfig dbConfig) 1243 throws DatabaseException, java.io.FileNotFoundException { 1244 1245 final Db db = DatabaseConfig.checkNull(dbConfig).createDatabase(null); 1246 return db.verify(fileName, databaseName, dumpStream, 1247 VerifyConfig.checkNull(verifyConfig).getFlags()); 1248 } 1249} 1250