File Coverage

blib/lib/POE/Component/DBIAgent.pm
Criterion Covered Total %
statement 18 134 13.4
branch 0 70 0.0
condition 0 25 0.0
subroutine 6 16 37.5
pod 3 7 42.8
total 27 252 10.7


line stmt bran cond sub pod time code
1             package POE::Component::DBIAgent;
2              
3             # {{{ POD
4              
5             =head1 NAME
6              
7             POE::Component::DBIAgent - POE Component for running asynchronous DBI calls.
8              
9             =head1 SYNOPSIS
10              
11             sub _start {
12             my ($self, $kernel, $heap) = @_[OBJECT, KERNEL, HEAP];
13              
14             $heap->{helper} = POE::Component::DBIAgent->new( DSN => [$dsn,
15             $username,
16             $password
17             ],
18             Queries => $self->make_queries,
19             Count => 3,
20             Debug => 1,
21             );
22              
23             # Queries takes a hashref of the form:
24             # { query_name => 'select blah from table where x = ?',
25             # other_query => 'select blah_blah from big_view',
26             # etc.
27             # }
28              
29             $heap->{helper}->query(query_name =>
30             { cookie => 'starting_query' },
31             session => 'get_row_from_dbiagent');
32              
33             }
34              
35             sub get_row_from_dbiagent {
36             my ($kernel, $self, $heap, $row, $cookie) = @_[KERNEL, OBJECT, HEAP, ARG0, ARG1];
37             if ($row ne 'EOF') {
38              
39             # {{{ PROCESS A ROW
40              
41             #row is a listref of columns
42              
43             # }}} PROCESS A ROW
44              
45             } else {
46              
47             # {{{ NO MORE ROWS
48              
49             #cleanup code here
50              
51             # }}} NO MORE ROWS
52              
53             }
54              
55             }
56              
57              
58             =head1 DESCRIPTION
59              
60             DBIAgent is your answer to non-blocking DBI in POE.
61              
62             It fires off a configurable number child processes (defaults to 3) and
63             feeds database queries to it via two-way pipe (or sockets ... however
64             POE::Component::Wheel::Run is able to manage it). The primary method
65             is C.
66              
67             =head2 Usage
68              
69             After initializing a DBIAgent and storing it in a session's heap, one
70             executes a C (or C) with the query name,
71             destination session (name or id) and destination state (as well as any
72             query parameters, optionally) as arguments. As each row of data comes
73             back from the query, the destination state (in the destination
74             session) is invoked with that row of data in its C<$_[ARG0]> slot. When
75             there are no more rows to return, the data in C<$_[ARG0]> is the string
76             'EOF'.
77              
78             Not EVERY query should run through the DBIAgent. If you need to run a
79             short lookup from within a state, sometimes it can be a hassle to have
80             to define a whole seperate state to receive its value, and resume
81             processing from there.. The determining factor, of course, is how
82             long your query will take to execute. If you are trying to retrieve
83             one row from a properly indexed table, use
84             C<$dbh-Eselectrow_array()>. If there's a join involved, or
85             multiple rows, or a view, you probably want to use DBIAgent. If it's
86             a longish query and startup costs (time) don't matter to you, go ahead
87             and do it inline.. but remember the whole of your program suspends
88             waiting for the result. If startup costs DO matter, use DBIAgent.
89              
90             =head2 Return Values
91              
92             The destination state in the destination session (specified in the
93             call to C) will receive the return values from the query in
94             its C<$_[ARG0]> parameter. DBIAgent invokes DBI's C method
95             internally, so the value will be a reference to an array. If your
96             query returns multiple rows, then your state will be invoked multiple
97             times, once per row. B, your state will be called one
98             time with C<$_[ARG0]> containing the string 'EOF'. 'EOF' is returned I
99             if the query doesn't return any other rows>. This is also what to
100             expect for DML (INSERT, UPDATE, DELETE) queries. A way to utilise
101             this might be as follows:
102              
103             sub some_state {
104             #...
105             if ($enough_values_to_begin_updating) {
106              
107             $heap->{dbiagent}->query(update_values_query =>
108             this_session =>
109             update_next_value =>
110             shift @{$heap->{values_to_be_updated}}
111             );
112             }
113             }
114              
115             sub update_next_value {
116             my ($self, $heap) = @_[OBJECT, HEAP];
117             # we got 'EOF' in ARG0 here but we don't care... we know that an
118             # update has been executed.
119              
120             for (1..3) { # Do three at a time!
121             my $value;
122             last unless defined ($value = shift @{$heap->{values_to_be_updated}});
123             $heap->{dbiagent}->query(update_values =>
124             this_session =>
125             update_next_value =>
126             $value
127             );
128             }
129              
130             }
131              
132             =cut
133              
134             # }}} POD
135              
136             #use Data::Dumper;
137 1     1   8393 use Storable qw/freeze thaw/;
  1         6556  
  1         121  
