An environment holds an unnamed main database and, if max_dbs allows, any
number of named ones. Named databases are independent key spaces: the same
key may appear in several with different values, and mdbx_keys() on one
never sees another's.
Arguments
- txn
An
mdbx_txnobject, frommdbx_txn_begin(). Creating a database needs a write transaction; opening an existing one does not.- name
The database's name, a single string.
- create
If
TRUE, create the database when it does not exist — which needs a write transaction, and is refused in a read one. IfFALSE, opening a database that was never created is an error naming it.
Value
An mdbx_dbi object, to pass as the db argument of mdbx_get(),
mdbx_put(), mdbx_del(), mdbx_keys() and mdbx_items().
Details
The database is opened for the duration of this transaction and re-resolved
by name in later ones, so the returned handle stays usable for the life of
the environment — but only if the transaction that created it commits.
If it aborts, the database was never created and the handle refers to
nothing; passing it as db then reports the database as missing, naming it.
Opening a database that does not exist is an error rather than NULL: a
name is something you wrote, so a mistyped one is worth reporting where it
was written. To find out whether one exists without handling an error, look
for it in mdbx_dbi_list().
Reserve capacity with max_dbs in mdbx_env_open() before opening any: the
libmdbx default leaves no room for named databases at all, and running out
reports MDBX_DBS_FULL.
See also
mdbx_dbi_list(), mdbx_dbi_drop(), mdbx_env_open() for
max_dbs
Examples
path <- tempfile(fileext = ".mdbx")
env <- mdbx_env_open(path, max_dbs = 8)
mdbx_with_write(env, function(txn) {
files <- mdbx_dbi_open(txn, "files", create = TRUE)
metadata <- mdbx_dbi_open(txn, "metadata", create = TRUE)
mdbx_put(txn, "abc", "/data/abc.parquet", db = files)
mdbx_put(txn, "abc", '{"size":1234}', db = metadata)
})
# The same key, two databases, two values.
mdbx_with_read(env, function(txn) {
c(files = mdbx_get(txn, "abc", db = mdbx_dbi_open(txn, "files")),
metadata = mdbx_get(txn, "abc", db = mdbx_dbi_open(txn, "metadata")))
})
#> files metadata
#> "/data/abc.parquet" "{\"size\":1234}"
# Opening one that was never created is an error, so a reader that does not
# know which exist yet asks rather than catching.
mdbx_with_read(env, function(txn) {
c("files" %in% mdbx_dbi_list(txn), "sizes" %in% mdbx_dbi_list(txn))
})
#> [1] TRUE FALSE
mdbx_env_close(env)
unlink(c(path, paste0(path, "-lck")))