PostgreSQL/Storage/Async.pm

filter: Statementstmt 100% 9 / 9 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 3 / 3 Podpod n/a totaltotal 100% 12 / 12 CC 1 SCAR 0.0
CC
1
Cov
100%
BEGIN
1.0
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« PostgreSQL/JSONB.pm ↑ Summary PostgreSQL/Test/EventTZPg.pm »
1 package DBIO::PostgreSQL::Storage::Async;
2 # ABSTRACT: future_io async PostgreSQL transport over DBD::Pg's pg_async binding
3  
4 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use base 'DBIO::Async::Storage';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 use Carp 'croak';
9 use DBI;
10 use DBD::Pg qw(:async);
11 use Future::IO;
12 use DBIO::PostgreSQL::SQLMaker;
13 use namespace::clean;
14  
15  
16 # --- SQL shaping seams ------------------------------------------------------
17  
18  
19 sub sql_maker_class { 'DBIO::PostgreSQL::SQLMaker' }
20  
21  
22 sub _sql_maker_args {
23 return (
24 quote_char => '"',
25 name_sep => '.',
26 limit_dialect => 'LimitOffset',
27 );
28 }
29  
30 # Translate SQL-standard '?' placeholders into PostgreSQL positional '$N'
31 # placeholders, numbering left-to-right so they line up with the maker's @bind.
32 #
33 # The shared DBIO::PostgreSQL::SQLMaker is also used by the SYNC DBI driver,
34 # which needs '?', so the maker MUST keep emitting '?'. The translation
35 # therefore lives here, in the async transport, applied to maker output before
36 # it reaches DBD::Pg. DBD::Pg accepts both '?' and '$N', but we normalise to
37 # '$N' so _submit_query can set pg_placeholder_dollaronly and thereby leave the
38 # JSONB '@?' operator's literal '?' untouched.
39 #
40 # Subtleties this must respect (all verified against the maker's output):
41 # * '@?' is the JSONB jsonpath operator, not a placeholder. A '?' that is
42 # immediately preceded by '@' is part of an operator and is left alone.
43 # Its actual RHS placeholder ('@? ?::jsonpath') is a separate '?' and
44 # does get translated.
45 # * '?::jsonb' / '?::jsonpath' casts are real placeholders -> '$N::jsonb'.
46 # * 'ARRAY[?, ?]' (jsonb_exists_any/all) has one placeholder per '?'.
47 # * A '?' inside a single-quoted string literal ('...', with '' escaping)
48 # or a double-quoted identifier ("...", with "" escaping) is data/name,
49 # not a placeholder, and is skipped. This is defensive against inlined
50 # literals that happen to contain '?'.
51  
52  
53 sub _transform_sql {
54 my ($self, $sql) = @_;
55  
56 my $out = '';
57 my $n = 0;
58 my $len = length $sql;
59 my $i = 0;
60  
61 while ($i < $len) {
62 my $c = substr($sql, $i, 1);
63  
64 if ($c eq "'" || $c eq '"') {
65 # Copy a quoted run verbatim, honouring doubled-quote escaping.
66 my $quote = $c;
67 $out .= $c;
68 $i++;
69 while ($i < $len) {
70 my $d = substr($sql, $i, 1);
71 $out .= $d;
72 $i++;
73 if ($d eq $quote) {
74 if ($i < $len && substr($sql, $i, 1) eq $quote) {
75 $out .= $quote; # doubled quote -> escaped, stay inside
76 $i++;
77 } else {
78 last; # end of quoted run
79 }
80 }
81 }
82 next;
83 }
84  
85 if ($c eq '?') {
86 # '@?' operator: the '?' belongs to the operator, not a placeholder.
87 if ($i > 0 && substr($sql, $i - 1, 1) eq '@') {
88 $out .= $c;
89 $i++;
90 next;
91 }
92 $out .= '$' . (++$n);
93 $i++;
94 next;
95 }
96  
97 $out .= $c;
98 $i++;
99 }
100  
101 return $out;
102 }
103  
104  
105 sub _post_insert_sql { ' RETURNING *' }
106  
107 # --- Connect-info seam ------------------------------------------------------
108  
109  
110 sub _normalize_conninfo {
111 my ($self, $info) = @_;
112  
113 # DBI-form: [ 'dbi:Pg:...', $user, $pass, \%attrs ] -> our conninfo shape.
114 if (ref $info eq 'ARRAY'
115 && defined $info->[0] && !ref $info->[0] && $info->[0] =~ /^dbi:/i) {
116 my ($dsn, $user, $pass, $attrs) = @$info;
117 $attrs = {} unless ref $attrs eq 'HASH';
118 my %conninfo = (
119 dsn => $dsn,
120 user => $user,
121 password => $pass,
122 attrs => { %$attrs },
123 );
124 $conninfo{pool_size} = delete $conninfo{attrs}{pool_size}
125 if defined $conninfo{attrs}{pool_size};
126 return [ \%conninfo, {} ];
127 }
128  
129 # Broker arrayref [ $broker ], or an already-normalised [ \%conninfo, \%opts ]
130 # pair -- leave for the inherited broker detection / normalisation.
131 return $info;
132 }
133  
134 # --- Pool connection lifecycle ----------------------------------------------
135  
136  
137 sub _create_pool_connection {
138 my ($self, $conninfo) = @_;
139  
140 croak 'PostgreSQL async conninfo must be a hashref with a dsn'
141 unless ref $conninfo eq 'HASH' && defined $conninfo->{dsn};
142  
143 my $dbh = DBI->connect(
144 $conninfo->{dsn},
145 $conninfo->{user},
146 $conninfo->{password},
147 {
148 %{ $conninfo->{attrs} || {} },
149 AutoCommit => 1,
150 RaiseError => 1,
151 PrintError => 0,
152 },
153 ) or croak "DBD::Pg connect failed: $DBI::errstr";
154  
155 return { dbh => $dbh };
156 }
157  
158  
159 sub _shutdown_pool_connection {
160 my ($self, $conn) = @_;
161 my $dbh = $conn->{dbh} or return;
162 $dbh->disconnect if $dbh->{Active};
163 }
164  
165 # --- Readiness / socket seams -----------------------------------------------
166  
167  
168 sub _conn_ready {
169 my ($self, $conn) = @_;
170 return $conn->{dbh} && $conn->{dbh}{Active} ? 1 : 0;
171 }
172  
173  
174 sub _conn_fileno {
175 my ($self, $conn) = @_;
176 return $conn->{dbh}{pg_socket};
177 }
178  
179 # --- Query submit / collect -------------------------------------------------
180  
181  
182 sub _submit_query {
183 my ($self, $conn, $sql, $bind) = @_;
184 $bind //= [];
185  
186 my $dbh = $conn->{dbh};
187  
188 # Release the previous (already-collected) async statement handle BEFORE
189 # starting a new async query. DBD::Pg tracks async state on the DATABASE
190 # handle; destroying a spent async sth *after* the new execute clobbers the
191 # new query's async status back to 0, so the next _collect_result sees
192 # "pg_ready: No asynchronous query is running" on the second query over a
193 # reused pooled connection. Clearing it here means the new execute owns the
194 # dbh async slot uncontested.
195 delete $conn->{sth};
196  
197 my $sth = $dbh->prepare($sql, {
198 pg_async => PG_ASYNC,
199 pg_placeholder_dollaronly => 1,
200 });
201 $sth->execute(@$bind);
202 $conn->{sth} = $sth;
203  
204 return;
205 }
206  
207  
208 sub _collect_result {
209 my ($self, $conn, $sql, $bind) = @_;
210  
211 my $dbh = $conn->{dbh};
212  
213 # The result may not have fully arrived on the first readable event. pg_ready
214 # consumes what is on the wire and reports whether the result is complete;
215 # if not, wait for more and re-check rather than blocking in pg_result.
216 unless ($dbh->pg_ready) {
217 return $self->_await_readable($conn)->then(sub {
218 return $self->_collect_result($conn, $sql, $bind);
219 });
220 }
221  
222 my $sth = $conn->{sth};
223 my $rv = $dbh->pg_result; # finalise; dies (RaiseError) on a query error
224  
225 if (($sth->{NUM_OF_FIELDS} || 0) > 0) {
226 my $rows = $sth->fetchall_arrayref;
227 return $self->future_class->done(@$rows);
228 }
229  
230 return $self->future_class->done($rv);
231 }
232  
233 # --- Transaction context seams ----------------------------------------------
234  
235  
236 sub _txn_context_class { 'DBIO::Async::TransactionContext' }
237  
238  
239 sub _txn_conn_accessor { 'txn_conn' }
240  
241 1;
242  
243 __END__
244  
245 =pod
246  
247 =encoding UTF-8
248  
249 =head1 NAME
250  
251 DBIO::PostgreSQL::Storage::Async - future_io async PostgreSQL transport over DBD::Pg's pg_async binding
252  
253 =head1 VERSION
254  
255 version 0.900001
256  
257 =head1 DESCRIPTION
258  
259 The concrete C<future_io> transport adapter for PostgreSQL (core ADR 0030 /
260 0031). It is resolved B<by convention> off the sync driver storage: a
261 connection opened with
262  
263 MyApp::Schema->connect($dsn, $user, $pass, { async => 'future_io' });
264  
265 on a L<DBIO::PostgreSQL::Storage> instance derives C<ref($storage) . '::Async'>
266 == C<DBIO::PostgreSQL::Storage::Async>. No C<register_async_mode> call is
267 needed; the name itself is the registration.
268  
269 =head2 Storage extensions ride on top by composition
270  
271 Under the storage-layer composition model (core karr #70), a PostgreSQL
272 extension (AGE, PostGIS, ...) is B<not> a C<storage_type> subclass and does
273 B<not> ship a shadow C<register_async_mode> / C<< ::Storage::Async >> of its
274 own. It ships a plain storage B<layer> registered with
275 C<< $schema->register_storage_layer('DBIO::PostgreSQL::Ext::Storage') >> and,
276 for async behaviour, a sibling async mirror
277 C<DBIO::PostgreSQL::Ext::Storage::Async> (a plain method package, B<not> a
278 transport). When a layered schema connects C<< { async => 'future_io' } >>,
279 core resolves this transport by convention off the B<composition base> (the
280 driver, not the layers -- see L<DBIO::Storage::DBI/_async_resolution_class>) and
281 then C<< DBIO::Storage::Composed->compose >>s each registered layer's async
282 mirror B<on top of> it. So this class stays the single per-driver future_io
283 transport BASE; extensions add behaviour above it via C3, exactly as their sync
284 layers ride the sync driver storage.
285  
286 The Model-B orchestration -- the CRUD runner (L<DBIO::Storage::Async/_run_crud>
287 with its pooled / pinned runners), INSERT returned-columns mapping,
288 L<DBIO::Storage::Async/txn_do_async> bracketing, the pipeline scaffold, and the
289 sync C<< ->get >> fallbacks -- is inherited unchanged from
290 L<DBIO::Storage::Async>. The L<Future::IO> transport (query execution over the
291 socket-readable watcher, the L<Future> class and the L<DBIO::Async::Pool>) is
292 inherited from L<DBIO::Async::Storage>. This class fills B<only> the
293 DB-specific transport seams over L<DBD::Pg>'s own asynchronous binding
294 (C<< {pg_async => PG_ASYNC} >> + C<pg_ready> / C<pg_result> / C<pg_socket>):
295  
296 =over 4
297  
298 =item * L</sql_maker_class> / L</_sql_maker_args> -- the PostgreSQL SQLMaker
299  
300 =item * L</_transform_sql> -- C<?> to positional C<$N> placeholders
301  
302 =item * L</_post_insert_sql> -- C< RETURNING *> for the returned-columns hashref
303  
304 =item * L</_normalize_conninfo> -- DBI-form connect info into the pool's shape
305  
306 =item * L</_create_pool_connection> / L</_shutdown_pool_connection> -- DBD::Pg
307 handle lifecycle
308  
309 =item * L</_conn_ready> / L</_conn_fileno> -- readiness + the C<pg_socket> fd
310 for the L<Future::IO> watcher
311  
312 =item * L</_submit_query> / L</_collect_result> -- send non-blocking, then
313 gather once the wire is readable
314  
315 =item * L</_txn_context_class> / L</_txn_conn_accessor> -- the pinned-connection
316 transaction context
317  
318 =back
319  
320 A connection is represented as a small hashref C<< { dbh => $dbh, sth => $sth } >>:
321 the DBD::Pg database handle plus the statement handle of the in-flight async
322 query (there is at most one per connection at a time, guaranteed by the pool /
323 transaction pinning).
324  
325 =head2 Transport capabilities
326  
327 This transport inherits C<transport_capabilities> from
328 L<DBIO::Async::Storage>, which advertises exactly C<on_connect_replay> (the
329 pool replays the owning sync storage's C<on_connect_do> / C<on_connect_call>
330 on every freshly-spawned connection). It declares B<nothing extra>: the
331 advanced PostgreSQL wire features are B<not> implemented on the C<future_io>
332 transport.
333  
334 C<LISTEN>/C<NOTIFY> (L<DBIO::Storage::Async/listen>),
335 C<COPY>, and pipelining (L<DBIO::Storage::Async/pipeline>) are B<not> supported
336 here -- DBD::Pg's async binding exposes no libpq pipeline mode, and the base
337 seams croak if called. The native C<ev> backend
338 (L<DBIO::PostgreSQL::EV::Storage>, dist C<dbio-postgresql-ev>) is the transport
339 that carries C<LISTEN>/C<NOTIFY>, C<COPY> and pipelining. An async storage
340 layer that declares C<required_transport_capabilities> for any of these will
341 therefore fail loud (core capability gate) when composed over this C<future_io>
342 transport, naming the missing capability -- never a silent feature loss.
343  
344 =head1 METHODS
345  
346 =head2 sql_maker_class
347  
348 The L<DBIO::PostgreSQL::SQLMaker> subclass used to generate SQL.
349  
350 =head2 _sql_maker_args
351  
352 PostgreSQL SQLMaker construction args: double-quote identifier quoting, C<.>
353 name separator, LIMIT/OFFSET dialect. Matches the sync driver and the C<ev>
354 backend.
355  
356 =head2 _transform_sql
357  
358 Rewrite C<?> placeholders to PostgreSQL positional C<$N>, skipping quoted
359 literals / identifiers and the JSONB C<@?> operator.
360  
361 =head2 _post_insert_sql
362  
363 Returns C< RETURNING *> so an INSERT yields every populated column (autoinc PK
364 + retrieve-on-insert defaults); the inherited runner folds the row onto the
365 supplied data to build the returned-columns hashref (ADR 0031 §3).
366  
367 =head2 _normalize_conninfo
368  
369 my $info = $storage->_normalize_conninfo([ 'dbi:Pg:...', $user, $pass, \%attrs ]);
370  
371 Convert the sync storage's DBI-form connect info into the C<[ \%conninfo,
372 \%opts ]> pair the pool consumes, carrying the DSN / user / password / attrs
373 straight through for L</_create_pool_connection> to hand to C<< DBI->connect >>.
374 A C<pool_size> attribute, if present, is lifted into the conninfo hash (the
375 inherited normaliser strips it back out to size the pool). Broker-style or
376 already-normalised info is passed through untouched.
377  
378 =head2 _create_pool_connection
379  
380 my $conn = $storage->_create_pool_connection(\%conninfo);
381  
382 Open one DBD::Pg handle via C<< DBI->connect >> and wrap it as
383 C<< { dbh => $dbh } >>. C<AutoCommit> is on: the inherited orchestration drives
384 transactions with explicit C<BEGIN> / C<COMMIT> / C<ROLLBACK> on the pinned
385 connection, so DBD::Pg's own transaction tracking stays out of the way.
386  
387 =head2 _shutdown_pool_connection
388  
389 Disconnect the DBD::Pg handle held by C<$conn>.
390  
391 =head2 _conn_ready
392  
393 True once the connection can accept queries. C<< DBI->connect >> is a blocking
394 connect, so a handed-out connection is ready immediately -- we only confirm the
395 handle is live.
396  
397 =head2 _conn_fileno
398  
399 The connection socket fd for the L<Future::IO> readable watcher, exposed by
400 DBD::Pg as C<< $dbh->{pg_socket} >>. The transport base
401 (L<DBIO::Async::Storage/_await_readable>) dups this integer fd into a
402 filehandle for C<< Future::IO->poll >>.
403  
404 =head2 _submit_query
405  
406 $storage->_submit_query($conn, $sql, $bind);
407  
408 Send C<$sql> non-blocking via DBD::Pg's async binding: prepare with
409 C<< {pg_async => PG_ASYNC} >> and execute the bind values. C<execute> returns
410 immediately; the result is gathered later by L</_collect_result>. The statement
411 handle is stashed on C<$conn> so the collector can fetch its rows.
412  
413 C<pg_placeholder_dollaronly> is set so DBD::Pg treats only the C<$N>
414 placeholders L</_transform_sql> produced as bind parameters, leaving any
415 literal C<?> (the JSONB C<@?> operator) alone.
416  
417 =head2 _collect_result
418  
419 my $future = $storage->_collect_result($conn, $sql, $bind);
420  
421 Called once the socket is readable. If the async result has not fully arrived
422 (C<< $dbh->pg_ready >> is false) it waits for the socket again and re-checks --
423 so a large result spanning several reads is handled correctly. Once ready it
424 finalises with C<< $dbh->pg_result >> and resolves:
425  
426 =over 4
427  
428 =item * a query that produced a result set (SELECT, or INSERT/UPDATE/DELETE
429 C<... RETURNING>) -> the list of raw row arrayrefs, exactly the shape the sync
430 cursor's C<< ->all >> yields (ADR 0031 §3);
431  
432 =item * a statement with no result set (plain UPDATE/DELETE, BEGIN/COMMIT/...)
433 -> the affected-row count from C<pg_result>.
434  
435 =back
436  
437 The full list is carried in an explicit C<< future_class->done(@rows) >> so it
438 survives the surrounding C<< ->then >> chain (a bare list return would collapse
439 to its last element).
440  
441 =head2 _txn_context_class
442  
443 The pinned-connection transaction context handed to a C<txn_do_async> coderef:
444 the C<future_io> L<DBIO::Async::TransactionContext>.
445  
446 =head2 _txn_conn_accessor
447  
448 The constructor key the pinned connection is passed under -- C<txn_conn>,
449 matching L<DBIO::Storage::Async::TransactionContext>.
450  
451 =head1 AUTHOR
452  
453 DBIO & DBIx::Class Authors
454  
455 =head1 COPYRIGHT AND LICENSE
456  
457 Copyright (C) 2026 DBIO Authors
458 Portions Copyright (C) 2005-2025 DBIx::Class Authors
459 Based on DBIx::Class, heavily modified.
460  
461 This is free software; you can redistribute it and/or modify it under
462 the same terms as the Perl 5 programming language system itself.
463  
464 =cut
« PostgreSQL/JSONB.pm ↑ Summary PostgreSQL/Test/EventTZPg.pm »