ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent-DBI/DBI.pm
(Generate patch)

Comparing AnyEvent-DBI/DBI.pm (file contents):
Revision 1.1 by root, Fri Jun 6 15:35:46 2008 UTC vs.
Revision 1.18 by root, Sun Aug 27 09:54:25 2017 UTC

3AnyEvent::DBI - asynchronous DBI access 3AnyEvent::DBI - asynchronous DBI access
4 4
5=head1 SYNOPSIS 5=head1 SYNOPSIS
6 6
7 use AnyEvent::DBI; 7 use AnyEvent::DBI;
8
9 my $cv = AnyEvent->condvar;
10
11 my $dbh = new AnyEvent::DBI "DBI:SQLite:dbname=test.db", "", "";
12
13 $dbh->exec ("select * from test where num=?", 10, sub {
14 my ($dbh, $rows, $rv) = @_;
15
16 $#_ or die "failure: $@";
17
18 print "@$_\n"
19 for @$rows;
20
21 $cv->broadcast;
22 });
23
24 # asynchronously do sth. else here
25
26 $cv->wait;
8 27
9=head1 DESCRIPTION 28=head1 DESCRIPTION
10 29
11This module is an L<AnyEvent> user, you need to make sure that you use and 30This module is an L<AnyEvent> user, you need to make sure that you use and
12run a supported event loop. 31run a supported event loop.
13 32
14This module implements asynchronous DBI access my forking or executing 33This module implements asynchronous DBI access by forking or executing
15separate "DBI-Server" processes and sending them requests. 34separate "DBI-Server" processes and sending them requests.
16 35
17It means that you can run DBI requests in parallel to other tasks. 36It means that you can run DBI requests in parallel to other tasks.
18 37
38With DBD::mysql, the overhead for very simple statements
39("select 0") is somewhere around 50% compared to an explicit
40prepare_cached/execute/fetchrow_arrayref/finish combination. With
41DBD::SQlite3, it's more like a factor of 8 for this trivial statement.
42
43=head2 ERROR HANDLING
44
45This module defines a number of functions that accept a callback
46argument. All callbacks used by this module get their AnyEvent::DBI handle
47object passed as first argument.
48
49If the request was successful, then there will be more arguments,
50otherwise there will only be the C<$dbh> argument and C<$@> contains an
51error message.
52
53A convenient way to check whether an error occurred is to check C<$#_> -
54if that is true, then the function was successful, otherwise there was an
55error.
56
19=cut 57=cut
20 58
21package AnyEvent::DBI; 59package AnyEvent::DBI;
22 60
23use strict; 61use common::sense;
24no warnings;
25 62
26use Carp; 63use Carp;
27use Socket (); 64use Convert::Scalar ();
28use Scalar::Util (); 65use AnyEvent::Fork ();
29use Storable (); 66use CBOR::XS ();
30
31use DBI ();
32 67
33use AnyEvent (); 68use AnyEvent ();
34use AnyEvent::Util (); 69use AnyEvent::Util ();
35 70
71use Errno ();
72
36our $VERSION = '1.0'; 73our $VERSION = '3.01';
37
38# this is the forked server code
39
40our $DBH;
41
42sub req_open {
43 my (undef, $dbi, $user, $pass, %attr) = @{+shift};
44
45 $DBH = DBI->connect ($dbi, $user, $pass, \%attr);
46
47 [1]
48}
49
50sub serve {
51 my ($fh) = @_;
52
53 no strict;
54
55 eval {
56 my $rbuf;
57
58 while () {
59 sysread $fh, $rbuf, 16384, length $rbuf
60 or last;
61
62 while () {
63 my $len = unpack "L", $rbuf;
64
65 # full request available?
66 last unless $len && $len + 4 <= length $rbuf;
67
68 my $req = Storable::thaw substr $rbuf, 4;
69 substr $rbuf, 0, $len + 4, ""; # remove length + request
70
71 my $wbuf = eval { pack "L/a*", Storable::freeze $req->[0]($req) };
72
73 $wbuf = pack "L/a*", Storable::freeze [undef, "$@"]
74 if $@;
75
76 for (my $ofs = 0; $ofs < length $wbuf; ) {
77 $ofs += (syswrite $fh, substr $wbuf, $ofs
78 or die "unable to write results");
79 }
80 }
81 }
82 };
83
84 warn $@;#d#
85
86 kill 9, $$; # no other way on the broken windows platform
87}
88 74
89=head2 METHODS 75=head2 METHODS
90 76
91=over 4 77=over 4
92 78
113 99
114When an error occurs, then this callback will be invoked. On entry, C<$@> 100When an error occurs, then this callback will be invoked. On entry, C<$@>
115is set to the error message. C<$filename> and C<$line> is where the 101is set to the error message. C<$filename> and C<$line> is where the
116original request was submitted. 102original request was submitted.
117 103
118If this callback returns and this was a fatal error (C<$fatal> is true) 104If the fatal argument is true then the database connection is shut down
119then AnyEvent::DBI die's, otherwise it calls the original request callback 105and your database handle became invalid. In addition to invoking the
120without any arguments. 106C<on_error> callback, all of your queued request callbacks are called
107without only the C<$dbh> argument.
121 108
122If omitted, then C<die> will be called on any fatal errors, others will be ignored. 109If omitted, then C<die> will be called on any errors, fatal or not.
110
111=item on_connect => $callback->($dbh[, $success])
112
113If you supply an C<on_connect> callback, then this callback will be
114invoked after the database connect attempt. If the connection succeeds,
115C<$success> is true, otherwise it is missing and C<$@> contains the
116C<$DBI::errstr>.
117
118Regardless of whether C<on_connect> is supplied, connect errors will result in
119C<on_error> being called. However, if no C<on_connect> callback is supplied, then
120connection errors are considered fatal. The client will C<die> and the C<on_error>
121callback will be called with C<$fatal> true.
122
123When on_connect is supplied, connect error are not fatal and AnyEvent::DBI
124will not C<die>. You still cannot, however, use the $dbh object you
125received from C<new> to make requests.
126
127=item fork_template => $AnyEvent::Fork-object
128
129C<AnyEvent::DBI> uses C<< AnyEvent::Fork->new >> to create the database
130slave, which in turn either C<exec>'s a new process (similar to the old
131C<exec_server> constructor argument) or uses a process forked early (see
132L<AnyEvent::Fork::Early>).
133
134With this argument you can provide your own fork template. This can be
135useful if you create a lot of C<AnyEvent::DBI> handles and want to save
136memory (And speed up startup) by not having to load C<AnyEvent::DBI> again
137and again into your child processes:
138
139 my $template = AnyEvent::Fork
140 ->new # create new template
141 ->require ("AnyEvent::DBI::Slave"); # preload AnyEvent::DBI::Slave module
142
143 for (...) {
144 $dbh = new AnyEvent::DBI ...
145 fork_template => $template;
146
147=item timeout => seconds
148
149If you supply a timeout parameter (fractional values are supported), then
150a timer is started any time the DBI handle expects a response from the
151server. This includes connection setup as well as requests made to the
152backend. The timeout spans the duration from the moment the first data
153is written (or queued to be written) until all expected responses are
154returned, but is postponed for "timeout" seconds each time more data is
155returned from the server. If the timer ever goes off then a fatal error is
156generated. If you have an C<on_error> handler installed, then it will be
157called, otherwise your program will die().
158
159When altering your databases with timeouts it is wise to use
160transactions. If you quit due to timeout while performing insert, update
161or schema-altering commands you can end up not knowing if the action was
162submitted to the database, complicating recovery.
163
164Timeout errors are always fatal.
123 165
124=back 166=back
125 167
168Any additional key-value pairs will be rolled into a hash reference
169and passed as the final argument to the C<< DBI->connect (...) >>
170call. For example, to suppress errors on STDERR and send them instead to an
171AnyEvent::Handle you could do:
172
173 $dbh = new AnyEvent::DBI
174 "DBI:mysql:test;mysql_read_default_file=/root/.my.cnf", "", "",
175 PrintError => 0,
176 on_error => sub {
177 $log_handle->push_write ("DBI Error: $@ at $_[1]:$_[2]\n");
178 };
179
126=cut 180=cut
127
128# stupid Storable autoloading, total loss-loss situation
129Storable::thaw Storable::freeze [];
130 181
131sub new { 182sub new {
132 my ($class, $dbi, $user, $pass, %arg) = @_; 183 my ($class, $dbi, $user, $pass, %arg) = @_;
133 184
134 socketpair my $client, my $server, &Socket::AF_UNIX, &Socket::SOCK_STREAM, &Socket::PF_UNSPEC 185 # we use our own socketpair, so we always have a socket
186 # available, even before the forked process exsist.
187 # this is mostly done so this module is compatible
188 # to versions of itself older than 3.0.
189 my ($client, $server) = AnyEvent::Util::portable_socketpair
135 or croak "unable to create dbi communicaiton pipe: $!"; 190 or croak "unable to create AnyEvent::DBI communications pipe: $!";
191
192 my $fork = delete $arg{fork_template};
193
194 my %dbi_args = %arg;
195 delete @dbi_args{qw(on_connect on_error timeout fork_template exec_server)};
136 196
137 my $self = bless \%arg, $class; 197 my $self = bless \%arg, $class;
138 198
139 $self->{fh} = $client; 199 $self->{fh} = $client;
140
141 Scalar::Util::weaken (my $wself = $self);
142
143 AnyEvent::Util::fh_nonblocking $client, 1;
144 200
145 my $rbuf; 201 my $rbuf;
146 my @caller = (caller)[1,2]; # the "default" caller 202 my @caller = (caller)[1,2]; # the "default" caller
147 203
148 $self->{rw} = AnyEvent->io (fh => $client, poll => "r", cb => sub { 204 $fork = $fork ? $fork->fork : AnyEvent::Fork->new
149 my $len = sysread $client, $rbuf, 65536, length $rbuf; 205 or croak "fork: $!";
150 206
207 $fork->require ("AnyEvent::DBI::Slave");
208 $fork->send_arg ($VERSION);
209 $fork->send_fh ($server);
210
211 # we don't rely on the callback, because we use our own
212 # socketpair, for better or worse.
213 $fork->run ("AnyEvent::DBI::Slave::serve", sub { });
214
215 {
216 Convert::Scalar::weaken (my $self = $self);
217
218 my $cbor = new CBOR::XS;
219
220 $self->{rw} = AE::io $client, 0, sub {
221 my $len = Convert::Scalar::extend_read $client, $rbuf, 65536;
222
151 if ($len > 0) { 223 if ($len > 0) {
224 # we received data, so reset the timer
225 $self->{last_activity} = AE::now;
152 226
153 while () { 227 for my $res ($cbor->incr_parse_multiple ($rbuf)) {
154 my $len = unpack "L", $rbuf; 228 last unless $self;
155 229
156 # full request available?
157 last unless $len && $len + 4 <= length $rbuf;
158
159 my $res = Storable::thaw substr $rbuf, 4;
160 substr $rbuf, 0, $len + 4, ""; # remove length + request
161
162 my $req = shift @{ $wself->{queue} }; 230 my $req = shift @{ $self->{queue} };
163 231
164 if (defined $res->[0]) { 232 if (defined $res->[0]) {
233 $res->[0] = $self;
165 $req->[0](@$res); 234 $req->[0](@$res);
235 } else {
236 my $cb = shift @$req;
237 local $@ = $res->[1];
238 $cb->($self);
239 $self->_error ($res->[1], @$req, $res->[2]) # error, request record, is_fatal
240 if $self; # cb() could have deleted it
241 }
242
243 # no more queued requests, so become idle
244 if ($self && !@{ $self->{queue} }) {
245 undef $self->{last_activity};
246 $self->{tw_cb}->();
247 }
248 }
249
250 } elsif (defined $len) {
251 # todo, caller?
252 $self->_error ("unexpected eof", @caller, 1);
253 } elsif ($! != Errno::EAGAIN) {
254 # todo, caller?
255 $self->_error ("read error: $!", @caller, 1);
256 }
257 };
258
259 $self->{tw_cb} = sub {
260 if ($self->{timeout} && $self->{last_activity}) {
261 if (AE::now > $self->{last_activity} + $self->{timeout}) {
262 # we did time out
263 my $req = $self->{queue}[0];
264 $self->_error (timeout => $req->[1], $req->[2], 1); # timeouts are always fatal
166 } else { 265 } else {
167 my $cb = shift @$req; 266 # we need to re-set the timeout watcher
168 $wself->_error ($res->[1], @$req); 267 $self->{tw} = AE::timer
268 $self->{last_activity} + $self->{timeout} - AE::now,
269 0,
270 $self->{tw_cb},
169 $cb->[0](); 271 ;
170 } 272 }
273 } else {
274 # no timeout check wanted, or idle
275 undef $self->{tw};
171 } 276 }
172
173 } elsif (defined $len) {
174 $wself->_error ("unexpected eof", @caller, 1);
175 } else {
176 $wself->_error ("read error: $!", @caller, 1);
177 } 277 };
278
279 $self->{ww_cb} = sub {
280 $self->{last_activity} = AE::now;
281
282 my $len = syswrite $client, $self->{wbuf}
283 or return delete $self->{ww};
284
285 substr $self->{wbuf}, 0, $len, "";
286 };
287 }
288
289 $self->_req (
290 sub {
291 return unless $self;
292 $self->{child_pid} = $_[1];
293 },
294 (caller)[1,2],
295 "req_pid"
178 }); 296 );
179 297
180 my $pid = fork; 298 $self->_req (
181 299 sub {
182 if ($pid) { 300 return unless $self;
183 # parent 301 &{ $self->{on_connect} } if $self->{on_connect};
184 close $server; 302 },
185 303 (caller)[1,2],
186 } elsif (defined $pid) { 304 req_open => $dbi, $user, $pass, %dbi_args
187 # child 305 );
188 close $client;
189 @_ = $server;
190 goto &serve;
191
192 } else {
193 croak "fork: $!";
194 }
195
196 $self->_req (sub { }, (caller)[1,2], 1, req_open => $dbi, $user, $pass);
197 306
198 $self 307 $self
308}
309
310sub _server_pid {
311 shift->{child_pid}
312}
313
314sub kill_child {
315 my $self = shift;
316
317 if (my $pid = delete $self->{child_pid}) {
318 # kill and reap process
319 my $kid_watcher; $kid_watcher = AE::child $pid, sub {
320 undef $kid_watcher;
321 };
322 kill TERM => $pid;
323 }
324
325 delete $self->{rw};
326 delete $self->{ww};
327 delete $self->{tw};
328 close delete $self->{fh};
329}
330
331sub DESTROY {
332 shift->kill_child;
199} 333}
200 334
201sub _error { 335sub _error {
202 my ($self, $error, $filename, $line, $fatal) = @_; 336 my ($self, $error, $filename, $line, $fatal) = @_;
203 337
338 if ($fatal) {
339 delete $self->{tw};
204 delete $self->{rw}; 340 delete $self->{rw};
205 delete $self->{ww}; 341 delete $self->{ww};
206 delete $self->{fh}; 342 delete $self->{fh};
207 343
344 # for fatal errors call all enqueued callbacks with error
345 while (my $req = shift @{$self->{queue}}) {
346 local $@ = $error;
347 $req->[0]->($self);
348 }
349 $self->kill_child;
350 }
351
208 $@ = $error; 352 local $@ = $error;
209 353
354 if ($self->{on_error}) {
210 $self->{on_error}($self, $filename, $line, $fatal) 355 $self->{on_error}($self, $filename, $line, $fatal)
211 if $self->{on_error}; 356 } else {
212
213 die "$error at $filename, line $line\n" 357 die "$error at $filename, line $line\n";
214 if $fatal; 358 }
359}
360
361=item $dbh->on_error ($cb->($dbh, $filename, $line, $fatal))
362
363Sets (or clears, with C<undef>) the C<on_error> handler.
364
365=cut
366
367sub on_error {
368 $_[0]{on_error} = $_[1];
369}
370
371=item $dbh->timeout ($seconds)
372
373Sets (or clears, with C<undef>) the database timeout. Useful to extend the
374timeout when you are about to make a really long query.
375
376=cut
377
378sub timeout {
379 my ($self, $timeout) = @_;
380
381 $self->{timeout} = $timeout;
382
383 # reschedule timer if one was running
384 $self->{tw_cb}->();
215} 385}
216 386
217sub _req { 387sub _req {
218 warn "<req(@_>\n";#d#
219 my ($self, $cb, $filename, $line, $fatal) = splice @_, 0, 5, (); 388 my ($self, $cb, $filename, $line) = splice @_, 0, 4, ();
220 389
390 unless ($self->{fh}) {
391 local $@ = my $err = 'no database connection';
392 $cb->($self);
393 $self->_error ($err, $filename, $line, 1);
394 return;
395 }
396
221 push @{ $self->{queue} }, [$cb, $filename, $line, $fatal]; 397 push @{ $self->{queue} }, [$cb, $filename, $line];
222 398
223 $self->{wbuf} .= pack "L/a*", Storable::freeze \@_; 399 # re-start timeout if necessary
400 if ($self->{timeout} && !$self->{tw}) {
401 $self->{last_activity} = AE::now;
402 $self->{tw_cb}->();
403 }
404
405 $self->{wbuf} .= CBOR::XS::encode_cbor \@_;
224 406
225 unless ($self->{ww}) { 407 unless ($self->{ww}) {
226 my $len = syswrite $self->{fh}, $self->{wbuf}; 408 my $len = syswrite $self->{fh}, $self->{wbuf};
227 substr $self->{wbuf}, 0, $len, ""; 409 substr $self->{wbuf}, 0, $len, "";
228 410
229 #TODO, ww_cb
230 # still any left? then install a write watcher 411 # still any left? then install a write watcher
231 $self->{ww} = AnyEvent->io (fh => $self->{fh}, poll => "w", cb => $self->{ww_cb}) 412 $self->{ww} = AE::io $self->{fh}, 1, $self->{ww_cb}
232 if length $self->{wbuf}; 413 if length $self->{wbuf};
233 } 414 }
234} 415}
235 416
417=item $dbh->attr ($attr_name[, $attr_value], $cb->($dbh, $new_value))
418
419An accessor for the database handle attributes, such as C<AutoCommit>,
420C<RaiseError>, C<PrintError> and so on. If you provide an C<$attr_value>
421(which might be C<undef>), then the given attribute will be set to that
422value.
423
424The callback will be passed the database handle and the attribute's value
425if successful.
426
427If an error occurs and the C<on_error> callback returns, then only C<$dbh>
428will be passed and C<$@> contains the error message.
429
236=item $dbh->exec ("statement", @args, $cb->($rows, %extra)) 430=item $dbh->exec ("statement", @args, $cb->($dbh, \@rows, $rv))
237 431
238Executes the given SQL statement with placeholders replaced by 432Executes the given SQL statement with placeholders replaced by
239C<@args>. The statement will be prepared and cached on the 433C<@args>. The statement will be prepared and cached on the server side, so
240server side, so using placeholders is compulsory. 434using placeholders is extremely important.
241 435
242The callback will be called with the result of C<fetchall_arrayref> as 436The callback will be called with a weakened AnyEvent::DBI object as the
243first argument and possibly a hash reference with additional information. 437first argument and the result of C<fetchall_arrayref> as (or C<undef>
438if the statement wasn't a select statement) as the second argument.
439
440Third argument is the return value from the C<< DBI->execute >> method
441call.
442
443If an error occurs and the C<on_error> callback returns, then only C<$dbh>
444will be passed and C<$@> contains the error message.
445
446=item $dbh->stattr ($attr_name, $cb->($dbh, $value))
447
448An accessor for the statement attributes of the most recently executed
449statement, such as C<NAME> or C<TYPE>.
450
451The callback will be passed the database handle and the attribute's value
452if successful.
453
454If an error occurs and the C<on_error> callback returns, then only C<$dbh>
455will be passed and C<$@> contains the error message.
456
457=item $dbh->begin_work ($cb->($dbh[, $rc]))
458
459=item $dbh->commit ($cb->($dbh[, $rc]))
460
461=item $dbh->rollback ($cb->($dbh[, $rc]))
462
463The begin_work, commit, and rollback methods expose the equivalent
464transaction control method of the DBI driver. On success, C<$rc> is true.
465
466If an error occurs and the C<on_error> callback returns, then only C<$dbh>
467will be passed and C<$@> contains the error message.
468
469=item $dbh->func ('string_which_yields_args_when_evaled', $func_name, $cb->($dbh, $rc, $dbi_err, $dbi_errstr))
470
471This gives access to database driver private methods. Because they
472are not standard you cannot always depend on the value of C<$rc> or
473C<$dbi_err>. Check the documentation for your specific driver/function
474combination to see what it returns.
475
476Note that the first argument will be eval'ed to produce the argument list to
477the func() method. This must be done because the serialization protocol
478between the AnyEvent::DBI server process and your program does not support the
479passage of closures.
480
481Here's an example to extend the query language in SQLite so it supports an
482intstr() function:
483
484 $cv = AnyEvent->condvar;
485 $dbh->func (
486 q{
487 instr => 2, sub {
488 my ($string, $search) = @_;
489 return index $string, $search;
490 },
491 },
492 create_function => sub {
493 return $cv->send ($@)
494 unless $#_;
495 $cv->send (undef, @_[1,2,3]);
496 }
497 );
498
499 my ($err,$rc,$errcode,$errstr) = $cv->recv;
500
501 die $err if defined $err;
502 die "EVAL failed: $errstr"
503 if $errcode;
504
505 # otherwise, we can ignore $rc and $errcode for this particular func
244 506
245=cut 507=cut
246 508
247sub exec { 509for my $cmd_name (qw(attr exec stattr begin_work commit rollback func)) {
510 eval 'sub ' . $cmd_name . '{
248 my $cb = pop; 511 my $cb = pop;
249 splice @_, 1, 0, $cb, (caller)[1,2], 0, "exec"; 512 splice @_, 1, 0, $cb, (caller)[1,2], "req_' . $cmd_name . '";
250 513 &_req
251 goto &_req; 514 }';
252} 515}
253 516
254=back 517=back
255 518
256=head1 SEE ALSO 519=head1 SEE ALSO
257 520
258L<AnyEvent>, L<DBI>. 521L<AnyEvent>, L<DBI>, L<Coro::Mysql>.
259 522
260=head1 AUTHOR 523=head1 AUTHOR AND CONTACT
261 524
262 Marc Lehmann <schmorp@schmorp.de> 525 Marc Lehmann <schmorp@schmorp.de> (current maintainer)
263 http://home.schmorp.de/ 526 http://home.schmorp.de/
527
528 Adam Rosenstein <adam@redcondor.com>
529 http://www.redcondor.com/
264 530
265=cut 531=cut
266 532
2671 5331
268

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines