DBD::DBM(3)
π DBD::DBM π β the DBI driver for DBM & MLDBM files
okay bestie, welcome to DBD::DBM(3), straight out of the User Contributed Perl Documentation section of the manual. this is the page that tells you how to make DBI talk to DBM and MLDBM files, and honestly? it's giving "database management system that just works out of the box." let's get into it π
β¨ NAME β¨
DBD::DBM β a DBI driver for DBM & MLDBM files π
πΈ SYNOPSIS πΈ
use DBI;
$dbh = DBI->connect('dbi:DBM:'); # defaults to SDBM_File
$dbh = DBI->connect('DBI:DBM(RaiseError=1):'); # defaults to SDBM_File
$dbh = DBI->connect('dbi:DBM:dbm_type=DB_File'); # defaults to DB_File
$dbh = DBI->connect('dbi:DBM:dbm_mldbm=Storable'); # MLDBM with SDBM_File
# or
$dbh = DBI->connect('dbi:DBM:', undef, undef);
$dbh = DBI->connect('dbi:DBM:', undef, undef, {
f_ext => '.db/r',
f_dir => '/path/to/dbfiles/',
f_lockfile => '.lck',
dbm_type => 'BerkeleyDB',
dbm_mldbm => 'FreezeThaw',
dbm_store_metadata => 1,
dbm_berkeley_flags => {
'-Cachesize' => 1000, # set a ::Hash flag
},
});
and yeah, there are other variations on connect() as shown in the DBI docs, DBD::File metadata and the "Metadata" shown below.
use standard DBI prepare, execute, fetch, placeholders, etc., see "QUICK START" for an example π«Ά
π¦ DESCRIPTION π¦
DBD::DBM is a database management system that works right out of the box. like, no cap. if you've got a standard installation of Perl and DBI, you can already start creating, accessing, and modifying simple database tables without any further modules. and if you want more, you can add other modules (e.g., SQL::Statement, DB_File etc) for improved functionality β¨
the module uses a DBM file storage layer. DBM file storage is common on many platforms, and files can be created with it in many programming languages using different APIs. which means: in addition to creating files with DBI/SQL, you can also use DBI/SQL to access and modify files created by other DBM modules and programs β and vice versa π note that in those cases it might be necessary to use a common subset of the provided features.
DBM files are stored in binary format optimized for quick retrieval when using a key field. that optimization can be used advantageously to make DBD::DBM SQL operations that use key fields very fast. there are several different "flavors" of DBM which use different storage formats supported by perl modules such as SDBM_File and MLDBM. this module supports all of the flavors that perl supports and, when used with MLDBM, supports tables with any number of columns and insertion of Perl objects into tables π
DBD::DBM has been tested with the following DBM types: SDBM_File, NDBM_File, ODBM_File, GDBM_File, DB_File, BerkeleyDB. each type was tested both with and without MLDBM and with the Data::Dumper, Storable, FreezeThaw, YAML and JSON serializers using the DBI::SQL::Nano or the SQL::Statement engines π₯
β QUICK START β
DBD::DBM operates like all other DBD drivers β its basic syntax and operation is specified by DBI. if you're not familiar with DBI, you should start by reading DBI and the documents it points to and then come back and read this file. if you are familiar with DBI, you already know most of what you need to know to operate this module. just jump in and create a test script something like the one shown below π
you should be aware that there are several options for the SQL engine underlying DBD::DBM, see "Supported SQL syntax". there are also many options for DBM support, see especially the section on "Adding multi-column support with MLDBM".
but here's a sample to get you started π
use DBI;
my $dbh = DBI->connect('dbi:DBM:');
$dbh->{RaiseError} = 1;
for my $sql( split /;\n+/,"
CREATE TABLE user ( user_name TEXT, phone TEXT );
INSERT INTO user VALUES ('Fred Bloggs','233-7777');
INSERT INTO user VALUES ('Sanjay Patel','777-3333');
INSERT INTO user VALUES ('Junk','xxx-xxxx');
DELETE FROM user WHERE user_name = 'Junk';
UPDATE user SET phone = '999-4444' WHERE user_name = 'Sanjay Patel';
SELECT * FROM user
"){
my $sth = $dbh->prepare($sql);
$sth->execute;
$sth->dump_results if $sth->{NUM_OF_FIELDS};
}
$dbh->disconnect;
π USAGE π
this section will explain some usage cases in more detail. to get an overview about the available attributes, see "Metadata".
π Specifying Files and Directories π
DBD::DBM will automatically supply an appropriate file extension for the type of DBM you are using. for example, if you use SDBM_File, a table called "fruit" will be stored in two files called fruit.pag and fruit.dir. you should never specify the file extensions in your SQL statements, bestie. just don't.
DBD::DBM recognizes following default extensions for following types:
.pag/rβ chosen for dbm_typeSDBM_File,ODBM_FileandNDBM_Filewhen an implementation is detected which wraps-ldbmforNDBM_File(e.g. Solaris, AIX, ...). for those types, the.dirextension is recognized, too (for being deleted when dropping a table)..db/rβ chosen for dbm_typeNDBM_Filewhen an implementation is detected which wraps BerkeleyDB 1.x forNDBM_File(typically BSD's, Darwin).
GDBM_File, DB_File and BerkeleyDB don't usually use a file extension.
if your DBM type uses an extension other than one of the recognized types of extensions, you should set the f_ext attribute to the extension and file a bug report as described in DBI with the name of the implementation and extension so we can add it to DBD::DBM. thanks in advance for that :-) π«Ά
$dbh = DBI->connect('dbi:DBM:f_ext=.db'); # .db extension is used
$dbh = DBI->connect('dbi:DBM:f_ext='); # no extension is used
# or
$dbh->{f_ext}='.db'; # global setting
$dbh->{f_meta}->{'qux'}->{f_ext}='.db'; # setting for table 'qux'
by default files are assumed to be in the current working directory. to use other directories specify the f_dir attribute in either the connect string or by setting the database handle attribute.
for example, this will look for the file /foo/bar/fruit (or /foo/bar/fruit.pag for DBM types that use that extension) π
my $dbh = DBI->connect('dbi:DBM:f_dir=/foo/bar');
# and this will too:
my $dbh = DBI->connect('dbi:DBM:');
$dbh->{f_dir} = '/foo/bar';
# but this is recommended
my $dbh = DBI->connect('dbi:DBM:', undef, undef, { f_dir => '/foo/bar' } );
# now you can do
my $ary = $dbh->selectall_arrayref(q{ SELECT x FROM fruit });
you can also use delimited identifiers to specify paths directly in SQL statements. this looks in the same place as the two examples above but without setting f_dir:
my $dbh = DBI->connect('dbi:DBM:');
my $ary = $dbh->selectall_arrayref(q{
SELECT x FROM "/foo/bar/fruit"
});
you can also tell DBD::DBM to use a specified path for a specific table:
$dbh->{dbm_tables}->{f}->{file} = q(/foo/bar/fruit);
please be aware that you cannot specify this during connection. π
if you have SQL::Statement installed, you can use table aliases:
my $dbh = DBI->connect('dbi:DBM:');
my $ary = $dbh->selectall_arrayref(q{
SELECT f.x FROM "/foo/bar/fruit" AS f
});
see the "GOTCHAS AND WARNINGS" for using DROP on tables.
π Table locking and flock() π
table locking is accomplished using a lockfile which has the same basename as the table's file but with the file extension .lck (or a lockfile extension that you supply, see below). this lock file is created with the table during a CREATE and removed during a DROP. every time the table itself is opened, the lockfile is flocked. for SELECT, this is a shared lock. for all other operations, it is an exclusive lock (except when you specify something different using the f_lock attribute).
since the locking depends on flock(), it only works on operating systems that support flock(). in cases where flock() is not implemented, DBD::DBM will simply behave as if the flock() had occurred although no actual locking will happen. read the documentation for flock() for more information.
even on those systems that do support flock(), locking is only advisory β as is always the case with flock(). this means that if another program tries to access the table file while DBD::DBM has the table locked, that other program will succeed at opening unless it is also using flock on the .lck file. as a result DBD::DBM's locking only really applies to other programs using DBD::DBM or other program written to cooperate with DBD::DBM locking π
π Specifying the DBM type π
each "flavor" of DBM stores its files in a different format and has different capabilities and limitations. see AnyDBM_File for a comparison of DBM types.
by default, DBD::DBM uses the SDBM_File type of storage since SDBM_File comes with Perl itself. if you have other types of DBM storage available, you can use any of them with DBD::DBM. it is strongly recommended to use at least DB_File, because SDBM_File has quirks and limitations and ODBM_file, NDBM_File and GDBM_File are not always available.
you can specify the DBM type using the dbm_type attribute which can be set in the connection string or with $dbh->{dbm_type} and $dbh->{f_meta}->{$table_name}->{type} for per-table settings in cases where a single script is accessing more than one kind of DBM file.
in the connection string, just set dbm_type=TYPENAME where TYPENAME is any DBM type such as GDBM_File, DB_File, etc. do not use MLDBM as your dbm_type as that is set differently, see below π
my $dbh=DBI->connect('dbi:DBM:'); # uses the default SDBM_File
my $dbh=DBI->connect('dbi:DBM:dbm_type=GDBM_File'); # uses the GDBM_File
# You can also use $dbh->{dbm_type} to set the DBM type for the connection:
$dbh->{dbm_type} = 'DB_File'; # set the global DBM type
print $dbh->{dbm_type}; # display the global DBM type
if you have several tables in your script that use different DBM types, you can use the $dbh->{dbm_tables} hash to store different settings for the various tables. you can even use this to perform joins on files that have completely different storage mechanisms. iconic, honestly β¨
# sets global default of GDBM_File
my $dbh->('dbi:DBM:type=GDBM_File');
# overrides the global setting, but only for the tables called
# I<foo> and I<bar>
my $dbh->{f_meta}->{foo}->{dbm_type} = 'DB_File';
my $dbh->{f_meta}->{bar}->{dbm_type} = 'BerkeleyDB';
# prints the dbm_type for the table "foo"
print $dbh->{f_meta}->{foo}->{dbm_type};
note that you must change the dbm_type of a table before you access it for first time. π€
π Adding multi-column support with MLDBM π
okay bestie, so most of the DBM types only support two columns and even if it would support more, DBD::DBM would only use two. but a CPAN module called MLDBM overcomes this limitation by allowing more than two columns. MLDBM does this by serializing the data β basically it puts a reference to an array into the second column. it can also put almost any kind of Perl object or even Perl coderefs into columns. iconic.
If you want more than two columns, you must install MLDBM. It's available for many platforms and is easy to install.
MLDBM is by default distributed with three serializers β Data::Dumper, Storable, and FreezeThaw. Data::Dumper is the default and Storable is the fastest. MLDBM can also make use of user-defined serialization methods or other serialization modules (e.g. YAML::MLDBM or MLDBM::Serializer::JSON. You select the serializer using the dbm_mldbm attribute.
Some examples:
$dbh=DBI->connect('dbi:DBM:dbm_mldbm=Storable'); # use MLDBM with Storable
$dbh=DBI->connect(
'dbi:DBM:dbm_mldbm=MySerializer' # use MLDBM with a user defined module
);
$dbh=DBI->connect('dbi::dbm:', undef,
undef, { dbm_mldbm => 'YAML' }); # use 3rd party serializer
$dbh->{dbm_mldbm} = 'YAML'; # same as above
print $dbh->{dbm_mldbm} # show the MLDBM serializer
$dbh->{f_meta}->{foo}->{dbm_mldbm}='Data::Dumper'; # set Data::Dumper for table "foo"
print $dbh->{f_meta}->{foo}->{mldbm}; # show serializer for table "foo"
MLDBM works on top of other DBM modules so you can also set a DBM type along with setting dbm_mldbm. The examples above would default to using SDBM_File with MLDBM. If you wanted GDBM_File instead, here's how:
# uses DB_File with MLDBM and Storable
$dbh = DBI->connect('dbi:DBM:', undef, undef, {
dbm_type => 'DB_File',
dbm_mldbm => 'Storable',
});
SDBM_File, the default dbm_type is quite limited, so if you are going to use MLDBM, you should probably use a different type, see AnyDBM_File.
See below for some "GOTCHAS AND WARNINGS" about MLDBM.
ποΈ Support for Berkeley DB ποΈ
The Berkeley DB storage type is supported through two different Perl modules β DB_File (which supports only features in old versions of Berkeley DB) and BerkeleyDB (which supports all versions). DBD::DBM supports specifying either "DB_File" or "BerkeleyDB" as a dbm_type, with or without MLDBM support.
The "BerkeleyDB" dbm_type is experimental and its interface is likely to change. It currently defaults to BerkeleyDB::Hash and does not currently support ::Btree or ::Recno.
With BerkeleyDB, you can specify initialization flags by setting them in your script like this:
use BerkeleyDB;
my $env = new BerkeleyDB::Env -Home => $dir; # and/or other Env flags
$dbh = DBI->connect('dbi:DBM:', undef, undef, {
dbm_type => 'BerkeleyDB',
dbm_mldbm => 'Storable',
dbm_berkeley_flags => {
'DB_CREATE' => DB_CREATE, # pass in constants
'DB_RDONLY' => DB_RDONLY, # pass in constants
'-Cachesize' => 1000, # set a ::Hash flag
'-Env' => $env, # pass in an environment
},
});
β οΈ Do not set the-Flagsor-Filenameflags as those are determined and overwritten by the SQL (e.g.-Flags => DB_RDONLYis set automatically when you issue aSELECTstatement).
Time has not permitted us to provide support in this release of DBD::DBM for further Berkeley DB features such as transactions, concurrency, locking, etc. We will be working on these in the future and would value suggestions, patches, etc.
See DB_File and BerkeleyDB for further details.
β‘ Optimizing the use of key fields β‘
Most "flavors" of DBM have only two physical columns (but can contain multiple logical columns as explained above in "Adding multi-column support with MLDBM"). They work similarly to a Perl hash with the first column serving as the key. Like a Perl hash, DBM files permit you to do quick lookups by specifying the key and thus avoid looping through all records (supported by DBI::SQL::Nano only). Also like a Perl hash, the keys must be unique. It is impossible to create two records with the same key. To put this more simply and in SQL terms, the key column functions as the PRIMARY KEY or UNIQUE INDEX.
In DBD::DBM, you can take advantage of the speed of keyed lookups by using DBI::SQL::Nano and a WHERE clause with a single equal comparison on the key field. For example, the following SQL statements are optimized for keyed lookup:
CREATE TABLE user ( user_name TEXT, phone TEXT);
INSERT INTO user VALUES ('Fred Bloggs','233-7777');
# ... many more inserts
SELECT phone FROM user WHERE user_name='Fred Bloggs';
The "user_name" column is the key column since it is the first column. The SELECT statement uses the key column in a single equal comparison β "user_name='Fred Bloggs'" β so the search will find it very quickly without having to loop through all the names which were inserted into the table.
In contrast, these searches on the same table are not optimized:
1. SELECT phone FROM user WHERE user_name < 'Fred';
2. SELECT user_name FROM user WHERE phone = '233-7777';
In #1, the operation uses a less-than (<) comparison rather than an equals comparison, so it will not be optimized for key searching. In #2, the key field "user_name" is not specified in the WHERE clause, and therefore the search will need to loop through all rows to find the requested row(s).
Note that the underlying DBM storage needs to loop over all key/value pairs when the optimized fetch is used. SQL::Statement has a massively improved where clause evaluation which costs around 15% of the evaluation in DBI::SQL::Nano β combined with the loop in the DBM storage the speed improvement isn't so impressive.
Even if lookups are faster by around 50%, DBI::SQL::Nano and SQL::Statement can benefit from the key field optimizations on updating and deleting rows β and here the improved where clause evaluation of SQL::Statement might beat DBI::SQL::Nano every time the where clause contains not only the key field (or more than one).
π Updatable Keys π
The default behavior is that updating a key to the same value of an existing key will succeed, and the existing row will be overwritten.
There may be cases where this is undesirable.
This behavior can now be configured, by setting "dbm_updatable_key" attribute. To emit a warning when this happens, set it to 1:
$dbh = DBI->connect('dbi:DBM:', undef, undef, {
dbm_updatable_key => 1,
} );
To instead die when that happens, set it to 2:
$dbh = DBI->connect('dbi:DBM:', undef, undef, {
dbm_updatable_key => 2,
} );
π§ Supported SQL syntax π§
DBD::DBM uses a subset of SQL. The robustness of that subset depends on what other modules you have installed. Both options support basic SQL operations including CREATE TABLE, DROP TABLE, INSERT, DELETE, UPDATE, and SELECT.
Option #1: By default, this module inherits its SQL support from DBI::SQL::Nano that comes with DBI. Nano is, as its name implies, a very small SQL engine. Although limited in scope, it is faster than option #2 for some operations (especially single primary key lookups). See DBI::SQL::Nano for a description of the SQL it supports and comparisons of it with option #2.
Option #2: If you install the pure Perl CPAN module SQL::Statement, DBD::DBM will use it instead of Nano. This adds support for table aliases, functions, joins, and much more. If you're going to use DBD::DBM for anything other than very simple tables and queries, you should install SQL::Statement. You don't have to change DBD::DBM or your scripts in any way, simply installing SQL::Statement will give you the more robust SQL capabilities without breaking scripts written for DBI::SQL::Nano. See SQL::Statement for a description of the SQL it supports.
To find out which SQL module is working in a given script, you can use the dbm_versions() method or, if you don't need the full output and version numbers, just do this:
print $dbh->{sql_handler}, "\n";
That will print out either "SQL::Statement" or "DBI::SQL::Nano".
Baring the section about optimized access to the DBM storage in mind, comparing the benefits of both engines:
# DBI::SQL::Nano is faster
$sth = $dbh->prepare( "update foo set value='new' where key=15" );
$sth->execute();
$sth = $dbh->prepare( "delete from foo where key=27" );
$sth->execute();
$sth = $dbh->prepare( "select * from foo where key='abc'" );
# SQL::Statement might faster (depending on DB size)
$sth = $dbh->prepare( "update foo set value='new' where key=?" );
$sth->execute(15);
$sth = $dbh->prepare( "update foo set value=? where key=15" );
$sth->execute('new');
$sth = $dbh->prepare( "delete from foo where key=?" );
$sth->execute(27);
# SQL::Statement is faster
$sth = $dbh->prepare( "update foo set value='new' where value='old'" );
$sth->execute();
# must be expressed using "where key = 15 or key = 27 or key = 42 or key = 'abc'"
# in DBI::SQL::Nano
$sth = $dbh->prepare( "delete from foo where key in (15,27,42,'abc')" );
$sth->execute();
# must be expressed using "where key > 10 and key < 90" in DBI::SQL::Nano
$sth = $dbh->prepare( "select * from foo where key between (10,90)" );
$sth->execute();
# only SQL::Statement can handle
$sth->prepare( "select * from foo,bar where foo.name = bar.name" );
$sth->execute();
$sth->prepare( "insert into foo values ( 1, 'foo' ), ( 2, 'bar' )" );
$sth->execute();
π·οΈ Specifying Column Names π·οΈ
DBM files don't have a standard way to store column names. DBD::DBM gets around this issue with a DBD::DBM specific way of storing the column names. If you are working only with DBD::DBM and not using files created by or accessed with other DBM programs, you can ignore this section.
DBD::DBM stores column names as a row in the file with the key _metadata \0. So this code
my $dbh = DBI->connect('dbi:DBM:');
$dbh->do("CREATE TABLE baz (foo CHAR(10), bar INTEGER)");
$dbh->do("INSERT INTO baz (foo,bar) VALUES ('zippy',1)");
Will create a file that has a structure something like this:
_metadata \0 | <dbd_metadata><schema></schema><col_names>foo,bar</col_names></dbd_metadata>
zippy | 1
The next time you access this table with DBD::DBM, it will treat the _metadata \0 row as a header rather than as data and will pull the column names from there. However, if you access the file with something other than DBD::DBM, the row will be treated as a regular data row.
If you do not want the column names stored as a data row in the table you can set the dbm_store_metadata attribute to 0.
my $dbh = DBI->connect('dbi:DBM:', undef, undef, { dbm_store_metadata => 0 });
# or
$dbh->{dbm_store_metadata} = 0;
# or for per-table setting
$dbh->{f_meta}->{qux}->{dbm_store_metadata} = 0;
Okay so by default, DBD::DBM is just gonna assume you've got two columns named "k" and "v" (short for "key" and "value", obviously, we love a cute nickname π
). So if you've got dbm_store_metadata set to 1 and you wanna use alternate column names instead, you gotta spell them out like this:
my $dbh = DBI->connect('dbi:DBM:', undef, undef, {
dbm_store_metadata => 0,
dbm_cols => [ qw(foo bar) ],
});
# or
$dbh->{dbm_store_metadata} = 0;
$dbh->{dbm_cols} = 'foo,bar';
# or to set the column names on per-table basis, do this:
# sets the column names only for table "qux"
$dbh->{f_meta}->{qux}->{dbm_store_metadata} = 0;
$dbh->{f_meta}->{qux}->{col_names} = [qw(foo bar)];
Now listen β if you've got a file that some other DBM program made, or one that was made with dbm_store_metadata set to zero, and you wanna glow it up into DBD::DBM's column name storage? Just use one of the methods above to name the columns but without specifying dbm_store_metadata as zero. And that's it β you literally only do this once. After that you can totally skip setting either dbm_store_metadata or dbm_cols, because bestie, the names are stored in the file now. periodt. β¨
π«Ά DBI database handle attributes π«Ά
π Metadata π
π Statement handle ($sth) attributes and methods π
Most statement handle attributes β think NAME, NUM_OF_FIELDS, etc. β are only available after an execute. Same energy for $sth->rows, which you get after the execute, but lowkey it doesn't require a fetch. πΈ
π¦ Driver handle ($dbh) attributes π¦
ngl, it is not supported anymore to use dbm-attributes without the dbm_ prefix. So here's the current deal: if a DBD::DBM private attribute gets accessed without an underscore in its name, dbm_ gets prepended to that attribute and it's processed further. And if the resulting attribute name turns out to be invalid? Yeah, an error gets thrown. π
π dbm_cols
Contains a comma separated list of column names, or an array reference to the column names. easy!
π dbm_type
Contains the DBM storage type. The currently known supported types are "ODBM_File", "NDBM_File", "SDBM_File", "GDBM_File", "DB_File" and "BerkeleyDB". And no cap: it is not recommended to use one of the first three types β even if "SDBM_File" is the most commonly available dbm_type. π
β¨ dbm_mldbm
Contains the serializer for DBM storage (that's the value column). Heads up: this requires the CPAN module MLDBM installed. Currently known supported serializers are:
Data::Dumperβ the Default serializer. Deployed with Perl core. πStorableβ Faster serializer. Deployed with Perl core.FreezeThawβ Pure Perl serializer, requires FreezeThaw to be installed.YAMLβ Portable serializer (between languages but not architectures). Requires YAML::MLDBM installation.JSONβ Portable, fast serializer (between languages but not architectures). Requires MLDBM::Serializer::JSON installation.
π dbm_store_metadata
Boolean value which determines if the metadata in DBM is stored or not.
π§ dbm_berkeley_flags
Hash reference with additional flags for BerkeleyDB::Hash instantiation.
β dbm_version
Readonly attribute containing the version of DBD::DBM.
π¦ f_meta
On top of the attributes DBD::File recognizes, DBD::DBM knows about the (public) attributes "col_names" (Note not dbm_cols here!), "dbm_type", "dbm_mldbm", "dbm_store_metadata" and "dbm_berkeley_flags". And just like in DBD::File, there are undocumented, internal attributes hanging out in DBD::DBM too. So be very careful when modifying attributes you do not know β the consequence might a destroyed or corrupted table. π
π dbm_tables
This attribute provides restricted access to the table meta data. See f_meta and "f_meta" in DBD::File for attribute details.
dbm_tables is a tied hash providing the internal table names as keys (lowkey accessing unknown tables might create an entry) and their meta data as another tied hash. The table meta storage is obtained via the "get_table_meta" method from the table implementation (see DBD::File::Developers). Attribute setting and getting within the table meta data is handled via the methods "set_table_meta_attr" and "get_table_meta_attr".
Following attributes are no longer handled by DBD::DBM:
π dbm_ext
This attribute is silently mapped to DBD::File's attribute f_ext. Later versions of DBI might show a depreciated warning when this attribute is used and eventually it will be removed.
π₯ dbm_lockfile
This attribute is silently mapped to DBD::File's attribute f_lockfile. Later versions of DBI might show a depreciated warning when this attribute is used and eventually it will be removed.
π DBI database handle methods π
πΈ The $dbh->dbm_versions() method πΈ
The private method dbm_versions() returns a summary of what other modules are being used at any given time. And the way DBD::DBM is so versatile? It can work with or without many other modules β it can use either SQL::Statement or DBI::SQL::Nano as its SQL engine, it can be run with DBI or DBI::PurePerl, it can use many kinds of DBM modules, and many kinds of serializers when run with MLDBM. The dbm_versions() method reports all of that and more. π€©
print $dbh->dbm_versions; # displays global settings
print $dbh->dbm_versions($table_name); # displays per table settings
An important thing to note about this method: when it's called with no arguments, it displays the global settings. So if you override those by setting per-table attributes, bestie, those will not be shown unless you specify a table name as an argument to the method call. iykyk. π
π§ Storing Objects π§
If you are using MLDBM, you can use DBD::DBM to take advantage of its serializing abilities to serialize any Perl object that MLDBM can handle. To store objects in columns, you should (but don't absolutely need to) declare it as a column of type BLOB β the type is currently ignored by the SQL engine, but it's good form. π
π EXTENSIBILITY π
"SQL::Statement"β Improved SQL engine compared to the built-inDBI::SQL::Nanoβ see"Supported SQL syntax"."DB_File"β Berkeley DB version 1. This database library is available on many systems without additional installation and most systems are supported. β"GDBM_File"β Simple dbm type (comparable to"DB_File") under the GNU license. Typically not available (or requires extra installation) on non-GNU operating systems."BerkeleyDB"β Berkeley DB version up to v4 (and maybe higher) β requires additional installation but is easier thanGDBM_Fileon non-GNU systems.
db4 comes with a many tools which allow repairing and migrating databases. This is the recommended dbm type for production use. π
"MLDBM"β Serializer wrapper to support more than one column for the files. Comes with serializers using"Data::Dumper","FreezeThaw"and"Storable"."YAML::MLDBM"β Additional serializer for MLDBM. YAML is very portable between languages."MLDBM::Serializer::JSON"β Additional serializer for MLDBM. JSON is very portable between languages, probably more than YAML.
π GOTCHAS AND WARNINGS π
Using the SQL DROP command will remove any file that has the name specified in the command with either '.pag' and '.dir', '.db' or your {f_ext} appended to it. So yes bestie, this be dangerous if you aren't sure what file it refers to:
$dbh->do(qq{DROP TABLE "/path/to/any/file"});
Each DBM type has limitations. SDBM_File, for example, can only store values of less than 1,000 characters. You as the script author must ensure that you don't exceed those bounds. And if you try to insert a value that is larger than DBM can store? The results will be unpredictable. π See the documentation for whatever DBM you are using for details.
Different DBM implementations return records in different orders. Which means you should not rely on the order of records unless you use an ORDER BY statement.
DBM data files are platform-specific. To move them from one platform to another, you'll need to do something along the lines of dumping your data to CSV on platform #1 and then dumping from CSV to DBM on platform #2. DBD::AnyData and DBD::CSV can help with that. There may also be DBM conversion tools for your platforms which would probably be quicker.
When using MLDBM, there is a very powerful serializer β it will allow you to store Perl code or objects in database columns. When these get de-serialized, they may beeval'edβ in other words MLDBM (or actuallyData::Dumperwhen used by MLDBM) may take the values and try to execute them in Perl. Obviously, this can present dangers, so if you do not know what is in a file, be careful before you access it with MLDBM turned on! π¨
See the entire section on "Table locking and flock()" for gotchas and warnings about the use of flock().
π BUGS AND LIMITATIONS π
This module uses hash interfaces of two column file databases. While none of supported SQL engines have support for indices, the following statements really do the same (even if they mean something completely different) for each dbm type which lacks "EXISTS" support:
$sth->do( "insert into foo values (1, 'hello')" );
# this statement does ...
$sth->do( "update foo set v='world' where k=1" );
# ... the same as this statement
$sth->do( "insert into foo values (1, 'world')" );
This is considered to be a bug and might change in a future release. π
Known affected dbm types are "ODBM_File" and "NDBM_File". We highly recommended you use a more modern dbm type such as "DB_File". π
π«Ά GETTING HELP, MAKING SUGGESTIONS, AND REPORTING BUGS π
Okay bestie, stuck? It happens to literally everyone, no shame. If you need help installing or using DBD::DBM, slide into the DBI users mailing list at dbi-users@perl.org, or hit up the comp.lang.perl.modules newsgroup on usenet. Real talk tho: I can't always answer every single question fast β but there are so many people on the mailing list and in the newsgroup who absolutely can. The community ate and left no crumbs, fr fr. β¨
If you're a DBD developer whose DBD leans on DBD::File or DBD::DBM, or uses one of them as an example? You're suggested to join the DBI developers mailing list at dbi-dev@perl.org, and strongly encouraged to join our IRC channel at irc://irc.perl.org/dbi. Come thruuu, we're fun. π
Got suggestions? Ideas for improvements? Bugs? π Report a bug as described in DBI. And please do not mail any of the authors directly β you might not get an answer, and that's the saddest vibe. π
When you do report a bug, please send the output of $dbh->dbm_versions($table) for a table that exhibits the bug, plus as small a sample as you can make of the code that produces it. Tiny repro = iconic behavior. And of course, patches are welcome too :-). π§
Need enhancements quickly? You can get commercial support as described at http://dbi.perl.org/support/, or you can contact Jens Rehsack at rehsack@googlemail.com for commercial support in Germany. π
Please don't bother Jochen Wiedmann or Jeff Zucker for support β they handed over further maintenance to H.Merijn Brand and Jens Rehsack. Respect the handoff, babes. π
πΈ ACKNOWLEDGEMENTS πΈ
Many, many thanks to Tim Bunce for prodding me to write this, and for copious, wise, and patient suggestions all along the way. (Jeff Zucker) π
I send my thanks and acknowledgements to H.Merijn Brand for his initial refactoring of DBD::File and his strong and ongoing support of SQL::Statement. Without him, the current progress would never have been made. And I have to name Martin J. Evans for each laugh (and correction) of all those funny word creations I (as non-native speaker) made to the documentation. And β of course β I have to thank all those unnamed contributors and testers from the Perl community. (Jens Rehsack) π
Not me getting emotional over a changelog. It's giving community. π₯Ή
π AUTHOR AND COPYRIGHT π
This module is written by Jeff Zucker < jzucker AT cpan.org >, who also maintained it till 2007. After that, in 2010, Jens Rehsack & H.Merijn Brand took over maintenance.
Copyright (c) 2004 by Jeff Zucker, all rights reserved.
Copyright (c) 2010-2013 by Jens Rehsack & H.Merijn Brand, all rights reserved.
You may freely distribute and/or modify this module under the terms of either the GNU General Public License (GPL) or the Artistic License, as specified in the Perl README file.
Two licenses, your choice, go off. π
π SEE ALSO π
DBISQL::StatementDBI::SQL::NanoAnyDBM_FileDB_FileBerkeleyDBMLDBMYAML::MLDBMMLDBM::Serializer::JSON
And that's a wrap on DBD::DBM, bestie!! π¦ This lil corner of the docs is DBD::DBM(3) from perl v5.42.3, dated 2026-10-19. Go forth and DBM responsibly, mwah π
β¨
π¦ where this page comes from
- fedora 43: perl-DBI 1.656-1.fc43 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- fedora 44: perl-DBI 1.656-1.fc44 Β· GPL-1.0-or-later OR Artistic-1.0-Perl
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms