package com.sleepycat.dbxml.examples.gettingStarted;

import java.io.*;
import java.util.*;

import com.sleepycat.db.*;
import com.sleepycat.dbxml.examples.gettingStarted.myDbEnv;

//Class used to open and close a Berkeley Database using a transaction.
public class myDb
{
    public myDb( String dbName, myDbEnv dbEnv ) throws Throwable
    {

     dbName_ = dbName;
     dbEnv_ = dbEnv.getDbEnv();
     db_ = new Db(dbEnv_, 0);
     if (dbName_ == null) {
           throw new Exception("Error opening database. Name is null");
     }
     
     //Redirect debugging information to System.err
     db_.setErrorStream(System.err);

     //Open the database inside a transaction.
     DbTxn txn = dbEnv_.txnBegin(null, 0);
     db_.open(txn, dbName, null, Db.DB_BTREE, cFlags_, 0);
     txn.commit(0);

     //Boolean used to know whether to close the database
     // when the cleanup() method is called.
     dbIsOpen_ = true;
    }


    public Db getDatabase() { return db_; }
    public DbEnv getDbEnv() { return dbEnv_; }
    public String getDatabaseName() {return dbName_;}

    //Close the database
    public void cleanup() throws Throwable
    {
       if (dbIsOpen_)
       {
            db_.close(0);
            dbIsOpen_ = false;
       }
    }


    private DbEnv dbEnv_ = null;
    private String dbName_ = null;
    private int cFlags_ = Db.DB_CREATE;
    private boolean dbIsOpen_ = false;
    private Db db_ = null;


}
