/* package */
  DbSequence openSequence(final Db db, final DbTxn txn, final DatabaseEntry key)
      throws DatabaseException {

    final DbSequence seq = createSequence(db);
    // The DB_THREAD flag is inherited from the database
    boolean threaded = ((db.get_open_flags() & DbConstants.DB_THREAD) != 0);

    int openFlags = 0;
    openFlags |= allowCreate ? DbConstants.DB_CREATE : 0;
    openFlags |= exclusiveCreate ? DbConstants.DB_EXCL : 0;
    openFlags |= threaded ? DbConstants.DB_THREAD : 0;

    if (db.get_transactional() && txn == null) openFlags |= DbConstants.DB_AUTO_COMMIT;

    configureSequence(seq, DEFAULT);
    boolean succeeded = false;
    try {
      seq.open(txn, key, openFlags);
      succeeded = true;
      return seq;
    } finally {
      if (!succeeded)
        try {
          seq.close(0);
        } catch (Throwable t) {
          // Ignore it -- an exception is already in flight.
        }
    }
  }
  /* package */
  void configureSequence(final DbSequence seq, final SequenceConfig oldConfig)
      throws DatabaseException {

    int seqFlags = 0;
    seqFlags |= decrement ? DbConstants.DB_SEQ_DEC : DbConstants.DB_SEQ_INC;
    seqFlags |= wrap ? DbConstants.DB_SEQ_WRAP : 0;

    if (seqFlags != 0) seq.set_flags(seqFlags);

    if (rangeMin != oldConfig.rangeMin || rangeMax != oldConfig.rangeMax)
      seq.set_range(rangeMin, rangeMax);

    if (initialValue != oldConfig.initialValue) seq.initial_value(initialValue);

    if (cacheSize != oldConfig.cacheSize) seq.set_cachesize(cacheSize);
  }
  /* package */
  SequenceConfig(final DbSequence seq) throws DatabaseException {

    // XXX: can't get open flags
    final int openFlags = 0;
    allowCreate = (openFlags & DbConstants.DB_CREATE) != 0;
    exclusiveCreate = (openFlags & DbConstants.DB_EXCL) != 0;

    final int seqFlags = seq.get_flags();
    decrement = (seqFlags & DbConstants.DB_SEQ_DEC) != 0;
    wrap = (seqFlags & DbConstants.DB_SEQ_WRAP) != 0;

    // XXX: can't get initial value
    final long initialValue = 0;

    cacheSize = seq.get_cachesize();

    rangeMin = seq.get_range_min();
    rangeMax = seq.get_range_max();
  }