138 1     1   10 use Carp;
  1         2  
  1         85  
139              
140 1     1   6 use strict;
  1         6  
  1         44  
141 1     1   1246 use POE qw/Session Filter::Reference Wheel::Run Component::DBIAgent::Helper Component::DBIAgent::Queue/;
  1         61193  
  1         7  
142              
143 1     1   71 use vars qw/$VERSION/;
  1         2  
  1         87  
144              
145             $VERSION = sprintf("%d.%02d", q$Revision: 0.26 $ =~ /(\d+)\.(\d+)/);
146              
147 1     1   7 use constant DEFAULT_KIDS => 3;
  1         3  
  1         2763  
148              
149 0     0 0   sub debug { $_[0]->{debug} }
150             #sub debug { 1 }
151             #sub debug { 0 }
152              
153             #sub carp { warn @_ }
154             #sub croak { die @_ }
155              
156             # {{{ new
157              
158             =head2 new()
159              
160             Creating an instance creates a POE::Session to manage communication
161             with the Helper processes. Queue management is transparent and
162             automatic. The constructor is named C (surprised, eh? Yeah,
163             me too). The parameters are as follows:
164              
165             =over
166              
167             =item DSN
168              
169             An arrayref of parameters to pass to DBI->connect (usually a dsn,
170             username, and password).
171              
172             =item Queries
173              
174             A hashref of the form Query_Name => "$SQL". For example:
175              
176             {
177             sysdate => "select sysdate from dual",
178             employee_record => "select * from emp where id = ?",
179             increase_inventory => "update inventory
180             set count = count + ?
181             where item_id = ?",
182             }
183              
184             As the example indicates, DBI placeholders are supported, as are DML
185             statements.
186              
187             =item Count
188              
189             The number of helper processes to spawn. Defaults to 3. The optimal
190             value for this parameter will depend on several factors, such as: how
191             many different queries your program will be running, how much RAM you
192             have, how often you run queries, and most importantly, how many
193             queries you intend to run I.
194              
195             =item ErrorState
196              
197             An listref containing a session and event name to receive error
198             messages from the DBI. The message arrives in ARG0.
199              
200             =back
201              
202             =cut
203              
204             sub new {
205 0     0 1   my $type = shift;
206              
207 0 0         croak "$type needs an even number of parameters" if @_ & 1;
208 0           my %params = @_;
209              
210 0           my $dsn = delete $params{DSN};
211 0 0         croak "$type needs a DSN parameter" unless defined $dsn;
212 0 0         croak "DSN needs to be an array reference" unless ref $dsn eq 'ARRAY';
213              
214 0           my $queries = delete $params{Queries};
215 0 0         croak "$type needs a Queries parameter" unless defined $queries;
216 0 0         croak "Queries needs to be a hash reference" unless ref $queries eq 'HASH';
217              
218 0   0       my $count = delete $params{Count} || DEFAULT_KIDS;
219             #croak "$type needs a Count parameter" unless defined $queries;
220              
221             # croak "Queries needs to be a hash reference" unless ref $queries eq 'HASH';
222              
223 0   0       my $debug = delete $params{Debug} || 0;
224             # $count = 1 if $debug;
225              
226 0   0       my $errorstate = delete $params{ErrorState} || undef;
227              
228             # Make sure the user didn't pass in parameters we're not aware of.
229 0 0         if (scalar keys %params) {
230 0           carp( "unknown parameters in $type constructor call: ",
231             join(', ', sort keys %params)
232             );
233             }
234 0           my $self = bless {}, $type;
235 0           my $config = shift;
236              
237 0           $self->{dsn} = $dsn;
238 0           $self->{queries} = $queries;
239 0           $self->{count} = $count;
240 0           $self->{debug} = $debug;
241 0           $self->{errorstate} = $errorstate;
242 0           $self->{finish} = 0;
243 0           $self->{pending_query_count} = 0;
244 0           $self->{active_query_count} = 0;
245 0           $self->{cookies} = [];
246 0           $self->{group_cache} = [];
247              
248             # POE::Session->new( $self,
249             # [ qw [ _start _stop db_reply remote_stderr error ] ]
250             # );
251              
252 0           POE::Session->create( object_states =>
253             [ $self => [ qw [ _start _stop db_reply remote_stderr error ] ] ]
254             );
255              
256 0           return $self;
257              
258             }
259              
260             # }}} new
261              
262             # {{{ query
263              
264             # {{{ POD
265              
266             =head2 query(I<$query_name>, [ \%args, ] I<$session>, I<$state>, [ I<@parameters> ])
267              
268             The C method takes at least three parameters, plus any bind
269             values for the specific query you are executing.
270              
271             =over
272              
273             =item $query_name
274              
275             This parameter must be one of the keys to the Queries hashref you
276             passed to the constructor. It is used to indicate which query you
277             wish to execute.
278              
279             =item \%args
280              
281             This is an OPTIONAL hashref of arguments to pass to the query.
282              
283             Currently supported arguments:
284              
285             =over 4
286              
287             =item hash
288              
289             Return rows hash references instead of array references.
290              
291             =item cookie
292              
293             A cookie to pass to this query. This is passed back unchanged to the
294             destination state in C<$_[ARG1]>. Can be any scalar (including
295             references, and even POE postbacks, so be careful!). You can use this
296             as an identifier if you have one destination state handling multiple
297             different queries or sessions.
298              
299             =item delay
300              
301             Insert a 1ms delay between each row of output.
302              
303             I know what you're thinking: "WHY would you want to slow down query
304             responses?!?!?" It has to do with CONCURRENCY. When a response
305             (finally) comes in from the agent after running the query, it floods
306             the input channel with response data. This has the effect of
307             monopolizing POE's attention, so that any other handles (network
308             sockets, pipes, file descriptors) keep getting pushed further back on
309             the queue, and to all other processes EXCEPT the agent, your POE
310             program looks hung for the amount of time it takes to process all of
311             the incoming query data.
312              
313             So, we insert 1ms of time via Time::HiRes's C function. In
314             human terms, this is essentially negligible. But it is just enough
315             time to allow competing handles (sockets, files) to trigger
316             C, and get handled by the POE::Kernel, in situations where
317             concurrency has priority over transfer rate.
318              
319             Naturally, the Time::HiRes module is required for this functionality.
320             If Time::HiRes is not installed, the delay is ignored.
321              
322             =item group
323              
324             Sends the return event back when C rows are retrieved from the
325             database, to avoid event spam when selecting lots of rows. NB: using
326             group means that C<$row> will be an arrayref of rows, not just a single
327             row.
328              
329             =back
330              
331             =item $session, $state
332              
333             These parameters indicate the POE state that is to receive the data
334             returned from the database. The state indicated will receive the data
335             in its C<$_[ARG0]> parameter. I make sure this is a valid
336             state, otherwise you will spend a LOT of time banging your head
337             against the wall wondering where your query data is.
338              
339             =item @parameters
340              
341             These are any parameters your query requires. B You must
342             supply exactly as many parameters as your query has placeholders!
343             This means that if your query has NO placeholders, then you should
344             pass NO extra parameters to C.
345              
346             Suggestions to improve this syntax are welcome.
347              
348             =back
349              
350             =cut
351              
352             # }}} POD
353              
354             sub query {
355 0     0 1   my ($self, $query, $package, $state, @rest) = @_;
356 0           my $options = {};
357              
358 0 0         if (ref $package) {
359 0 0         unless (ref $package eq 'HASH') {
360 0           carp "Options has must be a HASH reference";
361             }
362 0           $options = $package;
363              
364             # this shifts the first element off of @rest and puts it into
365             # $state
366 0           ($package, $state) = ($state, shift @rest);
367             }
368              
369             # warn "QD: Running $query";
370              
371 0           my $agent = $self->{helper}->next;
372 0           my $input = { query => $query,
373             package => $package, state => $state,
374             params => \@rest,
375             delay => 0,
376             id => "_",
377             %$options,
378             };
379              
380 0           $self->{pending_query_count}++;
381 0 0         if ($self->{active_query_count} < $self->{count} ) {
382              
383 0           $input->{id} = $agent->ID;
384 0           $self->{cookies}[$input->{id}] = delete $input->{cookie};
385 0           $agent->put( $input );
386 0           $self->{active_query_count}++;
387 0           $self->{group_cache}[$input->{id}] = [];
388              
389             } else {
390 0           push @{$self->{pending_queries}}, $input;
  0            
391             }
392              
393 0 0 0       $self->debug
394             && warn sprintf("QA:(#%s) %d pending: %s => %s, return %d rows at once\n",
395             $input->{id}, $self->{pending_query_count},
396             $input->{query},
397             "$input->{package}::$input->{state}",
398             $input->{group} || 1,
399             );
400              
401             }
402              
403             # }}} query
404              
405             #========================================================================================
406             # {{{ shutdown
407              
408             =head2 finish()
409              
410             The C method tells DBIAgent that the program is finished
411             sending queries. DBIAgent will shut its helpers down gracefully after
412             they complete any pending queries. If there are no pending queries,
413             the DBIAgent will shut down immediately.
414              
415             =cut
416              
417             sub finish {
418 0     0 1   my $self = shift;
419              
420 0           $self->{finish} = 1;
421              
422 0 0         unless ($self->{pending_query_count}) {
423 0 0         $self->debug and carp "QA: finish() called without pending queries. Shutting down now.";
424 0           $self->{helper}->exit_all();
425             }
426             else {
427 0 0         $self->debug && carp "QA: Setting finish flag for later.\n";
428             }
429             }
430              
431             # }}} shutdown
432              
433             #========================================================================================
434              
435             # {{{ STATES
436              
437             # {{{ _start
438              
439             sub _start {
440 0     0     my ($self, $kernel, $heap, $dsn, $queries) = @_[OBJECT, KERNEL, HEAP, ARG0, ARG1];
441              
442 0 0         $self->debug && warn __PACKAGE__ . " received _start.\n";
443              
444             # make this session accessible to the others.
445             #$kernel->alias_set( 'qa' );
446              
447 0           my $queue = POE::Component::DBIAgent::Queue->new();
448 0           $self->{filter} = POE::Filter::Reference->new();
449              
450             ## Input and output from the children will be line oriented
451 0           foreach (1..$self->{count}) {
452             my $helper = POE::Wheel::Run->new(
453             Program => sub {
454 0     0     POE::Component::DBIAgent::Helper->run($self->{dsn}, $self->{queries});
455             },
456 0 0         StdoutEvent => 'db_reply',
457             StderrEvent => 'remote_stderr',
458             ErrorEvent => 'error',
459             #StdinFilter => POE::Filter::Line->new(),
460             StdinFilter => POE::Filter::Reference->new(),
461             StdoutFilter => POE::Filter::Reference->new(),
462             )
463             or warn "Can't create new Wheel::Run: $!\n";
464 0 0         $self->debug && warn __PACKAGE__, " Started db helper pid ", $helper->PID, " wheel ", $helper->ID, "\n";
465 0           $queue->add($helper);
466             }
467              
468 0           $self->{helper} = $queue;
469              
470             }
471              
472             # }}} _start
473             # {{{ _stop
474              
475             sub _stop {
476 0     0     my ($self, $heap) = @_[OBJECT, HEAP];
477              
478 0           $self->{helper}->kill_all();
479              
480             # Oracle clients don't like to TERMinate sometimes.
481 0           $self->{helper}->kill_all(9);
482 0 0         $self->debug && warn __PACKAGE__ . " has stopped.\n";
483              
484             }
485              
486             # }}} _stop
487              
488             # {{{ db_reply
489              
490             sub db_reply {
491 0     0 0   my ($kernel, $self, $heap, $input) = @_[KERNEL, OBJECT, HEAP, ARG0];
492              
493             # Parse the "receiving state" and dispatch the input line to that state.
494              
495             # not needed for Filter::Reference
496 0           my ($package, $state, $data, $cookie, $group);
497 0           $package = $input->{package};
498 0           $state = $input->{state};
499 0           $data = $input->{data};
500 0   0       $group = $input->{group} || 0;
501             # change so cookies are no longer sent over the reference channel
502 0           $cookie = $self->{cookies}[$input->{id}];
503              
504 0 0 0       unless (ref $data or $data eq 'EOF') {
505 0           warn "QA: Got $data\n";
506             }
507             # $self->debug && $self->debug && warn "QA: received db_reply for $package => $state\n";
508              
509 0 0         unless (defined $data) {
510 0 0         $self->debug && warn "QA: Empty input value.\n";
511 0           return;
512             }
513              
514 0 0         if ($data eq 'EOF') {
515             # $self->debug && warn "QA: ${package}::${state} (#$input->{id}): EOF\n";
516 0           $self->{pending_query_count}--;
517 0           $self->{active_query_count}--;
518              
519 0 0         $self->debug
520             && warn sprintf("QA:(#%s) %d pending: EOF => %s\n",
521             $input->{id}, $self->{pending_query_count},
522             "$input->{package}::$input->{state}");
523              
524             # If this was the last query to go, and we've been requested
525             # to finish, then turn out the lights.
526 0 0 0       unless ($self->{pending_query_count}) {
    0          
527 0 0         if ($self->{finish}) {
528 0 0         $self->debug and warn "QA: Last query done, and finish flag set. Shutting down.\n";
529 0           $self->{helper}->exit_all();
530             }
531             }
532             elsif ($self->debug and $self->{pending_query_count} < 0) {
533 0           die "QA: Pending query count went negative (should never do that)";
534             }
535              
536             # place this agent at the front of the queue, for next query
537 0           $self->{helper}->make_next($input->{id});
538              
539 0 0 0       if ( $self->{pending_queries} and
  0   0        
540             @{$self->{pending_queries}} and
541             $self->{active_query_count} < $self->{count}
542             ) {
543              
544 0           my $input = shift @{$self->{pending_queries}};
  0            
545 0           my $agent = $self->{helper}->next;
546              
547 0           $input->{id} = $agent->ID;
548 0           $self->{cookies}[$input->{id}] = delete $input->{cookie};
549 0           $agent->put( $input );
550 0           $self->{active_query_count}++;
551              
552 0 0         $self->debug &&
553             warn sprintf("QA:(#%s) %d pending: %s => %s\n",
554             $input->{id}, $self->{pending_query_count},
555             $input->{query},
556             "$input->{package}::$input->{state}"
557             );
558              
559             }
560             }
561 0 0         if ($group) {
562 0           push @{ $self->{group_cache}[$input->{id}] }, $data;
  0            
563 0 0 0       if (scalar @{ $self->{group_cache}[$input->{id}] } == $group || $data eq 'EOF') {
  0            
564 0           $kernel->post($package => $state => $self->{group_cache}[$input->{id}], $cookie);
565 0           $self->{group_cache}[$input->{id}] = [];
566             }
567             } else {
568 0           $kernel->post($package => $state => $data => $cookie);
569             }
570              
571              
572             }
573              
574             # }}} db_reply
575              
576             # {{{ remote_stderr
577              
578             sub remote_stderr {
579 0     0 0   my ($self, $kernel, $operation, $errnum, $errstr, $wheel_id, $data) = @_[OBJECT, KERNEL, ARG0..ARG4];
580              
581 0 0         $self->debug && warn defined $errstr ? "$operation: $errstr\n" : "$operation\n";
    0          
582              
583 0 0         $kernel->post(@{$self->{errorstate}}, $operation, $errstr, $wheel_id) if defined $self->{errorstate};
  0            
584             }
585              
586             # }}} remote_stderr
587             # {{{ error
588              
589             sub error {
590 0     0 0   my ($self, $operation, $errnum, $errstr, $wheel_id) = @_[OBJECT, ARG0..ARG3];
591              
592 0 0         $errstr = "child process closed connection" unless $errnum;
593 0 0         $self->debug and warn "error: Wheel $wheel_id generated $operation error $errnum: $errstr\n";
594              
595 0           $self->{helper}->remove_by_wheelid($wheel_id);
596             }
597              
598             # }}} error
599              
600             # }}} STATES
601              
602             1;
603              
604             __END__