PostgreSQL.pm

filter: Statementstmt 57.8% 294 / 508 Branchbran 33.8% 61 / 180 Conditioncond 10.0% 2 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 58.2% 46 / 79 Podpod 100% 25 / 25 totaltotal 51.9% 428 / 824 CC 109 SCAR 25.0
CC
109
Cov
50%
__ANON__
56.0
send_copy_data
43.5
__ANON__
42.0
CRAP 12.2
↑ Summary PostgreSQL/Statement.pm »
1 package Protocol::PostgreSQL;
2 # ABSTRACT: PostgreSQL wire protocol
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use parent qw(Mixin::Event::Dispatch);
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 5 our $VERSION = '0.008';
8  
9 =head1 NAME
10  
11 Protocol::PostgreSQL - support for the PostgreSQL wire protocol
12  
13 =head1 VERSION
14  
15 version 0.008
16  
17 =head1 SYNOPSIS
18  
19 use strict; use warnings;
20 package PostgreSQL::Client;
21 use parent q{Protocol::PostgreSQL::Client};
22  
23 sub new { my $self = shift->SUPER::new(@_); $self->{socket} = $self->connect(...); $self }
24 sub on_send_request { shift->socket->send(@_) }
25 sub socket { shift->{socket} }
26  
27 sub connect { ... } # provide a method to connect to the server
28 sub incoming { shift->socket->read(@_) } # provide a method which passes on data from server
29  
30 package main;
31 my $client = PostgreSQL::Client->new(user => ..., server => ..., database => ...);
32 $client->simple_query(sql => q{select * from table}, on_data_row => sub {
33 my ($client, %args) = @_;
34 my @cols = $args{row};
35 print join(',', @cols) . "\n";
36 });
37  
38 =head1 DESCRIPTION
39  
40 Provides protocol-level support for PostgreSQL 7.4+, as defined in L<http://www.postgresql.org/docs/current/static/protocol.html>.
41  
42 =head2 CALLBACKS
43  
44 The following callbacks can be provided either as parameters to L</new> or as methods in subclasses:
45  
46 =over 4
47  
48 =item * on_send_request - Called each time there is a new message to be sent to the other side of the connection.
49  
50 =item * on_authenticated - Called when authentication is complete
51  
52 =item * on_copy_data - we have received data from an ongoing COPY request
53  
54 =item * on_copy_complete - the active COPY request has completed
55  
56 =back
57  
58 For the client, the following additional callbacks are available:
59  
60 =over 4
61  
62 =item * on_request_ready - the server is ready for the next request
63  
64 =item * on_bind_complete - a Bind request has completed
65  
66 =item * on_close_complete - the Close request has completed
67  
68 =item * on_command_complete - the requested command has finished, this will typically be followed by an on_request_ready event
69  
70 =item * on_copy_in_response - indicates that the server is ready to receive COPY data
71  
72 =item * on_copy_out_response - indicates that the server is ready to send COPY data
73  
74 =item * on_copy_both_response - indicates that the server is ready to exchange COPY data (for replication)
75  
76 =item * on_data_row - data from the current query
77  
78 =item * on_empty_query - special-case response when sent an empty query, can be used for 'ping'. Typically followed by on_request_ready
79  
80 =item * on_error - server has raised an error
81  
82 =item * on_function_call_result - results from a function call
83  
84 =item * on_no_data - indicate that a query returned no data, typically followed by on_request_ready
85  
86 =item * on_notice - server has sent us a notice
87  
88 =item * on_notification - server has sent us a NOTIFY
89  
90 =item * on_parameter_description - parameters are being described
91  
92 =item * on_parameter_status - parameter status...
93  
94 =item * on_parse_complete - parsing is done
95  
96 =item * on_portal_suspended - the portal has been suspended, probably hit the row limit
97  
98 =item * on_ready_for_query - we're ready for queries
99  
100 =item * on_row_description - descriptive information about the rows we're likely to be seeing shortly
101  
102 =back
103  
104 And the server can send these events:
105  
106 =over 4
107  
108 =item * on_copy_fail - the frontend is indicating that the copy has failed
109  
110 =item * on_describe - request for something to be described
111  
112 =item * on_execute - request execution of a given portal
113  
114 =item * on_flush - request flush
115  
116 =item * on_function_call - request execution of a given function
117  
118 =item * on_parse - request to parse something
119  
120 =item * on_password - password information
121  
122 =item * on_query - simple query request
123  
124 =item * on_ssl_request - we have an SSL request
125  
126 =item * on_startup_message - we have an SSL request
127  
128 =item * on_sync - sync request
129  
130 =item * on_terminate - termination request
131  
132 =back
133  
134 =cut
135  
136 5 ▶use Digest::MD5 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
137 5 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
138 5 ▶use POSIX qw{strftime};
Subroutine BEGIN: called CC=1 SCAR=0.0
139 5 ▶use Protocol::PostgreSQL::RowDescription;
Subroutine BEGIN: called CC=1 SCAR=0.0
140 5 ▶use Protocol::PostgreSQL::Statement;
Subroutine BEGIN: called CC=1 SCAR=0.0
141  
142 # Currently v3.0, which is used in PostgreSQL 7.4+
143 5 ▶use constant PROTOCOL_VERSION => 0x00030000;
Subroutine BEGIN: called CC=1 SCAR=0.0
144  
145 # Currently-allowed list of callbacks (can be set via ->configure)
146 5 our @CALLBACKS_ALLOWED = qw(
147 on_send_request
148 on_authenticated
149 on_copy_data
150 on_copy_complete
151 on_request_ready
152 on_bind_complete
153 on_close_complete
154 on_command_complete
155 on_copy_in_response
156 on_copy_out_response
157 on_copy_both_response
158 on_data_row
159 on_empty_query
160 on_error
161 on_function_call_result
162 on_no_data
163 on_notice
164 on_notification
165 on_parameter_description
166 on_parameter_status
167 on_parse_complete
168 on_portal_suspended
169 on_ready_for_query
170 on_row_description
171 on_copy_fail
172 on_describe
173 on_execute
174 on_flush
175 on_function_call
176 on_parse
177 on_password
178 on_query
179 on_ssl_request
180 on_startup_message
181 on_sync
182 on_terminate
183 );
184 # Hash form for convenience
185 5 my %CALLBACK_MAP = map { $_ => 1 } @CALLBACKS_ALLOWED;
186  
187 # Types of authentication response
188 5 my %AUTH_TYPE = (
189 0 => 'AuthenticationOk',
190 2 => 'AuthenticationKerberosV5',
191 3 => 'AuthenticationCleartextPassword',
192 5 => 'AuthenticationMD5Password',
193 6 => 'AuthenticationSCMCredential',
194 7 => 'AuthenticationGSS',
195 9 => 'AuthenticationSSPI',
196 8 => 'AuthenticationGSSContinue',
197 );
198  
199 # Transaction states the backend can be in
200 5 my %BACKEND_STATE = (
201 I => 'idle',
202 T => 'transaction',
203 E => 'error'
204 );
205  
206 # used for error and notice responses
207 5 my %NOTICE_CODE = (
208 S => 'severity',
209 C => 'code',
210 M => 'message',
211 D => 'detail',
212 H => 'hint',
213 P => 'position',
214 p => 'internal_position',
215 q => 'internal_query',
216 W => 'where',
217 F => 'file',
218 L => 'line',
219 R => 'routine'
220 );
221  
222 # Mapping from name to backend message code (single byte)
223 5 our %MESSAGE_TYPE_BACKEND = (
224 AuthenticationRequest => 'R',
225 BackendKeyData => 'K',
226 BindComplete => '2',
227 CloseComplete => '3',
228 CommandComplete => 'C',
229 CopyData => 'd',
230 CopyDone => 'c',
231 CopyInResponse => 'G',
232 CopyOutResponse => 'H',
233 CopyBothResponse => 'W',
234 DataRow => 'D',
235 EmptyQueryResponse => 'I',
236 ErrorResponse => 'E',
237 FunctionCallResponse => 'V',
238 NoData => 'n',
239 NoticeResponse => 'N',
240 NotificationResponse => 'A',
241 ParameterDescription => 't',
242 ParameterStatus => 'S',
243 ParseComplete => '1',
244 PortalSuspended => 's',
245 ReadyForQuery => 'Z',
246 RowDescription => 'T',
247 );
248 5 our %BACKEND_MESSAGE_CODE = reverse %MESSAGE_TYPE_BACKEND;
249  
250 # Mapping from name to frontend message code (single byte)
251 5 our %MESSAGE_TYPE_FRONTEND = (
252 Bind => 'B',
253 Close => 'C',
254 CopyData => 'd',
255 CopyDone => 'c',
256 CopyFail => 'f',
257 Describe => 'D',
258 Execute => 'E',
259 Flush => 'H',
260 FunctionCall => 'F',
261 Parse => 'P',
262 PasswordMessage => 'p',
263 Query => 'Q',
264 # Both of these are handled separately
265 # SSLRequest => '',
266 # StartupMessage => '',
267 Sync => 'S',
268 Terminate => 'X',
269 );
270 5 our %FRONTEND_MESSAGE_CODE = reverse %MESSAGE_TYPE_FRONTEND;
271  
272 # Defined message handlers for outgoing frontend messages
273 our %FRONTEND_MESSAGE_BUILDER = (
274 # Bind parameters to an existing prepared statement
275 0 ▶ Bind => sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
276 0 my $self = shift;
277 0 my %args = @_;
278  
279 0 ▶ $args{param} ||= [];
Condition0%0/2
$args{"param"} ||= []
l!l
00
MC/DC0%0/1
$args{"param"} ||= []
$args{"param"}
Truth table0%0/2
A
A= $args{"param"}
Aresult
11
00
280 0 my $param = '';
281 0 my $count = scalar @{$args{param}};
282 0 foreach my $p (@{$args{param}}) {
283 0 ▶ if(!defined $p) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $p) { } 0 0 0
284 0 $param .= pack('N1', 0xFFFFFFFF);
285 } else {
286 0 $param .= pack('N1a*', length($p), $p);
287 }
288 }
289 my $msg = pack('Z*Z*n1n1a*n1',
290 defined($args{portal}) ? $args{portal} : '',
291 0 ▶ defined($args{statement}) ? $args{statement} : '',
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'portal'} ? : 0 0 0
defined $args{'statement'} ? : 0 0 0
292 0, # Parameter types
293 $count, # Number of bound parameters
294 $param, # Actual parameter values
295 0 # Number of result column format definitions (0=use default text format)
296 );
297 0 ▶ push @{$self->{pending_bind}}, $args{sth} if $args{sth};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"sth"} 0 0 0
298 0 ▶ $self->debug(sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
299 join('',
300 "Bind",
301 defined($args{portal}) ? " for portal [" . $args{portal} . "]" : '',
302 defined($args{statement}) ? " for statement [" . $args{statement} . "]" : '',
303 " with $count parameter(s): ",
304 0 ▶ join(',', @{$args{param}})
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'portal'} ? : 0 0 0
defined $args{'statement'} ? : 0 0 0
305 )
306 0 });
307 0 return $self->_build_message(
308 type => 'Bind',
309 data => $msg,
310 );
311 },
312 0 ▶ CopyData => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
313 0 my $self = shift;
314 0 my %args = @_;
315 return $self->_build_message(
316 type => 'CopyData',
317 data => pack('a*', $args{data})
318 0 );
319 },
320 0 ▶ Close => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
321 0 my $self = shift;
322 0 my %args = @_;
323  
324 my $msg = pack('a1Z*',
325 exists $args{portal} ? 'P' : 'S', # close a portal or a statement
326 defined($args{statement})
327 ? $args{statement}
328 : (defined($args{portal})
329 ? $args{portal}
330 0 ▶ : ''
Branch: 3 branches
BranchTrueFalseTotal
exists $args{'portal'} ? : 0 0 0
defined $args{'statement'} ? : 0 0 0
defined $args{'portal'} ? : 0 0 0
331 )
332 );
333 0 ▶ push @{$self->{pending_close}}, $args{on_complete} if $args{on_complete};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"on_complete"} 0 0 0
334 0 return $self->_build_message(
335 type => 'Close',
336 data => $msg,
337 );
338 },
339 0 ▶ CopyDone => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
340 0 my $self = shift;
341 0 return $self->_build_message(
342 type => 'CopyDone',
343 data => '',
344 );
345 },
346 # Describe expected SQL results
347 1 ▶ Describe => sub {
Subroutine __ANON__: called CC=5 SCAR=17.2
348 1 my $self = shift;
349 1 my %args = @_;
350  
351 1 ▶ my $msg = pack('a1Z*', exists $args{portal} ? 'P' : 'S', defined($args{statement}) ? $args{statement} : (defined($args{portal}) ? $args{portal} : ''));
Branch: 3 branches
BranchTrueFalseTotal
exists $args{'portal'} ? : 0 1 1
defined $args{'statement'} ? : 0 1 1
defined $args{'portal'} ? : 0 1 1
352 1 ▶ push @{$self->{pending_describe}}, $args{sth} if $args{sth};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"sth"} 1 0 1
353 1 return $self->_build_message(
354 type => 'Describe',
355 data => $msg,
356 ) . $self->_build_message(
357 type => 'Query',
358 data => "\0"
359 );
360 },
361 # Execute either a named or anonymous portal (prepared statement with bind vars)
362 0 ▶ Execute => sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
363 0 my $self = shift;
364 0 my %args = @_;
365  
366 0 ▶ my $msg = pack('Z*N1', defined($args{portal}) ? $args{portal} : '', $args{limit} || 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'portal'} ? : 0 0 0
Condition0%0/2
$args{'limit'} || 0
l!l
00
MC/DC0%0/1
$args{'limit'} || 0
$args{'limit'}
Truth table0%0/2
A
A= $args{'limit'}
Aresult
11
00
367 0 ▶ push @{$self->{pending_execute}}, $args{sth} if $args{sth};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"sth"} 0 0 0
368 0 ▶ $self->debug("Executing " . (defined($args{portal}) ? "portal " . $args{portal} : "default portal") . ($args{limit} ? " with limit " . $args{limit} : " with no limit"));
Branch: 2 branches
BranchTrueFalseTotal
defined $args{'portal'} ? : 0 0 0
$args{'limit'} ? : 0 0 0
369 0 return $self->_build_message(
370 type => 'Execute',
371 data => $msg,
372 );
373 },
374 # Parse SQL for a prepared statement
375 1 ▶ Parse => sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
376 1 my $self = shift;
377 1 my %args = @_;
378 1 ▶ die "No SQL provided" unless defined $args{sql};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"sql"} 0 1 1
379  
380 1 ▶ my $msg = pack('Z*Z*n1', (defined($args{statement}) ? $args{statement} : ''), $args{sql}, 0);
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'statement'} ? : 0 1 1
381 1 return $self->_build_message(
382 type => 'Parse',
383 data => $msg,
384 );
385 },
386 # Password data, possibly encrypted depending on what the server specified
387 1 ▶ PasswordMessage => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
388 1 my $self = shift;
389 1 my %args = @_;
390  
391 1 my $pass = $args{password};
392 1 ▶ if($self->{password_type} eq 'md5') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"password_type"} eq "md5") 0 1 1
393 # md5hex of password . username,
394 # then md5hex result with salt appended
395 # then stick 'md5' at the front.
396 $pass = 'md5' . Digest::MD5::md5_hex(
397 Digest::MD5::md5_hex($pass . $self->{user})
398 . $self->{password_salt}
399 0 );
400 }
401  
402 # Yes, protocol requires zero-terminated string format even
403 # if we have a binary password value.
404 1 return $self->_build_message(
405 type => 'PasswordMessage',
406 data => pack('Z*', $pass)
407 );
408 },
409 # Simple query
410 4 ▶ Query => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
411 4 my $self = shift;
412 4 my %args = @_;
413 return $self->_build_message(
414 type => 'Query',
415 data => pack('Z*', $args{sql})
416 4 );
417 },
418 # Initial mesage informing the server which database and user we want
419 3 ▶ StartupMessage => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
420 3 my $self = shift;
421 3 ▶ die "Not first message" unless $self->is_first_message;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_first_message 0 3 3
422  
423 3 my %args = @_;
424 3 my $parameters = join('', map { pack('Z*', $_) } map { $_, $args{$_} } grep { exists $args{$_} } qw(user database options));
425 3 $parameters .= "\0";
426  
427 3 return $self->_build_message(
428 type => undef,
429 data => pack('N*', PROTOCOL_VERSION) . $parameters
430 );
431 },
432 # Synchonise after a prepared statement has finished execution.
433 0 ▶ Sync => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
434 0 my $self = shift;
435 0 return $self->_build_message(
436 type => 'Sync',
437 data => '',
438 );
439 },
440 0 ▶ Terminate => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
441 0 my $self = shift;
442 0 return $self->_build_message(
443 type => 'Terminate',
444 data => '',
445 );
446 },
447 5 );
448  
449 # Handlers for specification authentication messages from backend.
450 my %AUTH_HANDLER = (
451 2 ▶ AuthenticationOk => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
452 2 my ($self, $msg) = @_;
453 2 $self->invoke_event('authenticated');
454 2 $self->invoke_event('request_ready');
455 2 return $self;
456 },
457 0 ▶ AuthenticationKerberosV5 => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
458 0 my ($self, $msg) = @_;
459 0 die "Not yet implemented";
460 },
461 2 ▶ AuthenticationCleartextPassword => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
462 2 my ($self, $msg) = @_;
463 2 $self->{password_type} = 'plain';
464 2 $self->invoke_event('password');
465 2 return $self;
466 },
467 0 ▶ AuthenticationMD5Password => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
468 0 my ($self, $msg) = @_;
469 0 (undef, undef, undef, my $salt) = unpack('C1N1N1a4', $msg);
470 0 $self->{password_type} = 'md5';
471 0 $self->{password_salt} = $salt;
472 0 $self->invoke_event('password');
473 0 return $self;
474 },
475 0 ▶ AuthenticationSCMCredential => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
476 0 my ($self, $msg) = @_;
477 0 die "Not yet implemented";
478 0 return $self;
479 },
480 0 ▶ AuthenticationGSS => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
481 0 my ($self, $msg) = @_;
482 0 die "Not yet implemented";
483 },
484 0 ▶ AuthenticationSSPI => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
485 0 my ($self, $msg) = @_;
486 0 die "Not yet implemented";
487 },
488 0 ▶ AuthenticationGSSContinue => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
489 0 my ($self, $msg) = @_;
490 0 die "Not yet implemented";
491 }
492 5 );
493  
494 # Defined message handlers for incoming messages from backend
495 our %BACKEND_MESSAGE_HANDLER = (
496 # We had some form of authentication request or response, pass it over to an auth handler to deal with it further.
497 4 ▶ AuthenticationRequest => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
498 4 my $self = shift;
499 4 my $msg = shift;
500  
501 4 my (undef, undef, $auth_code) = unpack('C1N1N1', $msg);
502 4 ▶ my $auth_type = $AUTH_TYPE{$auth_code} or die "Invalid auth code $auth_code received";
Branch: 1 branch
BranchTrueFalseTotal
my $auth_type = $AUTH_TYPE{$auth_code} or die "Invalid auth code $auth_code received" 4 0 4
503 4 $self->debug("Auth message [$auth_type]");
504 4 return $AUTH_HANDLER{$auth_type}->($self, $msg);
505 },
506 # Key data for cancellation requests
507 0 ▶ BackendKeyData => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
508 0 my $self = shift;
509 0 my $msg = shift;
510 0 (undef, my $size, my $pid, my $key) = unpack('C1N1N1N1', $msg);
511 0 $self->invoke_event('backendkeydata',
512 pid => $pid,
513 key => $key
514 );
515 0 return $self;
516 },
517 # A bind operation has completed
518 0 ▶ BindComplete => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
519 0 my $self = shift;
520 0 my $msg = shift;
521 0 (undef, my $size) = unpack('C1N1', $msg);
522 0 ▶ if(my $sth = shift(@{$self->{pending_bind}})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $sth = shift @{$$self{"pending_bind"};}) 0 0 0
523 0 $self->debug("Pass over to statement $sth");
524 0 $sth->bind_complete;
525 }
526 0 $self->invoke_event('bind_complete');
527 0 return $self;
528 },
529 # We have closed the connection to the server successfully
530 0 ▶ CloseComplete => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
531 0 my $self = shift;
532 0 my $msg = shift;
533 0 (undef, my $size) = unpack('C1N1', $msg);
534  
535 # Handler could be undef - we always push something to keep things symmetrical
536 0 ▶ if(my $handler = shift @{$self->{pending_close}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $handler = shift @{$$self{"pending_close"};}) 0 0 0
537 0 $handler->($self);
538 }
539 0 $self->invoke_event('close_complete');
540 0 return $self;
541 },
542 # A command has completed, we should see a ready response immediately after this
543 2 ▶ CommandComplete => sub {
Subroutine __ANON__: called CC=3 SCAR=13.6
544 2 my $self = shift;
545 2 my $msg = shift;
546 2 my (undef, undef, $result) = unpack('C1N1Z*', $msg);
547 2 ▶ if(@{$self->{pending_execute}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"pending_execute"};}) 0 2 2
548 0 my $last = shift @{$self->{pending_execute}};
549 0 $self->debug("Finished command for $last");
550 0 ▶ $last->command_complete if $last;
Branch: 1 branch
BranchTrueFalseTotal
if $last 0 0 0
551 }
552 2 $self->invoke_event('command_complete', result => $result);
553 2 return $self;
554 },
555 # We have a COPY response from the server indicating that it's ready to accept COPY data
556 1 ▶ CopyInResponse => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
557 1 my $self = shift;
558 1 my $msg = shift;
559 1 (undef, undef, my $type, my $count) = unpack('C1N1C1n1', $msg);
560 1 substr $msg, 0, 8, '';
561 1 my @formats;
562 1 for (1..$count) {
563 3 push @formats, unpack('n1', $msg);
564 3 substr $msg, 0, 2, '';
565 }
566 1 $self->invoke_event('copy_in_response', count => $count, columns => \@formats);
567 1 return $self;
568 },
569 # The basic SQL result - a single row of data
570 2 ▶ DataRow => sub {
Subroutine __ANON__: called CC=7 SCAR=19.7
571 2 my $self = shift;
572 2 my $msg = shift;
573 2 my (undef, undef, $count) = unpack('C1N1n1', $msg);
574 2 substr $msg, 0, 7, '';
575 2 my @fields;
576 # TODO Tidy this up
577 2 ▶ my $sth = @{$self->{pending_execute}} ? $self->{pending_execute}[0] : $self->active_statement;
Branch: 1 branch
BranchTrueFalseTotal
@{$self->{'pending_execute'};} ? : 0 2 2
578 2 ▶ my $desc = $sth ? $sth->row_description : $self->row_description;
Branch: 1 branch
BranchTrueFalseTotal
$sth ? : 0 2 2
579 2 foreach my $idx (0..$count-1) {
580 3 my $field = $desc->field_index($idx);
581 3 my ($size) = unpack('N1', $msg);
582 3 substr $msg, 0, 4, '';
583 3 my $data;
584 3 my $null = ($size == 0xFFFFFFFF);
585 3 ▶ unless($null) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($null) 3 0 3
586 3 $data = $field->parse_data($msg, $size);
587 3 substr $msg, 0, $size, '';
588 }
589 3 ▶ push @fields, {
Branch: 1 branch
BranchTrueFalseTotal
$null ? : 0 3 3
590 null => $null,
591 description => $field,
592 data => $null ? undef : $data,
593 }
594 }
595 2 ▶ $sth->data_row(\@fields) if $sth;
Branch: 1 branch
BranchTrueFalseTotal
if $sth 0 2 2
596 2 $self->invoke_event('data_row', row => \@fields);
597 2 return $self;
598 },
599 # Response given when empty query (whitespace only) is provided
600 1 ▶ EmptyQueryResponse => sub {
Subroutine __ANON__: called CC=2 SCAR=7.8
601 1 my $self = shift;
602 1 my $msg = shift;
603 1 ▶ if(@{$self->{pending_execute}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"pending_execute"};}) 0 1 1
604 0 my $last = shift @{$self->{pending_execute}};
605 0 $self->debug("Finished command for $last");
606 }
607 1 $self->invoke_event('empty_query');
608 1 return $self;
609 },
610 # An error occurred, can indicate that connection is about to close or just be a warning
611 0 ▶ ErrorResponse => sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
612 0 my $self = shift;
613 0 my $msg = shift;
614 0 (undef, my $size) = unpack('C1N1', $msg);
615 0 substr $msg, 0, 5, '';
616 0 my %notice;
617 FIELD:
618 0 ▶ while(length($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $msg) 0 0 0
619 0 my ($code, $str) = unpack('A1Z*', $msg);
620 0 ▶ last FIELD unless $code && $code ne "\0";
Branch: 1 branch
BranchTrueFalseTotal
unless $code and $code ne "\0" 0 0 0
Condition0%0/3
$code and $code ne "\0"
!ll&&!rl&&r
000
MC/DC0%0/2
$code and $code ne "\0"
$code $code ne "\0"
Truth table0%0/3
A and B
A= $codeB= $code ne "\0"
ABresult
0X0
100
111
621  
622 0 ▶ die "Unknown NOTICE code [$code]" unless exists $NOTICE_CODE{$code};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $NOTICE_CODE{$code} 0 0 0
623 0 $notice{$NOTICE_CODE{$code}} = $str;
624 0 substr $msg, 0, 2+length($str), '';
625 }
626 0 ▶ if(@{$self->{pending_execute}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"pending_execute"};}) 0 0 0
627 0 my $last = shift @{$self->{pending_execute}};
628 0 $self->debug("Error for $last");
629 }
630 0 $self->invoke_event('error', error => \%notice);
631 0 return $self;
632 },
633 # Result from calling a function
634 0 ▶ FunctionCallResponse => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
635 0 my $self = shift;
636 0 my $msg = shift;
637 0 (undef, my $size, my $len) = unpack('C1N1N1', $msg);
638 0 substr $msg, 0, 9, '';
639 0 ▶ my $data = ($len == 0xFFFFFFFF) ? undef : substr $msg, 0, $len;
Branch: 1 branch
BranchTrueFalseTotal
$len == 4294967295 ? : 0 0 0
640 0 $self->invoke_event('function_call_response', data => $data);
641 0 return $self;
642 },
643 # No data follows
644 0 ▶ NoData => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
645 0 my $self = shift;
646 0 my $msg = shift;
647 0 (undef, my $size) = unpack('C1N1', $msg);
648 0 $self->invoke_event('no_data');
649 0 return $self;
650 },
651 # We have a notice, which is like an error but can be just informational
652 1 ▶ NoticeResponse => sub {
Subroutine __ANON__: called CC=5 SCAR=16.4
653 1 my $self = shift;
654 1 my $msg = shift;
655 1 (undef, my $size) = unpack('C1N1', $msg);
656 1 substr $msg, 0, 5, '';
657 1 my %notice;
658 FIELD:
659 1 ▶ while(length($msg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $msg) 4 1 5
660 4 my ($code, $str) = unpack('A1Z*', $msg);
661 4 ▶ last FIELD unless $code && $code ne "\0";
Branch: 1 branch
BranchTrueFalseTotal
unless $code and $code ne "\0" 0 4 4
Condition33%1/3
$code and $code ne "\0"
!ll&&!rl&&r
004
MC/DC0%0/2
$code and $code ne "\0"
$code $code ne "\0"
Truth table33%1/3
A and B
A= $codeB= $code ne "\0"
ABresult
0X0
100
111
662  
663 4 ▶ die "Unknown NOTICE code [$code]" unless exists $NOTICE_CODE{$code};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $NOTICE_CODE{$code} 0 4 4
664 4 $notice{$NOTICE_CODE{$code}} = $str;
665 4 substr $msg, 0, 2+length($str), '';
666 }
667 1 $self->invoke_event('notice', notice => \%notice);
668 1 return $self;
669 },
670 # LISTEN/NOTIFY mechanism
671 0 ▶ NotificationReponse => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
672 0 my $self = shift;
673 0 my $msg = shift;
674 0 (undef, my $size, my $pid, my $channel, my $data) = unpack('C1N1N1Z*Z*', $msg);
675 0 $self->invoke_event('notification', pid => $pid, channel => $channel, data => $data);
676 0 return $self;
677 },
678 # Connection parameter information
679 0 ▶ ParameterStatus => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
680 0 my $self = shift;
681 0 my $msg = shift;
682 0 (undef, my $size) = unpack('C1N1', $msg);
683 0 substr $msg, 0, 5, '';
684 0 my %status;
685 # Series of key,value pairs
686 PARAMETER:
687 0 while(1) {
688 0 my ($k, $v) = unpack('Z*Z*', $msg);
689 0 ▶ last PARAMETER unless defined($k) && length($k);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k and length $k 0 0 0
Condition0%0/3
defined $k and length $k
!ll&&!rl&&r
000
MC/DC0%0/2
defined $k and length $k
defined $k length $k
Truth table0%0/3
A and B
A= defined $kB= length $k
ABresult
0X0
100
111
690 0 $status{$k} = $v;
691 0 substr $msg, 0, length($k) + length($v) + 2, '';
692 }
693 0 $self->invoke_event('parameter_status', status => \%status);
694 0 return $self;
695 },
696 # Description of the format that subsequent parameters are using, typically plaintext only
697 0 ▶ ParameterDescription => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
698 0 my $self = shift;
699 0 my $msg = shift;
700 0 (undef, my $size, my $count) = unpack('C1N1n1', $msg);
701 0 substr $msg, 0, 7, '';
702 0 my @oid_list;
703 0 for my $idx (1..$count) {
704 0 my ($oid) = unpack('N1', $msg);
705 0 substr $msg, 0, 4, '';
706 0 push @oid_list, $oid;
707 }
708 0 $self->invoke_event('parameter_description', parameters => \@oid_list);
709 0 return $self;
710 },
711 # Parse request succeeded
712 0 ▶ ParseComplete => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
713 0 my $self = shift;
714 0 my $msg = shift;
715 0 (undef, my $size) = unpack('C1N1', $msg);
716 0 ▶ $self->active_statement->parse_complete if $self->active_statement;
Branch: 1 branch
BranchTrueFalseTotal
if $self->active_statement 0 0 0
717 0 $self->invoke_event('parse_complete');
718 0 return $self;
719 },
720 # Portal has sent enough data to meet the row limit, should be requested again if more is required
721 0 ▶ PortalSuspended => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
722 0 my $self = shift;
723 0 my $msg = shift;
724 0 (undef, my $size) = unpack('C1N1', $msg);
725 0 ▶ if(@{$self->{pending_execute}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"pending_execute"};}) 0 0 0
726 0 my $last = shift @{$self->{pending_execute}};
727 0 $self->debug("Suspended portal for $last");
728 }
729 0 $self->invoke_event('portal_suspended');
730 0 return $self;
731 },
732 # All ready to accept queries
733 5 ▶ ReadyForQuery => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
734 5 my $self = shift;
735 5 my $msg = shift;
736 5 my (undef, undef, $state) = unpack('C1N1A1', $msg);
737 5 $self->debug("Backend state is $state");
738 5 $self->backend_state($BACKEND_STATE{$state});
739 5 $self->is_ready(1);
740 5 ▶ return $self->send_next_in_queue if $self->has_queued;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_queued 0 5 5
741 5 $self->invoke_event('ready_for_query');
742 5 return $self;
743 },
744 # Information on the row data that's expected to follow
745 2 ▶ RowDescription => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
746 2 my $self = shift;
747 2 my $msg = shift;
748 2 my (undef, undef, $count) = unpack('C1N1n1', $msg);
749 2 my $row = Protocol::PostgreSQL::RowDescription->new;
750 2 substr $msg, 0, 7, '';
751 2 foreach my $id (0..$count-1) {
752 3 my ($name, $table_id, $field_id, $data_type, $data_size, $type_modifier, $format_code) = unpack('Z*N1n1N1n1N1n1', $msg);
753 3 my %data = (
754 name => $name,
755 table_id => $table_id,
756 field_id => $field_id,
757 data_type => $data_type,
758 data_size => $data_size,
759 type_modifier => $type_modifier,
760 format_code => $format_code
761 );
762 3 $self->debug($_ . ' => ' . $data{$_}) for sort keys %data;
763 3 my $field = Protocol::PostgreSQL::FieldDescription->new(%data);
764 3 $row->add_field($field);
765 3 substr $msg, 0, 19 + length($name), '';
766 }
767 2 $self->row_description($row);
768 2 ▶ if(my $last = shift @{$self->{pending_describe}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $last = shift @{$$self{"pending_describe"};}) 0 2 2
769 0 $last->row_description($row);
770 }
771 2 $self->invoke_event('row_description', description => $row);
772 2 return $self;
773 },
774 5 );
775  
776 =head1 METHODS
777  
778 =cut
779  
780 =head2 new
781  
782 Instantiate a new object. Blesses an empty hashref and calls L</configure>, subclasses can bypass this entirely
783 and just call L</configure> directly after instantiation.
784  
785 =cut
786  
787 4 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
788 4 my $self = bless {
789 }, shift;
790 4 $self->configure(@_);
791 4 return $self;
792 }
793  
794 =head2 configure
795  
796 Does the real preparation for the object.
797  
798 Takes callbacks as named parameters, including:
799  
800 =over 4
801  
802 =item * on_error
803  
804 =item * on_data_row
805  
806 =item * on_ready_for_query
807  
808 =back
809  
810 =cut
811  
812 4 ▶sub configure {
Subroutine configure: called CC=10 SCAR=23.7
Pod documented
813 4 my $self = shift;
814 4 my %args = @_;
815  
816 # Init parameters - should only be needed on first call
817 4 $self->{$_} = [] for grep !exists $self->{$_}, qw(pending_execute pending_describe message_queue);
818 4 $self->{$_} = 0 for grep !exists $self->{$_}, qw(authenticated message_count);
819 4 ▶ $self->{wait_for_startup} = 1 unless exists $self->{wait_for_startup};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"wait_for_startup"} 4 0 4
820  
821 4 ▶ $self->{debug} = delete $args{debug} if exists $args{debug};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"debug"} 3 1 4
822  
823 4 ▶ $self->{user} = delete $args{user} if exists $args{user};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"user"} 0 4 4
824 4 ▶ $self->{pass} = delete $args{pass} if exists $args{pass};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"pass"} 0 4 4
825 4 ▶ $self->{database} = delete $args{database} if exists $args{database};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"database"} 0 4 4
826  
827 # Callbacks
828 4 foreach my $k (grep /on_(.+)$/, keys %args) {
829 4 my ($event) = $k =~ /on_(.+)$/;
830 4 ▶ die "Unknown callback '$k'" unless exists $CALLBACK_MAP{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $CALLBACK_MAP{$k} 0 4 4
831 4 $self->add_handler_for_event($event => delete $args{$k});
832 }
833 4 return %args;
834 }
835  
836 =head2 has_queued
837  
838 Returns number of queued messages.
839  
840 =cut
841  
842 5 ▶sub has_queued { scalar(@{$_[0]->{message_queue}}) }
Subroutine has_queued: called CC=1 SCAR=0.0
Pod documented
843  
844 =head2 is_authenticated
845  
846 Returns true if we are authenticated (and can start sending real data).
847  
848 =cut
849  
850 1 ▶sub is_authenticated { shift->{authenticated} ? 1 : 0 }
Subroutine is_authenticated: called CC=2 SCAR=7.6
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
+(shift())->{'authenticated'} ? : 0 1 1
851  
852 =head2 is_first_message
853  
854 Returns true if this is the first message, as per L<http://developer.postgresql.org/pgdocs/postgres/protocol-overview.html>:
855  
856 "For historical reasons, the very first message sent by the client (the startup message)
857 has no initial message-type byte."
858  
859 =cut
860  
861 16 ▶sub is_first_message { shift->{message_count} < 1 }
Subroutine is_first_message: called CC=1 SCAR=0.0
Pod documented
862  
863 =head2 initial_request
864  
865 Generate and send the startup request.
866  
867 =cut
868  
869 2 ▶sub initial_request {
Subroutine initial_request: called CC=3 SCAR=11.0
Pod documented
870 2 my $self = shift;
871 2 my %args = @_;
872 2 ▶ my %param = map { $_ => exists $args{$_} ? delete $args{$_} : $self->{$_} } qw(database user);
Branch: 1 branch
BranchTrueFalseTotal
exists $args{$_} ? : 2 2 4
873 2 delete @param{grep { !defined($param{$_}) } keys %param};
874 2 ▶ die "don't know how to handle " . join(',', keys %args) if keys %args;
Branch: 1 branch
BranchTrueFalseTotal
if keys %args 0 2 2
875  
876 2 $self->send_message('StartupMessage', %param);
877 2 $self->{wait_for_startup} = 0;
878 2 return $self;
879 }
880  
881 =head2 send_message
882  
883 Send a message.
884  
885 =cut
886  
887 4 ▶sub send_message {
Subroutine send_message: called CC=2 SCAR=9.9
Pod documented
888 4 my $self = shift;
889  
890 # Clear the ready-to-send flag since we're about to throw a message over to the
891 # server and we don't want any others getting in the way.
892 4 $self->{is_ready} = 0;
893  
894 4 my $msg = $self->message(@_);
895 4 ▶ die "Empty message?" unless defined $msg;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $msg 0 4 4
896  
897 # Use the coderef form of the debug call since the packet breakdown is a slow operation.
898 0 ▶ $self->debug(sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
899 "send data: [" .
900 join(" ", map sprintf("%02x", ord($_)), split //, $msg) . "], " .
901 (($self->is_first_message ? "startup packet" : $FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)}) || 'unknown message') . " (" .
902 0 ▶ join('', '', map { (my $txt = defined($_) ? $_ : '') =~ tr/ []"'!#$%*&=:;A-Za-z0-9,()_ -/./c; $txt } split //, $msg) . ")"
Branch: 2 branches
BranchTrueFalseTotal
$self->is_first_message ? : 0 0 0
defined $_ ? : 0 0 0
Condition0%0/2
($self->is_first_message ? 'startup packet' : $Protocol::PostgreSQL::FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)}) || 'unknown message'
l!l
00
MC/DC0%0/1
($self->is_first_message ? 'startup packet' : $Protocol::PostgreSQL::FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)}) || 'unknown message'
($self->is_first_message ? 'startup packet' : $Protocol::PostgreSQL::FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)})
Truth table0%0/2
A
A= ($self->is_first_message ? 'startup packet' : $Protocol::PostgreSQL::FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)})
Aresult
11
00
903 4 });
904 4 $self->invoke_event('send_request', $msg);
905 4 return $self;
906 }
907  
908 =head2 queue
909  
910 Queue up a message for sending. The message will only be sent when we're in ReadyForQuery
911 mode, which could be immediately or later.
912  
913 =cut
914  
915 5 ▶sub queue {
Subroutine queue: called CC=4 SCAR=13.9
Pod documented
916 5 my $self = shift;
917 5 my %args = @_;
918  
919 # Get raw message data to send, could be passed as a ready-built message packet or a set of parameters.
920 5 my $msg = delete $args{message};
921 5 ▶ unless($msg) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($msg) 1 4 5
922 # Might get a message with no parameters
923 1 ▶ $msg = $self->message(delete $args{type}, @{ delete $args{parameters} || [] });
Condition50%1/2
delete $args{'parameters'} || []
l!l
10
MC/DC0%0/1
delete $args{'parameters'} || []
delete $args{'parameters'}
Truth table50%1/2
A
A= delete $args{'parameters'}
Aresult
11
00
924 }
925  
926 # Add this to the queue
927 5 push @{$self->{message_queue}}, {
928 message => $msg,
929 %args
930 };
931  
932 # Send immediately if we're in a ready state
933 5 ▶ $self->send_next_in_queue if $self->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_ready 5 0 5
934 5 return $self;
935 }
936  
937 =head2 send_next_in_queue
938  
939 Send the next queued message.
940  
941 =cut
942  
943 5 ▶sub send_next_in_queue {
Subroutine send_next_in_queue: called CC=3 SCAR=11.2
Pod documented
944 5 my $self = shift;
945  
946 # TODO Clean up the duplication between this method and L</send_message>.
947 5 ▶ if(my $info = shift @{$self->{message_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $info = shift @{$$self{"message_queue"};}) 5 0 5
948 5 my $msg = delete $info->{message};
949  
950 # Clear flag so we only send a single message rather than hammering the server with everything in the queue
951 5 $self->{is_ready} = 0;
952 0 ▶ $self->debug(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
953 0 "send data: [" . join(" ", map sprintf("%02x", ord($_)), split //, $msg) . "], " . $FRONTEND_MESSAGE_CODE{substr($msg, 0, 1)} . " (" . join("", grep { /^([a-z0-9,()_ -])$/ } split //, $msg) . ")"
954 5 });
955 5 $self->invoke_event('send_request', $msg);
956  
957 # Ping the callback to let it know message is now in flight
958 5 ▶ $info->{callback}->($self, $info) if exists $info->{callback};
Branch: 1 branch
BranchTrueFalseTotal
if exists $info->{"callback"} 1 4 5
959 }
960 5 return $self;
961 }
962  
963 =head2 message
964  
965 Creates a new message of the given type.
966  
967 =cut
968  
969 10 ▶sub message {
Subroutine message: called CC=2 SCAR=7.0
Pod documented
970 10 my $self = shift;
971 10 my $type = shift;
972 10 ▶ die "Message $type unknown" unless exists $FRONTEND_MESSAGE_BUILDER{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $Protocol::PostgreSQL::FRONTEND_MESSAGE_BUILDER{$type} 0 10 10
973  
974 10 my $msg = $FRONTEND_MESSAGE_BUILDER{$type}->($self, @_);
975 10 ++$self->{message_count};
976 10 return $msg;
977 }
978  
979 =head2 attach_event
980  
981 Attach new handler(s) to the given event(s).
982  
983 =cut
984  
985 0 ▶sub attach_event {
Subroutine attach_event: not called CC=3 SCAR=24.8
Pod documented
986 0 my $self = shift;
987 0 my %args = @_;
988 0 $self->debug("Using old ->attach_event interface, suggest ->add_handler_for_event from Mixin::Event::Dispatch instead for %s", join(',', keys %args));
989 $self->add_handler_for_event(
990 0 ▶ map { $_ => sub { $args{$_}->(@_); 1 } } keys %args
Subroutine __ANON__: not called CC=1 SCAR=6.9
991 );
992 0 for (keys %args) {
993 0 my $k = "on_$_";
994 0 ▶ die "Unknown callback '$_'" unless exists $CALLBACK_MAP{$k};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $CALLBACK_MAP{$k} 0 0 0
995 0 $self->{_callback}->{$k} = $args{$_};
996 }
997 0 return $self;
998 }
999  
1000 =head2 detach_event
1001  
1002 Detach handler(s) from the given event(s). Not implemented.
1003  
1004 =cut
1005  
1006 0 ▶sub detach_event {
Subroutine detach_event: not called CC=1 SCAR=6.9
Pod documented
1007 0 my $self = shift;
1008 0 warn "detach_event not implemented, see ->add_handler_for_event in Mixin::Event::Dispatch";
1009 0 return $self;
1010 }
1011  
1012 =head2 debug
1013  
1014 Helper method to report debug information. Can take a string or a coderef.
1015  
1016 =cut
1017  
1018 81 ▶sub debug {
Subroutine debug: called CC=6 SCAR=33.9
Pod documented
1019 81 my $self = shift;
1020 81 ▶ return unless $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"debug"} 81 0 81
1021  
1022 0 my $msg = shift(@_);
1023 0 ▶ $msg = $msg->() if ref $msg && ref $msg eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $msg and ref $msg eq "CODE" 0 0 0
Condition0%0/3
ref $msg and ref $msg eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $msg and ref $msg eq "CODE"
ref $msg ref $msg eq "CODE"
Truth table0%0/3
A and B
A= ref $msgB= ref $msg eq "CODE"
ABresult
0X0
100
111
1024 0 ▶ if(!ref $self->{debug}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $self->{"debug"}) 0 0 0
1025 0 my $now = Time::HiRes::time;
1026 0 warn strftime("%Y-%m-%d %H:%M:%S", gmtime($now)) . sprintf(".%03d", int($now * 1000.0) % 1000.0) . " $msg\n";
1027 0 return;
1028 }
1029 0 ▶ if(ref $self->{debug} eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"debug"} eq "CODE") 0 0 0
1030 0 $self->{debug}->($msg, @_);
1031 0 return;
1032 }
1033 0 die "Unknown debug setting " . $self->{debug};
1034 }
1035  
1036 =head2 handle_message
1037  
1038 Handle an incoming message from the server.
1039  
1040 =cut
1041  
1042 18 ▶sub handle_message {
Subroutine handle_message: called CC=2 SCAR=7.0
Pod documented
1043 18 my $self = shift;
1044 18 my $msg = shift;
1045 0 ▶ $self->debug(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1046 0 "recv data: [" . join(" ", map sprintf("%02x", ord($_)), split //, $msg) . "], " . $BACKEND_MESSAGE_CODE{substr($msg, 0, 1)}
1047 18 });
1048  
1049 # Extract code and identify which message handler to use
1050 18 my $code = substr $msg, 0, 1;
1051 18 my $type = $BACKEND_MESSAGE_CODE{$code};
1052 18 $self->debug("Handle [$type] message");
1053 18 ▶ die "No handler for $type" unless exists $BACKEND_MESSAGE_HANDLER{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $Protocol::PostgreSQL::BACKEND_MESSAGE_HANDLER{$type} 0 18 18
1054  
1055 # Clear the ready-to-send flag until we've processed this
1056 18 $self->{is_ready} = 0;
1057 18 return $BACKEND_MESSAGE_HANDLER{$type}->($self, $msg);
1058 }
1059  
1060 =head2 message_length
1061  
1062 Returns the length of the given message.
1063  
1064 =cut
1065  
1066 17 ▶sub message_length {
Subroutine message_length: called CC=2 SCAR=7.0
Pod documented
1067 17 my $self = shift;
1068 17 my $msg = shift;
1069 17 ▶ return undef unless length($msg) >= 5;
Branch: 1 branch
BranchTrueFalseTotal
unless length $msg >= 5 0 17 17
1070 17 my ($code, $len) = unpack('C1N1', substr($msg, 0, 5));
1071 17 return $len;
1072 }
1073  
1074 =head2 simple_query
1075  
1076 Send a simple query to the server - only supports plain queries (no bind parameters).
1077  
1078 =cut
1079  
1080 4 ▶sub simple_query {
Subroutine simple_query: called CC=2 SCAR=7.0
Pod documented
1081 4 my $self = shift;
1082 4 my $sql = shift;
1083 4 ▶ die "Invalid backend state" if $self->backend_state eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $self->backend_state eq "error" 0 4 4
1084  
1085 4 $self->debug("Running query [$sql]");
1086 4 $self->queue(
1087 message => $self->message('Query', sql => $sql)
1088 );
1089 4 return $self;
1090 }
1091  
1092 =head2 copy_data
1093  
1094 Send copy data to the server.
1095  
1096 =cut
1097  
1098 0 ▶sub copy_data {
Subroutine copy_data: not called CC=2 SCAR=17.9
Pod documented
1099 0 my $self = shift;
1100 0 my $data = shift;
1101 0 ▶ die "Invalid backend state" if $self->backend_state eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $self->backend_state eq "error" 0 0 0
1102  
1103 0 $self->send_message('CopyData', data => $data);
1104 0 return $self;
1105 }
1106  
1107 =head2 copy_done
1108  
1109 Indicate that the COPY data from the client is complete.
1110  
1111 =cut
1112  
1113 0 ▶sub copy_done {
Subroutine copy_done: not called CC=2 SCAR=17.9
Pod documented
1114 0 my $self = shift;
1115 0 my $data = shift;
1116 0 ▶ die "Invalid backend state" if $self->backend_state eq 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $self->backend_state eq "error" 0 0 0
1117  
1118 0 $self->send_message('CopyDone');
1119 0 return $self;
1120 }
1121  
1122 =head2 backend_state
1123  
1124 Accessor for current backend state.
1125  
1126 =cut
1127  
1128 10 ▶sub backend_state {
Subroutine backend_state: called CC=3 SCAR=11.0
Pod documented
1129 10 my $self = shift;
1130 10 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 5 5 10
1131 5 my $state = shift;
1132 5 ▶ die "bad state code" unless grep { $state eq $_ } qw(idle transaction error);
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$state eq $_;} "idle", "transaction", "error" 0 5 5
1133  
1134 5 $self->{backend_state} = $state;
1135 5 return $self;
1136 }
1137 5 return $self->{backend_state};
1138 }
1139  
1140 =head2 active_statement
1141  
1142 Returns the currently active L<Protocol::PostgreSQL::Statement> if we have one.
1143  
1144 =cut
1145  
1146 2 ▶sub active_statement {
Subroutine active_statement: called CC=2 SCAR=8.4
Pod documented
1147 2 my $self = shift;
1148 2 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 0 2 2
1149 0 $self->{active_statement} = shift;
1150 0 return $self;
1151 }
1152 2 return $self->{active_statement};
1153 }
1154  
1155 =head2 row_description
1156  
1157 Accessor for row description.
1158  
1159 =cut
1160  
1161 4 ▶sub row_description {
Subroutine row_description: called CC=2 SCAR=6.9
Pod documented
1162 4 my $self = shift;
1163 4 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 2 2 4
1164 2 $self->{row_description} = shift;
1165 2 return $self;
1166 }
1167 2 return $self->{row_description};
1168 }
1169  
1170 =head2 prepare
1171  
1172 Prepare a L<Protocol::PostgreSQL::Statement>. Intended to be mostly compatible with the L<DBI>
1173 ->prepare method.
1174  
1175 =cut
1176  
1177 1 ▶sub prepare {
Subroutine prepare: called CC=1 SCAR=0.0
Pod documented
1178 1 my $self = shift;
1179 1 my $sql = shift;
1180 1 return $self->prepare_async(sql => $sql);
1181 }
1182  
1183 =head2 prepare_async
1184  
1185 Set up a L<Protocol::PostgreSQL::Statement> allowing callbacks and other options to be provided.
1186  
1187 =cut
1188  
1189 1 ▶sub prepare_async {
Subroutine prepare_async: called CC=2 SCAR=7.0
Pod documented
1190 1 my $self = shift;
1191 1 my %args = @_;
1192 1 ▶ die "SQL statement not provided" unless defined $args{sql};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"sql"} 0 1 1
1193  
1194 1 my $sth = Protocol::PostgreSQL::Statement->new(
1195 dbh => $self,
1196 %args,
1197 );
1198 1 return $sth;
1199 }
1200  
1201 =head2 is_ready
1202  
1203 Returns true if we're ready to send more data to the server.
1204  
1205 =cut
1206  
1207 10 ▶sub is_ready {
Subroutine is_ready: called CC=3 SCAR=11.0
Pod documented
1208 10 my $self = shift;
1209 10 ▶ if(@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 5 5 10
1210 5 $self->{is_ready} = shift;
1211 5 return $self;
1212 }
1213 5 ▶ return 0 if $self->{wait_for_startup};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"wait_for_startup"} 0 5 5
1214 5 return $self->{is_ready};
1215 }
1216  
1217 =head2 send_copy_data
1218  
1219 Send COPY data to the server. Takes an arrayref and replaces any reserved characters with quoted versions.
1220  
1221 =cut
1222  
1223 100 ▶sub send_copy_data {
Subroutine send_copy_data: called CC=8 SCAR=37.7
Pod documented
1224 100 my $self = shift;
1225 100 my $data = shift;
1226 my $content = pack 'a*', (join("\t", map {
1227 0 ▶ if(defined) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $_) { } 0 0 0
1228 0 ▶ s/\\/\\\\/g if index($_, "\\") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\\") != -1 0 0 0
1229 0 ▶ s/\x08/\\b/g if index($_, "\x08") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\b") != -1 0 0 0
1230 0 ▶ s/\f/\\f/g if index($_, "\f") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\f") != -1 0 0 0
1231 0 ▶ s/\n/\\n/g if index($_, "\n") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\n") != -1 0 0 0
1232 0 ▶ s/\t/\\t/g if index($_, "\t") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\t") != -1 0 0 0
1233 0 ▶ s/\v/\\v/g if index($_, "\r") >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if index($_, "\r") != -1 0 0 0
1234 } else {
1235 0 $_ = '\N';
1236 }
1237 0 $_;
1238 } @$data) . "\n");
1239
1240 100 $self->invoke_event('send_request', $MESSAGE_TYPE_FRONTEND{'CopyData'} . pack('N1', 4 + length $content) . $content);
1241 100 return $self;
1242 }
1243  
1244 =head2 _build_message
1245  
1246 Construct a new message.
1247  
1248 =cut
1249  
1250 13 ▶sub _build_message {
Subroutine _build_message: called CC=4 SCAR=13.9
1251 13 my $self = shift;
1252 13 my %args = @_;
1253  
1254 # Can be undef
1255 13 ▶ die "No type provided" unless exists $args{type};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"type"} 1 12 13
1256 12 ▶ die "No data provided" unless exists $args{data};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $args{"data"} 1 11 12
1257  
1258 # Length includes the 4-byte length field, but not the type byte
1259 11 my $length = length($args{data}) + 4;
1260 11 ▶ my $msg = ($self->is_first_message ? '' : $MESSAGE_TYPE_FRONTEND{$args{type}}) . pack('N1', $length) . $args{data};
Branch: 1 branch
BranchTrueFalseTotal
$self->is_first_message ? : 3 8 11
1261 11 return $msg;
1262 }
1263  
1264 5 1;
1265  
1266 __END__
↑ Summary PostgreSQL/Statement.pm »