DBI(3pm)
πΈ NAME πΈ
AnyEvent::DBI β asynchronous DBI access β¨
(yes bestie, this is the DBI(3pm) page, buckle up π
)
π¦ SYNOPSIS π¦
use AnyEvent::DBI;
my $cv = AnyEvent->condvar;
my $dbh = new AnyEvent::DBI "DBI:SQLite:dbname=test.db", "", "";
$dbh->exec ("select * from test where num=?", 10, sub {
my ($dbh, $rows, $rv) = @_;
$#_ or die "failure: $@";
print "@$_\n"
for @$rows;
$cv->broadcast;
});
# asynchronously do sth. else here
$cv->wait;
π DESCRIPTION π
okay so first things first: this module is an AnyEvent user, so you gotta make sure you use and run a supported event loop. no event loop, no vibes, fr fr.
So what does it actually do? It implements asynchronous DBI access by forking or executing separate "DBI-Server" processes and sending them requests. β¨
Which means: you can run DBI requests in parallel to other tasks. main character energy, truly. π
Now the numbers, no cap: with DBD::mysql, the overhead for very simple statements ("select 0") is somewhere around 50% compared to an explicit prepare_cached/execute/fetchrow_arrayref/finish combination. With DBD::SQlite3, it's more like a factor of 8 for this trivial statement. so like. know that going in. π«Ά
π ERROR HANDLING π
This module defines a bunch of functions that accept a callback argument. And every single callback used by this module gets its AnyEvent::DBI handle object passed as the first argument. every time. that's the rule. π
If the request was successful, then there will be more arguments. Otherwise there will only be the $dbh argument and $@ contains an error message. π
A convenient way to check whether an error occurred is to check $#_ β if that is true, then the function was successful, otherwise there was an error. iconic little trick, iykyk.
β METHODS β
$dbh = new AnyEvent::DBI $database, $user, $pass, [key => value]...β Returns a database handle for the given database. Each database handle has an associated server process that executes statements in order. So if you want to run more than one statement in parallel, you need to create additional database handles. The advantage of this approach is that transactions work as state is preserved. π«Ά
Example:
$dbh = new AnyEvent::DBI
"DBI:mysql:test;mysql_read_default_file=/root/.my.cnf", "", "";
Additional key-value pairs can be used to adjust behaviour:
on_error => $callback->($dbh, $filename, $line, $fatal)β When an error occurs, then this callback will be invoked. On entry,$@is set to the error message.$filenameand$lineis where the original request was submitted. If the fatal argument is true then the database connection is shut down and your database handle became invalid. In addition to invoking theon_errorcallback, all of your queued request callbacks are called without only the$dbhargument. If omitted, thendiewill be called on any errors, fatal or not. πon_connect => $callback->($dbh[, $success])β If you supply anon_connectcallback, then this callback will be invoked after the database connect attempt. If the connection succeeds,$successis true, otherwise it is missing and$@contains the$DBI::errstr. Regardless of whetheron_connectis supplied, connect errors will result inon_errorbeing called. However, if noon_connectcallback is supplied, then connection errors are considered fatal. The client willdieand theon_errorcallback will be called with$fataltrue. When on_connect is supplied, connect error are not fatal and AnyEvent::DBI will notdie. You still cannot, however, use the$dbhobject you received fromnewto make requests. πfork_template => $AnyEvent::Fork-objectβAnyEvent::DBIusesAnyEvent::Fork->newto create the database slave, which in turn eitherexec's a new process (similar to the oldexec_serverconstructor argument) or uses a process forked early (see AnyEvent::Fork::Early). With this argument you can provide your own fork template. This can be useful if you create a lot ofAnyEvent::DBIhandles and want to save memory (And speed up startup) by not having to loadAnyEvent::DBIagain and again into your child processes:
my $template = AnyEvent::Fork
->new # create new template
->require ("AnyEvent::DBI::Slave"); # preload AnyEvent::DBI::Slave module
for (...) {
$dbh = new AnyEvent::DBI ...
fork_template => $template;
timeout => secondsβ If you supply a timeout parameter (fractional values are supported), then a timer is started any time the DBI handle expects a response from the server. This includes connection setup as well as requests made to the backend. The timeout spans the duration from the moment the first data is written (or queued to be written) until all expected responses are returned, but is postponed for"timeout"seconds each time more data is returned from the server. If the timer ever goes off then a fatal error is generated. If you have anon_errorhandler installed, then it will be called, otherwise your program willdie().
π¨ bestie listen: When altering your databases with timeouts it is wise to use transactions. If you quit due to timeout while performing insert, update or schema-altering commands you can end up not knowing if the action was submitted to the database, complicating recovery. Timeout errors are always fatal. π
- Any additional key-value pairs will be rolled into a hash reference and passed as the final argument to the
DBI->connect (...)call. For example, to suppress errors on STDERR and send them instead to an AnyEvent::Handle you could do:
$dbh = new AnyEvent::DBI
"DBI:mysql:test;mysql_read_default_file=/root/.my.cnf", "", "",
PrintError => 0,
on_error => sub {
$log_handle->push_write ("DBI Error: $@ at $_[1]:$_[2]\n");
};
$dbh->on_error ($cb->($dbh, $filename, $line, $fatal))β Sets (or clears, withundef) theon_errorhandler. β¨$dbh->timeout ($seconds)β Sets (or clears, withundef) the database timeout. Useful to extend the timeout when you are about to make a really long query. π’$dbh->attr ($attr_name[, $attr_value], $cb->($dbh, $new_value))β An accessor for the database handle attributes, such asAutoCommit,RaiseError,PrintErrorand so on. If you provide an$attr_value(which might beundef), then the given attribute will be set to that value. The callback will be passed the database handle and the attribute's value if successful. If an error occurs and theon_errorcallback returns, then only$dbhwill be passed and$@contains the error message. π$dbh->exec ("statement", @args, $cb->($dbh, \@rows, $rv))β Executes the given SQL statement with placeholders replaced by@args. The statement will be prepared and cached on the server side, so using placeholders is extremely important. The callback will be called with a weakened AnyEvent::DBI object as the first argument and the result offetchall_arrayrefas (orundefif the statement wasn't a select statement) as the second argument. Third argument is the return value from theDBI->executemethod call. If an error occurs and theon_errorcallback returns, then only$dbhwill be passed and$@contains the error message. π«Ά$dbh->stattr ($attr_name, $cb->($dbh, $value))β An accessor for the statement attributes of the most recently executed statement, such asNAMEorTYPE. The callback will be passed the database handle and the attribute's value if successful. If an error occurs and theon_errorcallback returns, then only$dbhwill be passed and$@contains the error message. π$dbh->begin_work ($cb->($dbh[, $rc]))$dbh->commit ($cb->($dbh[, $rc]))$dbh->rollback ($cb->($dbh[, $rc]))β The begin_work, commit, and rollback methods expose the equivalent transaction control method of the DBI driver. On success,$rcis true. If an error occurs and theon_errorcallback returns, then only$dbhwill be passed and$@contains the error message. β¨$dbh->func ('string_which_yields_args_when_evaled', $func_name, $cb->($dbh, $rc, $dbi_err, $dbi_errstr))β This gives access to database driver private methods. Because they are not standard you cannot always depend on the value of$rcor$dbi_err. Check the documentation for your specific driver/function combination to see what it returns. Note that the first argument will beeval'ed to produce the argument list to thefunc()method. This must be done because the serialization protocol between the AnyEvent::DBI server process and your program does not support the passage of closures. Here's an example to extend the query language in SQLite so it supports anintstr()function:
$cv = AnyEvent->condvar;
$dbh->func (
q{
instr => 2, sub {
my ($string, $search) = @_;
return index $string, $search;
},
},
create_function => sub {
return $cv->send ($@)
unless $#_;
$cv->send (undef, @_[1,2,3]);
}
);
my ($err,$rc,$errcode,$errstr) = $cv->recv;
die $err if defined $err;
die "EVAL failed: $errstr"
if $errcode;
# otherwise, we can ignore $rc and $errcode for this particular func
π SEE ALSO π
AnyEvent, DBI, Coro::Mysql. go read them bestie, they're the whole friend group π«Ά
π AUTHOR AND CONTACT π
Marc Lehmann <schmorp@schmorp.de> (current maintainer) http://home.schmorp.de/
Adam Rosenstein <adam@redcondor.com> http://www.redcondor.com/
and that's the whole page!! π this one shipped in perl v5.32.0, dated 2021-01-05, and it lives at DBI(3pm) in the User Contributed Perl Documentation. slay, bye bestie π
ππ¦
π¦ where this page comes from
- debian bookworm: libanyevent-dbi-perl 3.04-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libanyevent-dbi-perl 3.04-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu jammy: libanyevent-dbi-perl 3.04-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libanyevent-dbi-perl 3.04-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libanyevent-dbi-perl 3.04-1.1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms