Pg/Connection.pm

filter: Statementstmt 88.8% 16 / 18 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod n/a totaltotal 91.6% 22 / 24 CC 1 SCAR 0.5
CC
1
Cov
89%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Pg.pm ↑ Summary
1 package IO::Async::Pg::Connection;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use IO::Async::Handle;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 0 ▶use DBD::Pg qw(:async);
Subroutine BEGIN: called CC=1 SCAR=2.6
10  
11 use IO::Async::Pg::Cursor;
12 use IO::Async::Pg::Error;
13 use IO::Async::Pg::Results;
14 use IO::Async::Pg::Util qw(convert_placeholders);
15  
16 sub _init {
17 my ($self, $params) = @_;
18 $self->{dbh} = delete $params->{dbh};
19 $self->{pool} = delete $params->{pool};
20 $self->{created_at} = delete $params->{created_at} // time();
21 $self->{query_count} = delete $params->{query_count} // 0;
22 $self->{last_used} = time();
23 $self->{released} = 0;
24 $self->{in_transaction} = 0;
25 $self->SUPER::_init($params);
26 }
27  
28 # Accessors
29 sub dbh { shift->{dbh} }
30 sub pool { shift->{pool} }
31 sub last_used { shift->{last_used} }
32 sub query_count { shift->{query_count} }
33 sub created_at { shift->{created_at} }
34 sub in_transaction { shift->{in_transaction} }
35 sub is_released { shift->{released} }
36  
37 # Execute a query asynchronously
38 async sub query {
39 my ($self, $sql, @args) = @_;
40  
41 # Parse arguments: can be positional values, hashref for named, or options
42 my ($bind, $opts) = $self->_parse_query_args(@args);
43  
44 # Convert named placeholders if hashref provided
45 if (ref $bind eq 'HASH') {
46 ($sql, $bind) = convert_placeholders($sql, $bind);
47 }
48  
49 $self->{query_count}++;
50 $self->{last_used} = time();
51  
52 # Execute with optional timeout
53 my $result;
54 if (my $timeout = $opts->{timeout}) {
55 $result = await $self->_query_with_timeout($sql, $bind, $timeout);
56 }
57 else {
58 $result = await $self->_execute_async($sql, $bind);
59 }
60  
61 return $result;
62 }
63  
64 # Parse query arguments into bind values and options
65 sub _parse_query_args {
66 my ($self, @args) = @_;
67  
68 my $opts = {};
69 my $bind = [];
70  
71 # Check if last arg is options hash
72 if (@args && ref $args[-1] eq 'HASH') {
73 my $last = $args[-1];
74 # Distinguish between named placeholders and options
75 if (exists $last->{timeout}) {
76 $opts = pop @args;
77 }
78 }
79  
80 # Remaining args are bind values
81 if (@args == 1 && ref $args[0] eq 'HASH') {
82 $bind = $args[0]; # Named placeholders
83 }
84 elsif (@args) {
85 $bind = \@args; # Positional placeholders
86 }
87  
88 return ($bind, $opts);
89 }
90  
91 # Execute async query with timeout
92 async sub _query_with_timeout {
93 my ($self, $sql, $bind, $timeout) = @_;
94  
95 my $query_future = $self->_execute_async($sql, $bind);
96 my $timer = $self->loop->delay_future(after => $timeout);
97  
98 my $winner = await Future->wait_any($query_future, $timer);
99  
100 if ($winner == $timer) {
101 # Timer won - cancel the query
102 $self->cancel;
103  
104 # Wait for query to finish with error
105 eval { await $query_future };
106  
107 die IO::Async::Pg::Error::Timeout->new(
108 message => "Query timeout after ${timeout}s",
109 timeout => $timeout,
110 );
111 }
112  
113 return $winner->get;
114 }
115  
116 # Core async query execution using DBD::Pg async support
117 async sub _execute_async {
118 my ($self, $sql, $bind) = @_;
119 $bind //= [];
120  
121 my $dbh = $self->{dbh};
122  
123 # Prepare statement
124 my $sth = eval { $dbh->prepare($sql, { pg_async => PG_ASYNC }) };
125 if ($@ || !$sth) {
126 $self->_throw_query_error($@ || $dbh->errstr, $sql);
127 }
128  
129 # Execute with bind values
130 my $rv = eval {
131 if (ref $bind eq 'ARRAY' && @$bind) {
132 $sth->execute(@$bind);
133 }
134 else {
135 $sth->execute;
136 }
137 };
138  
139 if ($@ || !defined $rv) {
140 $self->_throw_query_error($@ || $sth->errstr || $dbh->errstr, $sql);
141 }
142  
143 # Wait for async result
144 await $self->_wait_for_result($dbh);
145  
146 # Get result
147 my $result = eval { $dbh->pg_result };
148 if ($@ || !$result) {
149 $self->_throw_query_error($@ || $dbh->errstr, $sql);
150 }
151  
152 return IO::Async::Pg::Results->new($sth);
153 }
154  
155 # Wait for PostgreSQL socket to be readable
156 async sub _wait_for_result {
157 my ($self, $dbh) = @_;
158  
159 my $socket_fd = $dbh->{pg_socket};
160 die "No PostgreSQL socket" unless defined $socket_fd;
161  
162 my $future = $self->loop->new_future;
163  
164 # Create handle to watch the socket
165 my $handle;
166 $handle = IO::Async::Handle->new(
167 read_fileno => $socket_fd,
168 want_readready => 1,
169 on_read_ready => sub {
170 # Check if result is ready
171 if ($dbh->pg_ready) {
172 $self->loop->remove($handle);
173 $future->done;
174 }
175 # else keep waiting
176 },
177 );
178  
179 $self->loop->add($handle);
180  
181 # Ensure cleanup on cancellation
182 $future->on_cancel(sub {
183 $self->loop->remove($handle) if $handle->loop;
184 });
185  
186 await $future;
187 }
188  
189 # Cancel current query
190 sub cancel {
191 my ($self) = @_;
192 eval { $self->{dbh}->pg_cancel };
193 }
194  
195 # Execute code within a transaction
196 async sub transaction {
197 my ($self, $code, %opts) = @_;
198  
199 my $isolation = $opts{isolation};
200 my $savepoint_depth = $self->{_savepoint_depth} // 0;
201  
202 if ($savepoint_depth > 0) {
203 # Nested transaction - use savepoint
204 my $savepoint = "sp_$savepoint_depth";
205 await $self->query("SAVEPOINT $savepoint");
206  
207 $self->{_savepoint_depth} = $savepoint_depth + 1;
208  
209 my $result = eval { await $code->($self) };
210 my $err = $@;
211  
212 $self->{_savepoint_depth} = $savepoint_depth;
213  
214 if ($err) {
215 await $self->query("ROLLBACK TO SAVEPOINT $savepoint");
216 die $err;
217 }
218  
219 await $self->query("RELEASE SAVEPOINT $savepoint");
220 return $result;
221 }
222 else {
223 # Top-level transaction
224 my $begin = 'BEGIN';
225 if ($isolation) {
226 my $level = uc($isolation);
227 $level =~ s/_/ /g; # read_committed -> READ COMMITTED
228 $begin .= " ISOLATION LEVEL $level";
229 }
230 await $self->query($begin);
231 $self->{in_transaction} = 1;
232  
233 $self->{_savepoint_depth} = 1;
234  
235 my $result = eval { await $code->($self) };
236 my $err = $@;
237  
238 $self->{_savepoint_depth} = 0;
239  
240 if ($err) {
241 eval { await $self->query('ROLLBACK') };
242 $self->{in_transaction} = 0;
243 die $err;
244 }
245  
246 await $self->query('COMMIT');
247 $self->{in_transaction} = 0;
248 return $result;
249 }
250 }
251  
252 # Create a streaming cursor for large result sets
253 async sub cursor {
254 my ($self, $sql, @args) = @_;
255  
256 # Parse arguments: can be positional values, hashref for named, or options
257 my ($bind, $opts) = $self->_parse_cursor_args(@args);
258  
259 # Convert named placeholders if hashref provided
260 if (ref $bind eq 'HASH') {
261 ($sql, $bind) = convert_placeholders($sql, $bind);
262 }
263  
264 my $batch_size = delete $opts->{batch_size} // 1000;
265 my $cursor_name = delete $opts->{name} // IO::Async::Pg::Cursor::_generate_name();
266  
267 # Must be in a transaction for cursors
268 my $was_in_transaction = $self->{in_transaction};
269 if (!$was_in_transaction) {
270 await $self->query('BEGIN');
271 $self->{in_transaction} = 1;
272 }
273  
274 # Build DECLARE CURSOR statement
275 my $declare_sql = "DECLARE $cursor_name CURSOR FOR $sql";
276  
277 # Execute the DECLARE
278 if (ref $bind eq 'ARRAY' && @$bind) {
279 await $self->query($declare_sql, @$bind);
280 }
281 else {
282 await $self->query($declare_sql);
283 }
284  
285 my $cursor = IO::Async::Pg::Cursor->new(
286 name => $cursor_name,
287 batch_size => $batch_size,
288 conn => $self,
289 _owns_transaction => !$was_in_transaction,
290 );
291  
292 return $cursor;
293 }
294  
295 # Parse cursor arguments into bind values and options
296 sub _parse_cursor_args {
297 my ($self, @args) = @_;
298  
299 my $opts = {};
300 my $bind = [];
301  
302 # Check if last arg is options hash (contains cursor-specific keys)
303 if (@args && ref $args[-1] eq 'HASH') {
304 my $last = $args[-1];
305 # Distinguish between named placeholders and options
306 if (exists $last->{batch_size} || exists $last->{name}) {
307 $opts = pop @args;
308 }
309 }
310  
311 # Remaining args are bind values
312 if (@args == 1 && ref $args[0] eq 'HASH') {
313 $bind = $args[0]; # Named placeholders
314 }
315 elsif (@args) {
316 $bind = \@args; # Positional placeholders
317 }
318  
319 return ($bind, $opts);
320 }
321  
322 # Release connection back to pool
323 sub release {
324 my ($self) = @_;
325 return if $self->{released};
326 $self->{released} = 1;
327  
328 if (my $pool = $self->{pool}) {
329 $pool->_return_connection($self);
330 }
331 }
332  
333 # Close the underlying database handle
334 sub _close_dbh {
335 my ($self) = @_;
336 if ($self->{dbh}) {
337 eval { $self->{dbh}->disconnect };
338 $self->{dbh} = undef;
339 }
340 }
341  
342 # Auto-release on destruction
343 sub DESTROY {
344 my ($self) = @_;
345  
346 # During global destruction, don't try to release to pool
347 return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
348  
349 $self->release unless $self->{released};
350 $self->_close_dbh;
351 }
352  
353 # Throw a query error with PostgreSQL details
354 sub _throw_query_error {
355 my ($self, $err, $sql) = @_;
356  
357 my $dbh = $self->{dbh};
358 my $state = eval { $dbh->state } // '';
359  
360 die IO::Async::Pg::Error::Query->new(
361 message => $err,
362 code => $state,
363 detail => eval { $dbh->pg_errorlevel } // undef,
364 constraint => undef, # Would need to parse from error
365 hint => undef,
366 position => undef,
367 );
368 }
369  
370 1;
371  
372 __END__
« Pg.pm ↑ Summary