Async.pm

filter: Statementstmt 52.9% 81 / 153 Branchbran 38.4% 10 / 26 Conditioncond 11.7% 2 / 17 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 58.9% 23 / 39 Podpod 75.0% 15 / 20 totaltotal 49.2% 131 / 266 CC 20 SCAR 25.6
CC
20
Cov
47%
engine_instance
72.0
configure
11.5
ryu
6.0
CRAP 13.0
« Async/ORM.pm ↑ Summary Async/Engine.pm »
1 package Database::Async;
2 # ABSTRACT: database interface for use with IO::Async
3 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 4 our $VERSION = '0.019';
7  
8 4 ▶use parent qw(Database::Async::DB IO::Async::Notifier);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =head1 NAME
11  
12 Database::Async - provides a database abstraction layer for L<IO::Async>
13  
14 =head1 SYNOPSIS
15  
16 # Just looking up one thing?
17 my ($id) = $db->query(
18 q{select id from some_table where name = ?},
19 bind => ['some name']
20 )->single
21 # This is an example, so we want the result immediately - in
22 # real async code, you'd rarely call Future->get, but would
23 # typically use `->then` or `->on_done` instead
24 ->get;
25 # or, with Future::AsyncAwait, try:
26 my ($id) = await $db->query(
27 q{select id from some_table where name = ?},
28 bind => ['some name']
29 )->single;
30  
31 # Simple query
32 $db->query(q{select id, some_data from some_table})
33 ->row_hashrefs
34 ->each(sub {
35 printf "ID %d, data %s\n", $_->{id}, $_->{some_data};
36 })
37 # If you want to complete the full query, don't forget to call
38 # ->get or ->retain here!
39 ->retain;
40  
41 # Transactions
42 $db->transaction(sub {
43 my ($tx) = @_;
44 })->commit
45 # This returns a Future, so if you want to wait for it to complete,
46 # call `->get` (throws an exception if something goes wrong)
47 # or `->await` (just waits for it to succeed or fail, but ignores
48 # the result).
49 ->get;
50  
51 =head1 DESCRIPTION
52  
53 Database support for L<IO::Async>. This is the base API, see L<Database::Async::Engine>
54 and subclasses for specific database functionality.
55  
56 B<This is an early preview release>.
57  
58 L<DBI> provides a basic API for interacting with a database, but this is
59 very low level and uses a synchronous design. See L<DBIx::Async> if you're
60 familiar with L<DBI> and want an interface that follows it more closely.
61  
62 Typically a database only allows a single query to run at a time.
63 Other queries will be queued.
64  
65 Set up a pool of connections to provide better parallelism:
66  
67 my $dbh = Database::Async->new(
68 uri => 'postgresql://write@maindb/dbname?sslmode=require',
69 pool => {
70 max => 4,
71 },
72 );
73  
74 Queries and transactions will then automatically be distributed
75 among these connections. However, note that:
76  
77 =over 4
78  
79 =item * all queries within a transaction will be made on the same connection
80  
81 =item * ordering guarantees are weaker: queries will be started in
82 order on the next available connection
83  
84 =back
85  
86 With a single connection, you could expect:
87  
88 Future->needs_all(
89 $dbh->do(q{insert into x ...}),
90 $dbh->do(q{select from x ...})
91 );
92  
93 to insert the rows first, then return them in the C<select> call. B<With a pool of connections, that's not guaranteed>.
94  
95 =head2 Pool configuration
96  
97 The following parameters are currently accepted for defining the pool:
98  
99 =over 4
100  
101 =item * C<min> - minimum number of total connections to maintain, defaults to 0
102  
103 =item * C<max> - maximum permitted active connections, default is 1
104  
105 =item * C<ordering> - how to iterate through the available URIs, options include
106 C<random> and C<serial> (default, round-robin behaviour).
107  
108 =item * C<backoff> - algorithm for managing connection timeouts or failures. The default
109 is an exponential backoff with 10ms initial delay, 30s maximum, resetting on successful
110 connection.
111  
112 =back
113  
114 See L<Database::Async::Pool> for more details.
115  
116 =head2 DBI
117  
118 The interface is not the same as L<DBI>, but here are some approximate equivalents for
119 common patterns:
120  
121 =head3 selectall_hashref
122  
123 In L<DBI>:
124  
125 print $_->{id} . "\n" for
126 $dbh->selectall_hashref(
127 q{select * from something where id = ?},
128 undef,
129 $id
130 )->@*;
131  
132 In L<Database::Async>:
133  
134 print $_->{id} . "\n" for
135 $db->query(
136 q{select * from something where id = ?},
137 bind => [
138 $id
139 ])->row_hashrefs
140 ->as_arrayref
141 ->@*
142  
143 In L<DBI>:
144  
145 my $sth = $dbh->prepare(q{select * from something where id = ?});
146 for my $id (1, 2, 3) {
147 $sth->bind(0, $id, 'bigint');
148 $sth->execute;
149 while(my $row = $sth->fetchrow_hashref) {
150 print $row->{name} . "\n";
151 }
152 }
153  
154 In L<Database::Async>:
155  
156 my $sth = $db->prepare(q{select * from something where id = ?});
157 (Future::Utils::fmap_void {
158 my ($id) = @_;
159 $sth->bind(0, $id, 'bigint')
160 ->then(sub { $sth->execute })
161 ->then(sub {
162 $sth->row_hashrefs
163 ->each(sub {
164 print $_->{name} . "\n";
165 })->completed
166 })
167 } foreach => [1, 2, 3 ])->get;
168  
169 =cut
170  
171 4 ▶use mro;
Subroutine BEGIN: called CC=1 SCAR=0.0
172 4 ▶no indirect;
Subroutine BEGIN: called CC=1 SCAR=0.0
173  
174 4 ▶use Future::AsyncAwait qw(:experimental);
Subroutine BEGIN: called CC=1 SCAR=0.0
175 4 ▶use Syntax::Keyword::Try;
Subroutine BEGIN: called CC=1 SCAR=0.0
176  
177 4 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
178 4 ▶use URI::db;
Subroutine BEGIN: called CC=1 SCAR=0.0
179 4 ▶use Module::Load ();
Subroutine BEGIN: called CC=1 SCAR=0.0
180 4 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
181  
182 4 ▶use Database::Async::Engine;
Subroutine BEGIN: called CC=1 SCAR=0.0
183 4 ▶use Database::Async::Pool;
Subroutine BEGIN: called CC=1 SCAR=0.0
184 4 ▶use Database::Async::Query;
Subroutine BEGIN: called CC=1 SCAR=0.0
185 4 ▶use Database::Async::StatementHandle;
Subroutine BEGIN: called CC=1 SCAR=0.0
186 4 ▶use Database::Async::Transaction;
Subroutine BEGIN: called CC=1 SCAR=0.0
187  
188 4 ▶use Log::Any qw($log);
Subroutine BEGIN: called CC=1 SCAR=0.0
189  
190 =head1 METHODS
191  
192 =cut
193  
194 =head2 transaction
195  
196 Resolves to a L<Future> which will yield a L<Database::Async::Transaction>
197 instance once ready.
198  
199 =cut
200  
201 0 ▶async sub transaction {
Subroutine transaction: not called CC=1 SCAR=6.9
Pod documented
202 0 my ($self, @args) = @_;
203 Scalar::Util::weaken(
204 0 $self->{transactions}[@{$self->{transactions}}] =
205 my $txn = Database::Async::Transaction->new(
206 database => $self,
207 @args
208 )
209 );
210 0 await $txn->begin;
211 0 return $txn;
212 4 }
213  
214 =head2 txn
215  
216 Executes code within a transaction. This is meant as a shorter form of
217 the common idiom
218  
219 $db->transaction
220 ->then(sub {
221 my ($txn) = @_;
222 Future->call($code)
223 ->then(sub {
224 $txn->commit
225 })->on_fail(sub {
226 $txn->rollback
227 });
228 })
229  
230 The code must return a L<Future>, and the transaction will only be committed
231 if that L<Future> resolves cleanly.
232  
233 Returns a L<Future> which resolves once the transaction is committed.
234  
235 =cut
236  
237 0 ▶async sub txn {
Subroutine txn: not called CC=1 SCAR=6.9
Pod documented
238 0 my ($self, $code, @args) = @_;
239 0 my $txn = await $self->transaction;
240 try {
241 0 my @data = await Future->call(
242 $code => ($txn, @args)
243 );
244 0 await $txn->commit;
245 0 return @data;
246 0 } catch {
247 0 my $exception = $@;
248 try {
249 0 await $txn->rollback;
250 0 } catch {
251 0 $log->warnf("exception %s in rollback", $@);
252 }
253 0 die $exception;
254 }
255 4 }
256  
257 =head1 METHODS - Internal
258  
259 You're welcome to call these, but they're mostly intended
260 for internal usage, and the API B<may> change in future versions.
261  
262 =cut
263  
264 =head2 uri
265  
266 Returns the configured L<URI> for populating database instances.
267  
268 =cut
269  
270 5 ▶sub uri { shift->{uri} }
Subroutine uri: called CC=1 SCAR=0.0
Pod documented
271  
272 =head2 pool
273  
274 Returns the L<Database::Async::Pool> instance.
275  
276 =cut
277  
278 19 ▶sub pool {
Subroutine pool: called CC=2 SCAR=7.1
Pod documented
279 19 my ($self) = @_;
280 19 ▶ $self->{pool} ||= Database::Async::Pool->new(
Condition66%2/3
$self->{"pool"} ||= "Database::Async::Pool"->new($self->pool_args)
l!l&&r!l&&!r
1630
MC/DC0%0/2
$self->{"pool"} ||= "Database::Async::Pool"->new($self->pool_args)
$self->{"pool"} "Database::Async::Pool"->new($self->pool_args)
Truth table66%2/3
A ||= B
A= $self->{"pool"}B= "Database::Async::Pool"->new($self->pool_args)
ABresult
1X1
011
000
281 $self->pool_args
282 );
283 }
284  
285 =head2 pool_args
286  
287 Returns a list of standard pool constructor arguments.
288  
289 =cut
290  
291 5 ▶sub pool_args {
Subroutine pool_args: called CC=1 SCAR=0.0
Pod documented
292 5 my ($self) = @_;
293 return (
294 5 request_engine => $self->curry::weak::request_engine,
295 uri => $self->uri,
296 );
297 }
298  
299 =head2 configure
300  
301 Applies configuration, see L<IO::Async::Notifier> for details.
302  
303 Supports the following named parameters:
304  
305 =over 4
306  
307 =item * C<uri> - the endpoint to use when connecting a new engine instance
308  
309 =item * C<engine> - the parameters to pass when instantiating a new L<Database::Async::Engine>
310  
311 =item * C<pool> - parameters for setting up the pool, or a L<Database::Async::Pool> instance
312  
313 =item * C<encoding> - default encoding to apply to parameters, queries and results, defaults to C<binary>
314  
315 =back
316  
317 =cut
318  
319 4 my %encoding_map = (
320 'utf8' => 'UTF-8',
321 'utf-8' => 'UTF-8',
322 'UTF8' => 'UTF-8',
323 'unicode' => 'UTF-8',
324 );
325  
326 7 ▶sub configure {
Subroutine configure: called CC=8 SCAR=24.4
Pod documented
327 7 my ($self, %args) = @_;
328  
329 7 ▶ if(my $encoding = delete $args{encoding}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $encoding = delete $args{"encoding"}) 0 7 7
330 0 ▶ $self->{encoding} = $encoding_map{$encoding} // $encoding;
Condition0%0/3
$encoding_map{$encoding} // $encoding
l!l&&r!l&&!r
000
MC/DC0%0/2
$encoding_map{$encoding} // $encoding
$encoding_map{$encoding} $encoding
Truth table0%0/3
A // B
A= $encoding_map{$encoding}B= $encoding
ABresult
1X1
011
000
331 }
332  
333 7 ▶ if(my $uri = delete $args{uri}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $uri = delete $args{"uri"}) 0 7 7
334 # This could be any type of object. We make
335 # the assumption here that it safely serialises
336 # to a standard URI. Some of the database
337 # engines provide such a standard (e.g. PostgreSQL).
338 # Others may not...
339 0 $self->{uri} = URI->new("$uri");
340 }
341 7 ▶ if(exists $args{engine}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"engine"}) 0 7 7
342 0 $self->{engine_parameters} = delete $args{engine};
343 }
344 7 ▶ if(exists $args{type}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args{"type"}) 0 7 7
345 0 $self->{type} = delete $args{type};
346 }
347 7 ▶ if(my $pool = delete $args{pool}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $pool = delete $args{"pool"}) 3 4 7
348 3 ▶ if(blessed $pool) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($pool)) { } 1 2 3
349 1 $self->{pool} = $pool;
350 } else {
351 2 $self->{pool} = Database::Async::Pool->new(
352 $self->pool_args,
353 %$pool,
354 );
355 }
356 }
357 7 $self->next::method(%args);
358 }
359  
360 0 ▶sub encoding { shift->{encoding} }
Subroutine encoding: not called CC=1 SCAR=6.9
Pod documented
361  
362 =head2 ryu
363  
364 A L<Ryu::Async> instance, used for requesting sources, sinks and timers.
365  
366 =cut
367  
368 0 ▶sub ryu {
Subroutine ryu: not called CC=2 SCAR=17.9
Pod documented
369 0 my ($self) = @_;
370 0 ▶ $self->{ryu} //= do {
Condition0%0/3
$self->{"ryu"} //= do { $self->add_child(my $ryu = "Ryu::Async"->new); $ryu }
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"ryu"} //= do { $self->add_child(my $ryu = "Ryu::Async"->new); $ryu }
$self->{"ryu"} do { $self->add_child(my $ryu = "Ryu::Async"->new); $ryu }
Truth table0%0/3
A //= B
A= $self->{"ryu"}B= do { $self->add_child(my $ryu = "Ryu::Async"->new); $ryu }
ABresult
1X1
011
000
371 0 $self->add_child(
372 my $ryu = Ryu::Async->new
373 );
374 0 $ryu
375 }
376 }
377  
378 =head2 new_source
379  
380 Instantiates a new L<Ryu::Source>.
381  
382 =cut
383  
384 0 ▶sub new_source { shift->ryu->source }
Subroutine new_source: not called CC=1 SCAR=6.9
Pod documented
385  
386 =head2 new_sink
387  
388 Instantiates a new L<Ryu::Sink>.
389  
390 =cut
391  
392 0 ▶sub new_sink { shift->ryu->sink }
Subroutine new_sink: not called CC=1 SCAR=6.9
Pod documented
393  
394 =head2 new_future
395  
396 Instantiates a new L<Future>.
397  
398 =cut
399  
400 0 ▶sub new_future { shift->loop->new_future }
Subroutine new_future: not called CC=1 SCAR=6.9
Pod documented
401  
402 =head1 METHODS - Internal, engine-related
403  
404 =cut
405  
406 =head2 request_engine
407  
408 Attempts to instantiate and connect to a new L<Database::Async::Engine>
409 subclass. Returns a L<Future> which should resolve to a new
410 L<Database::Async::Engine> instance when ready to use.
411  
412 =cut
413  
414 0 ▶async sub request_engine {
Subroutine request_engine: not called CC=1 SCAR=6.9
Pod documented
415 0 my ($self) = @_;
416 0 $log->tracef('Requesting new engine');
417 0 my $engine = $self->engine_instance;
418 0 $log->tracef('Connecting');
419 0 return await $engine->connect;
420 4 }
421  
422 =head2 engine_instance
423  
424 Loads the appropriate engine class and attaches to the loop.
425  
426 =cut
427  
428 0 ▶sub engine_instance {
Subroutine engine_instance: not called CC=8 SCAR=42.8
Pod documented
429 0 my ($self) = @_;
430 0 my $uri = $self->uri;
431 0 ▶ my $type = $self->{type} // $uri->scheme;
Condition0%0/3
$self->{"type"} // $uri->scheme
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"type"} // $uri->scheme
$self->{"type"} $uri->scheme
Truth table0%0/3
A // B
A= $self->{"type"}B= $uri->scheme
ABresult
1X1
011
000
432 die 'unknown database type ' . $type
433 0 ▶ unless my $engine_class = $Database::Async::Engine::ENGINE_MAP{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless my $engine_class = $Database::Async::Engine::ENGINE_MAP{$type} 0 0 0
434 0 ▶ Module::Load::load($engine_class) unless $engine_class->can('new');
Branch: 1 branch
BranchTrueFalseTotal
unless $engine_class->can("new") 0 0 0
435 0 $log->tracef('Instantiating new %s', $engine_class);
436 my %param = (
437 0 ▶ %{$self->{engine_parameters} || {}},
Branch: 1 branch
BranchTrueFalseTotal
defined $uri ? : 0 0 0
Condition0%0/2
$self->{'engine_parameters'} || {}
l!l
00
MC/DC0%0/1
$self->{'engine_parameters'} || {}
$self->{'engine_parameters'}
Truth table0%0/2
A
A= $self->{'engine_parameters'}
Aresult
11
00
438 (defined($uri) ? (uri => $uri) : ()),
439 db => $self,
440 );
441  
442 # Only recent engine versions support this parameter
443 0 ▶ if(my $encoding = $self->encoding) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $encoding = $self->encoding) 0 0 0
444 0 ▶ if($engine_class->can('encoding')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine_class->can('encoding')) { } 0 0 0
445 0 $param{encoding} = $self->encoding;
446 } else {
447 # If we're given this parameter, let's not ignore it silently
448 0 die 'Database engine ' . $engine_class . ' does not support encoding parameter, try upgrading that module from CPAN or remove the encoding configuration in Database::Async';
449 }
450 }
451  
452 $self->add_child(
453 0 my $engine = $engine_class->new(%param)
454 );
455 0 $engine;
456 }
457  
458 =head2 engine_ready
459  
460 Called by L<Database::Async::Engine> instances when the engine is
461 ready for queries.
462  
463 =cut
464  
465 0 ▶sub engine_ready {
Subroutine engine_ready: not called CC=1 SCAR=6.9
Pod documented
466 0 my ($self, $engine) = @_;
467 0 $self->pool->queue_ready_engine($engine);
468 }
469  
470 0 ▶sub engine_disconnected {
Subroutine engine_disconnected: not called CC=1 SCAR=6.9
Pod undocumented
471 0 my ($self, $engine) = @_;
472 0 $self->pool->unregister_engine($engine);
473 }
474  
475 0 ▶sub db { shift }
Subroutine db: not called CC=1 SCAR=6.9
Pod undocumented
476  
477 =head2 queue_query
478  
479 Assign the given query to the next available engine instance.
480  
481 =cut
482  
483 0 ▶async sub queue_query {
Subroutine queue_query: not called CC=1 SCAR=6.9
Pod documented
484 0 my ($self, $query) = @_;
485 0 $log->tracef('Queuing query %s', $query);
486 0 my $f = $self->pool->next_engine;
487 CANCEL { $f->cancel; return undef }
488 0 my $engine = await $f;
489 0 $log->tracef('Query %s about to run on %s', $query, $engine);
490 0 my $q = $engine->handle_query($query);
491 CANCEL { $q->cancel; return undef }
492 0 return await $q;
493 4 }
494  
495 0 ▶sub diagnostics {
Subroutine diagnostics: not called CC=1 SCAR=6.9
Pod undocumented
496 0 my ($self) = @_;
497 }
498  
499 0 ▶sub notification {
Subroutine notification: not called CC=1 SCAR=6.9
Pod undocumented
500 0 my ($self, $engine, $channel, $data) = @_;
501 0 $log->tracef('Database notifies us via %s of %s', $channel, $data);
502 0 $self->notification_source($channel)->emit($data);
503 }
504  
505 0 ▶sub notification_source {
Subroutine notification_source: not called CC=2 SCAR=17.9
Pod undocumented
506 0 my ($self, $name) = @_;
507 0 ▶ $self->{notification_source}{$name} //= $self->new_source;
Condition0%0/3
$self->{"notification_source"}{$name} //= $self->new_source
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"notification_source"}{$name} //= $self->new_source
$self->{"notification_source"}{$name} $self->new_source
Truth table0%0/3
A //= B
A= $self->{"notification_source"}{$name}B= $self->new_source
ABresult
1X1
011
000
508 }
509  
510 2 ▶sub _add_to_loop {
Subroutine _add_to_loop: called CC=1 SCAR=0.0
511 2 my ($self, $loop) = @_;
512 2 $self->add_child(
513 $self->pool
514 );
515 2 return;
516 }
517  
518 2 ▶sub _remove_from_loop {
Subroutine _remove_from_loop: called CC=3 SCAR=11.8
519 2 my ($self, $loop) = @_;
520 2 ▶ if($self->{ryu}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"ryu"}) 0 2 2
521 0 $self->remove_child(delete $self->{ryu});
522 }
523 2 ▶ if($self->{pool}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pool"}) 2 0 2
524 2 $self->remove_child(delete $self->{pool});
525 }
526 2 return $self->next::method($loop);
527 }
528  
529 4 1;
530  
531 __END__
« Async/ORM.pm ↑ Summary Async/Engine.pm »