|
Next, we open three databases ("color" and "fruit" and "cats"), in the database environment. Again, our DB database handles are declared to be free-threaded using the DB_THREAD flag, and so may be used by any number of threads we subsequently create.
int main(int argc, char *argv) { extern char *optarg; extern int optind; DB *db_cats, *db_color, *db_fruit; DB_ENV *dbenv; pthread_t ptid; int ch;while ((ch = getopt(argc, argv, "")) != EOF) switch (ch) { case '?': default: usage(); } argc -= optind; argv += optind;
env_dir_create(); env_open(&dbenv);
/* Open database: Key is fruit class; Data is specific type. */ db_open(dbenv, &db_fruit, "fruit", 0);
/* Open database: Key is a color; Data is an integer. */ db_open(dbenv, &db_color, "color", 0);
/* * Open database: * Key is a name; Data is: company name, address, cat breeds. */ db_open(dbenv, &db_cats, "cats", 1);
return (0); }
void db_open(DB_ENV *dbenv, DB **dbp, char *name, int dups) { DB *db; int ret;
/* Create the database handle. */ if ((ret = db_create(&db, dbenv, 0)) != 0) { dbenv->err(dbenv, ret, "db_create"); exit (1); }
/* Optionally, turn on duplicate data items. */ if (dups && (ret = db->set_flags(db, DB_DUP)) != 0) { dbenv->err(dbenv, ret, "db->set_flags: DB_DUP"); exit (1); }
/* * Open a database in the environment: * create if it doesn't exist * free-threaded handle * read/write owner only */ if ((ret = db->open(db, name, NULL, DB_BTREE, DB_CREATE | DB_THREAD, S_IRUSR | S_IWUSR)) != 0) { dbenv->err(dbenv, ret, "db->open: %s", name); exit (1); }
*dbp = db; }
There is no reason to wrap database opens inside of transactions. All database opens are transaction protected internally to Berkeley DB, and applications using transaction-protected environments can simply rely on files either being successfully re-created in a recovered environment, or not appearing at all.
After running this initial code, we can use the db_stat utility to display information about a database we have created:
prompt> db_stat -h TXNAPP -d color 53162 Btree magic number. 8 Btree version number. Flags: 2 Minimum keys per-page. 8192 Underlying database page size. 1 Number of levels in the tree. 0 Number of unique keys in the tree. 0 Number of data items in the tree. 0 Number of tree internal pages. 0 Number of bytes free in tree internal pages (0% ff). 1 Number of tree leaf pages. 8166 Number of bytes free in tree leaf pages (0.% ff). 0 Number of tree duplicate pages. 0 Number of bytes free in tree duplicate pages (0% ff). 0 Number of tree overflow pages. 0 Number of bytes free in tree overflow pages (0% ff). 0 Number of pages on the free list.