EV/Storage.pm

filter: Statementstmt 65.2% 195 / 299 Branchbran 45.2% 48 / 106 Conditioncond 48.9% 23 / 47 MC/DCmcdc 25.0% 7 / 28 Subroutinesub 68.9% 40 / 58 Podpod 100% 12 / 12 totaltotal 59.0% 325 / 550 CC 72 SCAR 28.2
CC
72
Cov
59%
__ANON__
132.0
_drop_statements_for
30.0
deploy_async
12.0
CRAP 16.8
« EV/TestHarness.pm ↑ Summary EV/Pool.pm »
1 package DBIO::PostgreSQL::EV::Storage;
2 # ABSTRACT: Async PostgreSQL storage driver using EV::Pg
3  
4 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use base 'DBIO::Storage::Async';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 10 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use DBIO::PostgreSQL::SQLMaker;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use DBIO::PostgreSQL::EV::ConnectInfo 'conninfo_string';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use DBIO::PostgreSQL::EV::Pool;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use DBIO::PostgreSQL::EV::TransactionContext;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use DBIO::SQL::Util qw(_split_statements _quote_ident);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17  
18 # --- SQLMaker seams -----------------------------------------------------------
19 # The inherited DBIO::Storage::Async::sql_maker builds the maker from these.
20  
21  
22 8 ▶sub sql_maker_class { 'DBIO::PostgreSQL::SQLMaker' }
Subroutine sql_maker_class: called CC=1 SCAR=0.0
Pod documented
23  
24  
25 7 ▶sub _sql_maker_args {
Subroutine _sql_maker_args: called CC=1 SCAR=0.0
26 return (
27 7 quote_char => '"',
28 name_sep => '.',
29 limit_dialect => 'LimitOffset',
30 );
31 }
32  
33  
34 5 ▶sub _post_insert_sql { ' RETURNING *' }
Subroutine _post_insert_sql: called CC=1 SCAR=0.0
35  
36  
37 2 ▶sub future_class { 'Future' }
Subroutine future_class: called CC=1 SCAR=0.0
Pod documented
38  
39  
40 1 ▶sub transport_capabilities { qw(on_connect_replay listen notify copy pipeline) }
Subroutine transport_capabilities: called CC=1 SCAR=0.0
Pod documented
41  
42  
43 8 ▶sub connect_info {
Subroutine connect_info: called CC=9 SCAR=24.5
Pod documented
44 8 my ($self, $info) = @_;
45 8 ▶ if ($info) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info) 8 0 8
46 # Embedded path: the sync storage feeds its own DBI-form connect_info
47 # (['dbi:Pg:...', $user, $pass, \%attrs]). Translate it into the async
48 # [ \%conninfo, \%opts ] shape before the normal broker/normalize logic.
49 8 ▶ if (ref $info eq 'ARRAY' && defined $info->[0] && !ref $info->[0] && $info->[0] =~ /^dbi:/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $info eq "ARRAY" and defined $info->[0] and not ref $info->[0] and $info->[0] =~ /^dbi:/i) 0 8 8
Condition33%3/9
ref $info eq "ARRAY" and defined $info->[0] and not ref $info->[0] and $info->[0] =~ /^dbi:/i
!ll&&!rl&&r
800
ref $info eq "ARRAY" and defined $info->[0] and not ref $info->[0]
!ll&&!rl&&r
080
ref $info eq "ARRAY" and defined $info->[0]
!ll&&!rl&&r
008
MC/DC0%0/4
ref $info eq "ARRAY" and defined $info->[0] and not ref $info->[0] and $info->[0] =~ /^dbi:/i
ref $info eq "ARRAY" defined $info->[0] not ref $info->[0] $info->[0] =~ /^dbi:/i
Truth table20%1/5
A and B and not(C) and D
A= ref $info eq "ARRAY"B= defined $info->[0]C= not ref $info->[0]D= $info->[0] =~ /^dbi:/i
ABCDresult
0XXX0
10XX0
110X0
11100
11111
50 0 $info = DBIO::PostgreSQL::EV::ConnectInfo::dbi_to_conninfo($info);
51 }
52 8 ▶ $self->disconnect if $self->{pool} || $self->{_listen_pg};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pool"} or $self->{"_listen_pg"} 0 8 8
Condition33%1/3
$self->{"pool"} or $self->{"_listen_pg"}
l!l&&r!l&&!r
008
MC/DC0%0/2
$self->{"pool"} or $self->{"_listen_pg"}
$self->{"pool"} $self->{"_listen_pg"}
Truth table33%1/3
A or B
A= $self->{"pool"}B= $self->{"_listen_pg"}
ABresult
1X1
011
000
53 8 $self->{connect_info} = $info;
54  
55 8 ▶ if ($self->_is_access_broker_connect_info($info)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_access_broker_connect_info($info)) { } 2 6 8
56 2 $self->_setup_access_broker($info->[0]);
57 2 my ($conninfo, $pool_size, $opts) = $self->_normalize_async_connect_info(
58 $self->_current_async_connect_info($self->access_broker_mode)
59 );
60 2 $self->{_conninfo} = $conninfo;
61 2 $self->{_pool_size} = $pool_size;
62 2 $self->{_opts} = $opts;
63 }
64 else {
65 6 $self->_clear_access_broker;
66 6 my ($conninfo, $pool_size, $opts) = $self->_normalize_async_connect_info($info);
67 6 $self->{_conninfo} = $conninfo;
68 6 $self->{_pool_size} = $pool_size;
69 6 $self->{_opts} = $opts;
70 }
71 }
72 8 return $self->{connect_info};
73 }
74  
75  
76 1 ▶sub _async_broker_conninfo {
Subroutine _async_broker_conninfo: called CC=1 SCAR=0.0
77 1 my ($self, $mode) = @_;
78 1 my ($conninfo) = $self->_normalize_async_connect_info(
79 $self->_current_async_connect_info($mode)
80 );
81 1 return $conninfo;
82 }
83  
84  
85 44 ▶sub pool {
Subroutine pool: called CC=3 SCAR=11.8
Pod documented
86 44 my $self = shift;
87 44 ▶ $self->{pool} ||= do {
Condition66%2/3
$self->{"pool"} ||= do {
l!l&&r!l&&!r
4310
MC/DC0%0/2
$self->{"pool"} ||= do { my(%args) = ("storage", $self, "size", $self->{"_pool_size"}, "on_error", sub { warn "DBIO::PostgreSQL::EV pool error: $_[0]\n"; } ); if (my $provider = $self->_conninfo_provider) { $args{"conninfo_provider"} = $provider; } else { $args{"conninfo"} = $self->_conninfo_string; } ; "DBIO::PostgreSQL::EV::Pool"->new(%args) }
$self->{"pool"} do { my(%args) = ("storage", $self, "size", $self->{"_pool_size"}, "on_error", sub { warn "DBIO::PostgreSQL::EV pool error: $_[0]\n"; } ); if (my $provider = $self->_conninfo_provider) { $args{"conninfo_provider"} = $provider; } else { $args{"conninfo"} = $self->_conninfo_string; } ; "DBIO::PostgreSQL::EV::Pool"->new(%args) }
Truth table66%2/3
A ||= B
A= $self->{"pool"}B= do { my(%args) = ("storage", $self, "size", $self->{"_pool_size"}, "on_error", sub { warn "DBIO::PostgreSQL::EV pool error: $_[0]\n"; } ); if (my $provider = $self->_conninfo_provider) { $args{"conninfo_provider"} = $provider; } else { $args{"conninfo"} = $self->_conninfo_string; } ; "DBIO::PostgreSQL::EV::Pool"->new(%args) }
ABresult
1X1
011
000
88 my %args = (
89 storage => $self,
90 size => $self->{_pool_size},
91 0 ▶ on_error => sub { warn "DBIO::PostgreSQL::EV pool error: $_[0]\n" },
Subroutine __ANON__: not called CC=1 SCAR=6.9
92 1 );
93  
94 1 ▶ if (my $provider = $self->_conninfo_provider) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $provider = $self->_conninfo_provider) { } 0 1 1
95 0 $args{conninfo_provider} = $provider;
96 }
97 else {
98 1 $args{conninfo} = $self->_conninfo_string;
99 }
100  
101 1 DBIO::PostgreSQL::EV::Pool->new(%args);
102 };
103 }
104  
105 3 ▶sub _conninfo_string {
Subroutine _conninfo_string: called CC=2 SCAR=7.1
106 3 my ($self, $ci) = @_;
107 3 ▶ $ci = $self->_current_async_connect_info($self->access_broker_mode)->[0]
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ci 3 0 3
108 if ! defined $ci;
109 3 return conninfo_string($ci);
110 }
111  
112 # --- Transaction context seams ------------------------------------------------
113  
114  
115 1 ▶sub _txn_context_class { 'DBIO::PostgreSQL::EV::TransactionContext' }
Subroutine _txn_context_class: called CC=1 SCAR=0.0
116  
117  
118 1 ▶sub _txn_conn_accessor { 'pg' }
Subroutine _txn_conn_accessor: called CC=1 SCAR=0.0
119  
120 # --- SQL shaping seam ---------------------------------------------------------
121  
122 # Translate SQL-standard '?' placeholders into PostgreSQL positional '$N'
123 # placeholders, numbering left-to-right so they line up with the maker's
124 # @bind. libpq (EV::Pg->query_params) only understands $N, never '?'.
125 #
126 # The shared DBIO::PostgreSQL::SQLMaker is also used by the SYNC DBI driver,
127 # which needs '?', so the maker MUST keep emitting '?'. The translation
128 # therefore lives here, in the async transport, applied to maker output
129 # INTERNALLY (in _query_async / _query_async_pinned) before it reaches
130 # query_params -- the core #70 / ADR 0032 seam contract: '?'-in, dialect-out
131 # is the transport's own business.
132 #
133 # Subtleties this must respect (all verified against the maker's output):
134 # * '@?' is the JSONB jsonpath operator, not a placeholder. A '?' that is
135 # immediately preceded by '@' is part of an operator and is left alone.
136 # Its actual RHS placeholder ('@? ?::jsonpath') is a separate '?' and
137 # does get translated.
138 # * '?::jsonb' / '?::jsonpath' casts are real placeholders -> '$N::jsonb'.
139 # * 'ARRAY[?, ?]' (jsonb_exists_any/all) has one placeholder per '?'.
140 # * A '?' inside a single-quoted string literal ('...', with '' escaping)
141 # or a double-quoted identifier ("...", with "" escaping) is data/name,
142 # not a placeholder, and is skipped. This is defensive against inlined
143 # literals that happen to contain '?'.
144  
145  
146 37 ▶sub _transform_sql {
Subroutine _transform_sql: called CC=11 SCAR=24.0
147 37 my ($self, $sql) = @_;
148  
149 37 my $out = '';
150 37 my $n = 0;
151 37 my $len = length $sql;
152 37 my $i = 0;
153  
154 37 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 1092 37 1129
155 1092 my $c = substr($sql, $i, 1);
156  
157 1092 ▶ if ($c eq "'" || $c eq '"') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "'" or $c eq "\"") 61 1031 1092
Condition100%3/3
$c eq "'" or $c eq "\""
l!l&&r!l&&!r
3581031
MC/DC100%2/2
$c eq "'" or $c eq "\""
$c eq "'" $c eq "\""
Truth table100%3/3
A or B
A= $c eq "'"B= $c eq "\""
ABresult
1X1
011
000
158 # Copy a quoted run verbatim, honouring doubled-quote escaping.
159 61 my $quote = $c;
160 61 $out .= $c;
161 61 $i++;
162 61 ▶ while ($i < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 271 0 271
163 271 my $d = substr($sql, $i, 1);
164 271 $out .= $d;
165 271 $i++;
166 271 ▶ if ($d eq $quote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($d eq $quote) 62 209 271
167 62 ▶ if ($i < $len && substr($sql, $i, 1) eq $quote) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len and substr($sql, $i, 1) eq $quote) { } 1 61 62
Condition66%2/3
$i < $len and substr($sql, $i, 1) eq $quote
!ll&&!rl&&r
0611
MC/DC50%1/2
$i < $len and substr($sql, $i, 1) eq $quote
$i < $len substr($sql, $i, 1) eq $quote
Truth table66%2/3
A and B
A= $i < $lenB= substr($sql, $i, 1) eq $quote
ABresult
0X0
100
111
168 1 $out .= $quote; # doubled quote -> escaped, stay inside
169 1 $i++;
170 } else {
171 61 last; # end of quoted run
172 }
173 }
174 }
175 61 next;
176 }
177  
178 1031 ▶ if ($c eq '?') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq "?") 35 996 1031
179 # '@?' operator: the '?' belongs to the operator, not a placeholder.
180 35 ▶ if ($i > 0 && substr($sql, $i - 1, 1) eq '@') {
Branch: 1 branch
BranchTrueFalseTotal
if ($i > 0 and substr($sql, $i - 1, 1) eq "\@") 2 33 35
Condition66%2/3
$i > 0 and substr($sql, $i - 1, 1) eq "\@"
!ll&&!rl&&r
0332
MC/DC50%1/2
$i > 0 and substr($sql, $i - 1, 1) eq "\@"
$i > 0 substr($sql, $i - 1, 1) eq "\@"
Truth table66%2/3
A and B
A= $i > 0B= substr($sql, $i - 1, 1) eq "\@"
ABresult
0X0
100
111
181 2 $out .= $c;
182 2 $i++;
183 2 next;
184 }
185 33 $out .= '$' . (++$n);
186 33 $i++;
187 33 next;
188 }
189  
190 996 $out .= $c;
191 996 $i++;
192 }
193  
194 37 return $out;
195 }
196  
197 # --- Async query execution (transport seams) ----------------------------------
198  
199  
200 17 ▶sub _query_async {
Subroutine _query_async: called CC=3 SCAR=11.3
201 17 my ($self, $sql, $bind) = @_;
202 17 ▶ $bind //= [];
Condition50%1/2
$bind //= []
l!l
170
MC/DC0%0/1
$bind //= []
$bind
Truth table50%1/2
A
A= $bind
Aresult
11
00
203 17 $sql = $self->_transform_sql($sql);
204  
205 17 ▶ $self->_debug_query($sql, $bind) if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 17 17
206  
207 17 ▶ return $self->pool->acquire->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.1
208 17 my $pg = shift;
209 17 my $f = Future->new;
210 17 ▶ $pg->query_params($sql, $bind, sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
211 17 my ($rows, $err) = @_;
212 17 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) { } 0 17 17
213 0 $f->fail($err);
214 } else {
215 17 ▶ $f->done(ref $rows eq 'ARRAY' ? @$rows : $rows);
Branch: 1 branch
BranchTrueFalseTotal
ref $rows eq 'ARRAY' ? : 17 0 17
216 }
217 17 $self->pool->release($pg);
218 17 });
219 17 return $f;
220 17 });
221 }
222  
223  
224 1 ▶sub _query_async_pinned {
Subroutine _query_async_pinned: called CC=3 SCAR=11.5
225 1 my ($self, $pg, $sql, $bind) = @_;
226 1 ▶ $bind //= [];
Condition50%1/2
$bind //= []
l!l
10
MC/DC0%0/1
$bind //= []
$bind
Truth table50%1/2
A
A= $bind
Aresult
11
00
227 1 $sql = $self->_transform_sql($sql);
228  
229 1 ▶ $self->_debug_query($sql, $bind) if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 1 1
230  
231 1 my $f = Future->new;
232 1 ▶ $pg->query_params($sql, $bind, sub {
Subroutine __ANON__: called CC=3 SCAR=12.5
233 1 my ($rows, $err) = @_;
234 1 ▶ if ($err) { $f->fail($err) } else { $f->done(ref $rows eq 'ARRAY' ? @$rows : $rows) }
Branch: 2 branches
BranchTrueFalseTotal
if ($err) { } 0 1 1
ref $rows eq 'ARRAY' ? : 1 0 1
235 # Do NOT release — connection is pinned for the duration of the txn
236 1 });
237 1 return $f;
238 }
239  
240 0 ▶sub _debug_query {
Subroutine _debug_query: not called CC=2 SCAR=17.9
241 0 my ($self, $sql, $bind) = @_;
242 0 ▶ my $bind_str = join(', ', map { defined $_ ? "'$_'" : 'NULL' } @$bind);
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
243 0 warn "$sql: $bind_str\n";
244 }
245  
246 # --- Pool connect-action replay seam (karr #68) -------------------------------
247  
248  
249 5 ▶sub _run_pool_connect_statement {
Subroutine _run_pool_connect_statement: called CC=7 SCAR=20.6
250 5 my ($self, $conn, $sql, $attrs, @bind) = @_;
251 5 require EV;
252  
253 # The connection was just spawned; its async connect may still be in flight.
254 # Block the EV loop until it is ready (the core seam's synchronous contract).
255 # Prefer the pool's per-connection readiness Future (core
256 # DBIO::Storage::PoolBase::_connection_ready_future, karr #75), which is
257 # FAILED on a connect error -- so a bad connect surfaces as a thrown error
258 # here rather than busy-spinning on is_connected forever. Fall back to
259 # is_connected for a pool that does not expose the readiness seam (e.g. a
260 # bare test double that is not a PoolBase subclass at all).
261 5 my $pool = $self->pool;
262 5 ▶ if ($pool->can('_connection_ready_future')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pool->can('_connection_ready_future')) { } 0 5 5
263 0 my $ready = $pool->_connection_ready_future($conn);
264 0 ▶ EV::run(EV::RUN_ONCE()) until $ready->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
$ready->is_ready or do { EV::run(EV::RUN_ONCE()) } 0 0 0
265 0 $ready->get; # rethrows a connect error
266 }
267 else {
268 5 ▶ EV::run(EV::RUN_ONCE()) until $conn->is_connected;
Branch: 1 branch
BranchTrueFalseTotal
$conn->is_connected or do { EV::run(EV::RUN_ONCE()) } 5 0 5
269 }
270  
271 5 my $done = 0;
272 5 my $err;
273 5 ▶ my $cb = sub { (undef, $err) = @_; $done = 1 };
Subroutine __ANON__: called CC=1 SCAR=0.0
274 5 ▶ if (@bind) {
Branch: 1 branch
BranchTrueFalseTotal
if (@bind) { } 1 4 5
275 1 $conn->query_params($self->_transform_sql($sql), [@bind], $cb);
276 }
277 else {
278 4 $conn->query($sql, $cb);
279 }
280 5 ▶ EV::run(EV::RUN_ONCE()) until $done;
Branch: 1 branch
BranchTrueFalseTotal
$done or do { EV::run(EV::RUN_ONCE()) } 5 0 5
281  
282 5 ▶ croak "pool connect statement failed: $err" if defined $err;
Branch: 1 branch
BranchTrueFalseTotal
if defined $err 1 4 5
283 4 return;
284 }
285  
286 # --- Pipeline mode seams ------------------------------------------------------
287 # The inherited DBIO::Storage::Async::pipeline scaffold acquires a connection,
288 # brackets the batch with these three seams and releases the connection. EV::Pg
289 # expresses pipelining natively, so the base scaffold fits exactly -- no
290 # parallel pipeline() is needed (WP4 decision).
291  
292  
293 0 ▶sub _pipeline_enter { $_[1]->enter_pipeline }
Subroutine _pipeline_enter: not called CC=1 SCAR=6.9
294  
295  
296 0 ▶sub _pipeline_sync {
Subroutine _pipeline_sync: not called CC=1 SCAR=6.9
297 0 my ($self, $pg) = @_;
298 0 my $f = Future->new;
299 0 ▶ $pg->pipeline_sync(sub { $f->done });
Subroutine __ANON__: not called CC=1 SCAR=6.9
300 0 return $f;
301 }
302  
303  
304 0 ▶sub _pipeline_exit { $_[1]->exit_pipeline }
Subroutine _pipeline_exit: not called CC=1 SCAR=6.9
305  
306 # --- LISTEN/NOTIFY ------------------------------------------------------------
307  
308  
309 2 ▶sub listen {
Subroutine listen: called CC=3 SCAR=11.0
Pod documented
310 2 my ($self, $channel, $cb) = @_;
311  
312 2 $self->{_listeners}{$channel} = $cb;
313  
314 # Use a dedicated connection for LISTEN (not from the pool).
315 # EV::Pg->new returns before the socket is actually connected; query()
316 # dispatched on a not-yet-connected handle throws "not connected".
317 # We buffer LISTEN/UNLISTEN until on_connect fires and then flush.
318 #
319 # karr #15: a second listen() on an already-connected dedicated conn
320 # used to dispatch its LISTEN SQL directly via _listen_pg->query().
321 # That races the still-in-flight CommandComplete from the first
322 # LISTEN — libpq refuses with "another command is already in
323 # progress", the LISTEN SQL is lost, and notifications on the new
324 # channel are never delivered. Fix: route every LISTEN/UNLISTEN SQL
325 # through a single _dispatch_listen_queue serialiser so we never have
326 # two in flight at once. on_connect sets _listen_connected and calls
327 # us; listen/unlisten push onto _listen_pending and call us; we drain
328 # one at a time and re-enter from the in-flight query's callback.
329 2 ▶ $self->{_listen_pg} ||= do {
Condition66%2/3
$self->{"_listen_pg"} ||= do {
l!l&&r!l&&!r
110
MC/DC0%0/2
$self->{"_listen_pg"} ||= do { require EV::Pg; $self->{"_listen_pending"} = []; $self->{"_listen_dispatching"} = 0; $self->{"_listen_connected"} = 0; my $pg = "EV::Pg"->new("conninfo", $self->_conninfo_string, "keep_alive", 1, "on_connect", sub { $self->{"_listen_connected"} = 1; $self->_dispatch_listen_queue; } , "on_error", sub { warn "LISTEN connection error: $_[0]\n"; } , "on_notify", sub { my($ch, $payload, $pid) = @_; if (my $handler = $self->{"_listeners"}{$ch}) { &$handler($ch, $payload, $pid); } ; } ); $pg }
$self->{"_listen_pg"} do { require EV::Pg; $self->{"_listen_pending"} = []; $self->{"_listen_dispatching"} = 0; $self->{"_listen_connected"} = 0; my $pg = "EV::Pg"->new("conninfo", $self->_conninfo_string, "keep_alive", 1, "on_connect", sub { $self->{"_listen_connected"} = 1; $self->_dispatch_listen_queue; } , "on_error", sub { warn "LISTEN connection error: $_[0]\n"; } , "on_notify", sub { my($ch, $payload, $pid) = @_; if (my $handler = $self->{"_listeners"}{$ch}) { &$handler($ch, $payload, $pid); } ; } ); $pg }
Truth table66%2/3
A ||= B
A= $self->{"_listen_pg"}B= do { require EV::Pg; $self->{"_listen_pending"} = []; $self->{"_listen_dispatching"} = 0; $self->{"_listen_connected"} = 0; my $pg = "EV::Pg"->new("conninfo", $self->_conninfo_string, "keep_alive", 1, "on_connect", sub { $self->{"_listen_connected"} = 1; $self->_dispatch_listen_queue; } , "on_error", sub { warn "LISTEN connection error: $_[0]\n"; } , "on_notify", sub { my($ch, $payload, $pid) = @_; if (my $handler = $self->{"_listeners"}{$ch}) { &$handler($ch, $payload, $pid); } ; } ); $pg }
ABresult
1X1
011
000
330 1 require EV::Pg;
331 1 $self->{_listen_pending} = [];
332 1 $self->{_listen_dispatching} = 0;
333 1 $self->{_listen_connected} = 0;
334 my $pg = EV::Pg->new(
335 conninfo => $self->_conninfo_string,
336 keep_alive => 1,
337 1 ▶ on_connect => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
338 1 $self->{_listen_connected} = 1;
339 1 $self->_dispatch_listen_queue;
340 },
341 0 ▶ on_error => sub { warn "LISTEN connection error: $_[0]\n" },
Subroutine __ANON__: not called CC=1 SCAR=6.9
342 3 ▶ on_notify => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
343 3 my ($ch, $payload, $pid) = @_;
344 3 ▶ if (my $handler = $self->{_listeners}{$ch}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $handler = $self->{"_listeners"}{$ch}) 1 2 3
345 1 $handler->($ch, $payload, $pid);
346 }
347 },
348 1 );
349 1 $pg;
350 };
351  
352 2 my $quoted = $self->sql_maker->_quote($channel);
353 2 my $sql = "LISTEN $quoted";
354 2 push @{ $self->{_listen_pending} }, $sql;
355 2 ▶ $self->_dispatch_listen_queue if $self->{_listen_connected};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_listen_connected"} 1 1 2
356 }
357  
358 # Drain one SQL off _listen_pending and send it via the dedicated LISTEN
359 # connection, then chain the next dispatch off its callback. This is the
360 # single point through which ALL LISTEN/UNLISTEN SQLs flow, so we never
361 # have two in flight on the same libpq connection. Without this, a second
362 # listen() issued while the first LISTEN's CommandComplete is still in
363 # flight races libpq and dies with "another command is already in
364 # progress", losing the second subscription. (karr #15)
365 6 ▶sub _dispatch_listen_queue {
Subroutine _dispatch_listen_queue: called CC=5 SCAR=16.3
366 6 my ($self) = @_;
367  
368 # Not connected yet — on_connect will call us when the socket is up.
369 6 ▶ return unless $self->{_listen_connected};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_listen_connected"} 0 6 6
370 # A previous dispatch is still in flight; its callback will re-enter
371 # us once libpq has consumed its CommandComplete + ReadyForQuery.
372 6 ▶ return if $self->{_listen_dispatching};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_listen_dispatching"} 0 6 6
373 # Nothing queued.
374 6 ▶ return unless $self->{_listen_pending} && @{$self->{_listen_pending}};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_listen_pending"} and @{$self->{"_listen_pending"};} 3 3 6
Condition66%2/3
$self->{"_listen_pending"} and @{$self->{"_listen_pending"};}
!ll&&!rl&&r
033
MC/DC50%1/2
$self->{"_listen_pending"} and @{$self->{"_listen_pending"};}
$self->{"_listen_pending"} @{$self->{"_listen_pending"};}
Truth table66%2/3
A and B
A= $self->{"_listen_pending"}B= @{$self->{"_listen_pending"};}
ABresult
0X0
100
111
375  
376 3 my $sql = shift @{$self->{_listen_pending}};
377 3 $self->{_listen_dispatching} = 1;
378 3 ▶ $self->{_listen_pg}->query($sql, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
379 3 $self->{_listen_dispatching} = 0;
380 3 $self->_dispatch_listen_queue;
381 3 });
382 }
383  
384  
385 1 ▶sub unlisten {
Subroutine unlisten: called CC=3 SCAR=11.1
Pod documented
386 1 my ($self, $channel) = @_;
387 1 delete $self->{_listeners}{$channel};
388 1 ▶ if ($self->{_listen_pg}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_listen_pg"}) 1 0 1
389 1 my $quoted = $self->sql_maker->_quote($channel);
390 1 my $sql = "UNLISTEN $quoted";
391 1 push @{ $self->{_listen_pending} }, $sql;
392 1 ▶ $self->_dispatch_listen_queue if $self->{_listen_connected};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_listen_connected"} 1 0 1
393 }
394 }
395  
396  
397 3 ▶sub notify {
Subroutine notify: called CC=3 SCAR=11.1
Pod documented
398 3 my ($self, $channel, $payload) = @_;
399  
400 3 ▶ croak 'Channel name required' unless defined $channel && $channel ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $channel and $channel ne "" 1 2 3
Condition66%2/3
defined $channel and $channel ne ""
!ll&&!rl&&r
102
MC/DC50%1/2
defined $channel and $channel ne ""
defined $channel $channel ne ""
Truth table66%2/3
A and B
A= defined $channelB= $channel ne ""
ABresult
0X0
100
111
401  
402 2 ▶ return $self->pool->acquire->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
403 2 my $pg = shift;
404 2 my $f = Future->new;
405  
406 # pg_notify() with bind params -- NOTIFY itself takes no placeholders,
407 # and inlining the payload as a string literal invites quoting bugs.
408 2 ▶ $pg->query_params('SELECT pg_notify($1, $2)', [ $channel, $payload // '' ], sub {
Subroutine __ANON__: called CC=2 SCAR=7.4
409 2 my ($res, $err) = @_;
410 2 $self->pool->release($pg);
411 2 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) { } 0 2 2
412 0 $f->fail($err);
413 } else {
414 2 $f->done;
415 }
416 2 ▶ });
Condition100%2/2
$payload // ""
l!l
11
MC/DC100%1/1
$payload // ""
$payload
Truth table100%2/2
A
A= $payload
Aresult
11
00
417  
418 2 return $f;
419 2 });
420 }
421  
422 # --- COPY ---------------------------------------------------------------------
423  
424  
425 0 ▶sub copy_in {
Subroutine copy_in: not called CC=1 SCAR=6.9
Pod documented
426 0 my ($self, $table, $columns, $coderef) = @_;
427  
428 0 my $col_list = join(', ', map { $self->sql_maker->_quote($_) } @$columns);
429 0 my $quoted_table = $self->sql_maker->_quote($table);
430 0 my $sql = "COPY $quoted_table ($col_list) FROM STDIN";
431  
432 0 ▶ return $self->pool->acquire->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
433 0 my $pg = shift;
434 0 my $f = Future->new;
435  
436 # EV::Pg fires the COPY query callback TWICE (see EV::Pg::Pg POD,
437 # "A COPY command runs in two phases"): first with the string tag
438 # "COPY_IN" when libpq has accepted the COPY command and the stream
439 # is ready, then a second time with the final cmd_tuples result when
440 # libpq has consumed the EOF marker, applied every row, and sent
441 # CommandComplete + ReadyForQuery. The connection is NOT safe to
442 # hand back to the pool until that second firing — releasing after
443 # the first lets the next acquire race libpq's still-pending reply
444 # and fail with "another command is already in progress". We track
445 # which phase we're in with $phase and only release + complete the
446 # Future on the second firing. (karr #13.)
447 0 my $phase = 0;
448 0 my $coderef_err; # die from the user's coderef, captured to forward
449 # into the Future failure verbatim — libpq wraps
450 # whatever we pass to put_copy_end into its own
451 # "ERROR: COPY from stdin failed: …" envelope, so
452 # callers would see the wrapped string instead of
453 # their original die message unless we keep the
454 # raw $@. See t/18 "dying coderef" assertion.
455 0 ▶ $pg->query($sql, sub {
Subroutine __ANON__: not called CC=11 SCAR=48.8
456 0 my ($status, $err) = @_;
457 0 $phase++;
458  
459 # Second firing: server has finished the COPY, connection is back
460 # at ReadyForQuery and safe to reuse.
461 0 ▶ if ($phase == 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase == 2) 0 0 0
462 0 $self->pool->release($pg);
463 0 ▶ if ($coderef_err) {
Branch: 2 branches
BranchTrueFalseTotal
if ($coderef_err) { } 0 0 0
elsif ($err) { } 0 0 0
464 0 $f->fail($coderef_err);
465 } elsif ($err) {
466 0 $f->fail($err);
467 } else {
468 0 $f->done($status);
469 }
470 0 return;
471 }
472  
473 # First firing: COPY stream is ready. Either reject early on a
474 # synchronous libpq error, or run the user coderef + end the
475 # COPY. EV::Pg will then drive the second firing on its own when
476 # the server reports completion.
477 0 ▶ if ($err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($err) 0 0 0
478 # Connection is unrecoverable in COPY mode — release anyway so
479 # the pool slot isn't pinned; callers see the error via $f.
480 0 $self->pool->release($pg);
481 0 $f->fail($err);
482 0 return;
483 }
484  
485 0 ▶ my $put = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
486 0 my $row = shift;
487 0 ▶ my $line = join("\t", map { defined $_ ? $_ : '\N' } @$row) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
488 0 $pg->put_copy_data($line);
489 0 };
490  
491 0 ▶ my $eval_err = eval { $coderef->($put); 1 } ? undef : $@;
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &$coderef($put); 1 } } ? : 0 0 0
492 0 ▶ if ($eval_err) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eval_err) 0 0 0
493 0 $coderef_err = $eval_err;
494 # Pass the error to libpq so it aborts the COPY server-side,
495 # but keep $coderef_err so we fail the Future with the raw
496 # message instead of libpq's wrapped "ERROR: COPY from stdin
497 # failed: …" envelope.
498 0 my $rc = $pg->put_copy_end($eval_err);
499 0 ▶ if (defined $rc && $rc < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc and $rc < 0) 0 0 0
Condition0%0/3
defined $rc and $rc < 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $rc and $rc < 0
defined $rc $rc < 0
Truth table0%0/3
A and B
A= defined $rcB= $rc < 0
ABresult
0X0
100
111
500 0 $self->pool->release($pg);
501 0 $f->fail("put_copy_end failed");
502 0 return;
503 }
504 # put_copy_end queued the EOF marker with the abort message;
505 # second firing will fire $f with $coderef_err.
506 0 return;
507 }
508  
509 0 my $rc = $pg->put_copy_end;
510 0 ▶ if (defined $rc && $rc < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc and $rc < 0) 0 0 0
Condition0%0/3
defined $rc and $rc < 0
!ll&&!rl&&r
000
MC/DC0%0/2
defined $rc and $rc < 0
defined $rc $rc < 0
Truth table0%0/3
A and B
A= defined $rcB= $rc < 0
ABresult
0X0
100
111
511 # put_copy_end could not even queue the EOF marker (hard libpq
512 # error). Treat as COPY failure and complete the Future here
513 # because the second firing will never arrive.
514 0 $self->pool->release($pg);
515 0 $f->fail("put_copy_end failed");
516 0 return;
517 }
518 # put_copy_end queued (or was about to queue) the EOF marker.
519 # Second callback firing will release the pool and complete $f.
520 0 });
521  
522 0 return $f;
523 0 });
524 }
525  
526 # --- Async Deploy -------------------------------------------------------------
527 #
528 # WP4 note (karr #22): deploy_async / _execute_ddl_async / _drop_statements_for
529 # are kept here rather than hoisted into core. They are mostly generic
530 # (statement-splitting + sequential pinned _query_async inside a txn) and could
531 # be hoisted, but hoisting is a separate small core ticket and is NOT done here
532 # -- keeping the driver behaviour identical is the point of this thin-transport
533 # refactor. If/when core grows a generic deploy_async, this can inherit it.
534  
535  
536 0 ▶sub deploy_async {
Subroutine deploy_async: not called CC=3 SCAR=24.8
Pod documented
537 0 my ($self, $schema, $opts) = @_;
538 0 ▶ $opts //= {};
Condition0%0/2
$opts //= {}
l!l
00
MC/DC0%0/1
$opts //= {}
$opts
Truth table0%0/2
A
A= $opts
Aresult
11
00
539  
540 # Generate the install DDL from the schema classes (synchronous, in-memory
541 # — no DB roundtrips here; the whole point of routing through the DBIO
542 # deploy pipeline is to keep DDL construction out of the storage layer).
543 0 my $ddl = $schema->pg_install_ddl;
544  
545 # Optional DROP TABLE pre-pass for idempotent re-runs. Mirrors the
546 # {add_drop_table => 1} option that DBIO::Schema->deploy accepts.
547 0 ▶ if ($opts->{add_drop_table}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"add_drop_table"}) 0 0 0
548 0 $ddl = join("\n\n", _drop_statements_for($schema), $ddl);
549 }
550  
551 # Run all DDL on a single pinned connection inside an async transaction.
552 # PostgreSQL's transactional DDL means a failure on statement N of M
553 # rolls back the previous N-1 — same semantics as
554 # DBIO::Deploy::Base::_execute_ddl with _use_transactional_ddl(1),
555 # just on the Future side of the wire.
556 0 ▶ return $self->txn_do_async(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
557 0 my ($ctx) = @_;
558 0 return $self->_execute_ddl_async($ctx->txn_pg, $ddl);
559 0 });
560 }
561  
562 # Split a DDL string and execute each statement on a pinned EV::Pg
563 # connection, one at a time. Returns a Future that resolves on the last
564 # successful statement or fails on the first libpq error — the surrounding
565 # txn_do_async then COMMITs or ROLLBACKs accordingly.
566 #
567 # The recursion pumps exactly one DDL at a time on the pinned connection:
568 # libpq never has two in flight on the same handle. Each step waits for
569 # CommandComplete + ReadyForQuery before dispatching the next. The
570 # surrounding txn_do_async retain()s the returned Then-Future, which keeps
571 # the whole chain alive until COMMIT/ROLLBACK fires.
572 0 ▶sub _execute_ddl_async {
Subroutine _execute_ddl_async: not called CC=1 SCAR=6.9
573 0 my ($self, $pg, $ddl) = @_;
574  
575 0 my @stmts = grep { !/^\s*--/ } _split_statements($ddl);
576  
577 0 my $recur;
578 0 ▶ $recur = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
579 0 my $stmt;
580 0 ▶ unless (defined($stmt = shift @stmts)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined($stmt = shift @stmts)) 0 0 0
581 0 return Future->done;
582 }
583 0 my $f = Future->new;
584 0 ▶ $self->_debug_query($stmt, []) if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
585 0 ▶ $pg->query($stmt, sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
586 0 my (undef, $err) = @_;
587 0 ▶ $err ? $f->fail($err) : $f->done;
Branch: 1 branch
BranchTrueFalseTotal
$err ? : 0 0 0
588 0 });
589 0 return $f->then($recur);
590 0 };
591 0 return $recur->();
592 }
593  
594 # Build DROP TABLE IF EXISTS ... CASCADE for every regular table in the
595 # schema. Skips views, virtual views, and scalar-ref names that aren't
596 # plain identifiers. Returns a single string the caller prepends to the
597 # install DDL.
598 0 ▶sub _drop_statements_for {
Subroutine _drop_statements_for: not called CC=5 SCAR=34.0
599 0 my ($schema) = @_;
600 0 my @out;
601 0 for my $name ($schema->sources) {
602 0 my $source = $schema->source($name);
603 0 ▶ next if $source->isa('DBIO::ResultSource::View');
Branch: 1 branch
BranchTrueFalseTotal
if $source->isa("DBIO::ResultSource::View") 0 0 0
604 0 my $table = $source->name;
605 0 ▶ next if ref $table;
Branch: 1 branch
BranchTrueFalseTotal
if ref $table 0 0 0
606 0 ▶ next if $table =~ /\s|\(/;
Branch: 1 branch
BranchTrueFalseTotal
if $table =~ /\s|\(/ 0 0 0
607 0 push @out, sprintf 'DROP TABLE IF EXISTS %s CASCADE;', _quote_ident($table);
608 }
609 0 return join("\n\n", @out);
610 }
611  
612 0 ▶sub deploy {
Subroutine deploy: not called CC=1 SCAR=6.9
Pod documented
613 0 my $self = shift;
614 0 return $self->deploy_async(@_)->get;
615 }
616  
617 # --- Schema Integration -------------------------------------------------------
618 # schema / debug / connected / DESTROY and the sync CRUD/txn ->get fallbacks are
619 # inherited from DBIO::Storage::Async. disconnect is overridden to also tear down
620 # the dedicated LISTEN connection.
621  
622 9 ▶sub disconnect {
Subroutine disconnect: called CC=3 SCAR=12.3
Pod documented
623 9 my $self = shift;
624 9 ▶ if ($self->{pool}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pool"}) 9 0 9
625 9 $self->{pool}->shutdown;
626 9 $self->{pool} = undef;
627 }
628 9 ▶ if ($self->{_listen_pg}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_listen_pg"}) 0 9 9
629 0 $self->{_listen_pg}->finish;
630 0 $self->{_listen_pg} = undef;
631 }
632 }
633  
634 10 1;
635  
636 __END__
637  
638 =pod
639  
640 =encoding UTF-8
641  
642 =head1 NAME
643  
644 DBIO::PostgreSQL::EV::Storage - Async PostgreSQL storage driver using EV::Pg
645  
646 =head1 VERSION
647  
648 version 0.900001
649  
650 =head1 DESCRIPTION
651  
652 The native C<ev> async transport for PostgreSQL (core ADR 0030 / 0031): a
653 B<thin transport> over L<EV::Pg>, a non-blocking libpq client that speaks the
654 async wire protocol directly. No DBI, no DBD::Pg, just raw libpq performance.
655  
656 It resolves as the C<ev> async mode of L<DBIO::PostgreSQL::Storage> (registered
657 there via C<< register_async_mode( ev => ... ) >>), so a schema connected with
658 C<< { async => 'ev' } >> answers the six C<*_async> storage methods over EV::Pg
659 while the same schema keeps serving synchronous queries over DBI/DBD::Pg.
660  
661 =head2 Thin transport: shared machinery is inherited
662  
663 The B<Model-B orchestration> (ADR 0030 §4) is inherited unchanged from
664 L<DBIO::Storage::Async>: the CRUD runner (L<DBIO::Storage::Async/_run_crud>
665 with its pooled / pinned runners), the INSERT returned-columns mapping,
666 L<DBIO::Storage::Async/txn_do_async> bracketing, the L<DBIO::Storage::Async/pipeline>
667 scaffold, the C<sql_maker> plumbing and the sync C<< ->get >> fallbacks. This
668 class fills B<only> the loop-/wire-specific seams:
669  
670 =over 4
671  
672 =item * L</sql_maker_class> / L</_sql_maker_args> / L</_post_insert_sql> --
673 the PostgreSQL SQLMaker and its C< RETURNING *> insert suffix
674  
675 =item * L</_transform_sql> -- C<?> to positional C<$N> placeholders, applied
676 B<internally> by the query seams (the core #70 / ADR 0032 C<?>-in contract)
677  
678 =item * L</_query_async> / L</_query_async_pinned> -- native EV::Pg query
679 dispatch (pooled and pinned)
680  
681 =item * L</_run_pool_connect_statement> -- synchronous connect-action replay on
682 a freshly-spawned EV::Pg pool connection (karr #68 seam)
683  
684 =item * L</_pipeline_enter> / L</_pipeline_sync> / L</_pipeline_exit> -- libpq
685 pipeline mode
686  
687 =item * L</connect_info> / L</_conninfo_string> -- the libpq conninfo transport
688 shape
689  
690 =item * L</_txn_context_class> / L</_txn_conn_accessor> -- the pinned-connection
691 transaction context
692  
693 =back
694  
695 Because the extension-composition point is the core resolver, an async storage
696 layer composed onto this transport (core #70) inherits every CRUD/txn path for
697 free; the transport only has to advertise the wire capabilities it really
698 provides (see L</transport_capabilities>).
699  
700 =head2 Transport value-add
701  
702 Beyond the CRUD/txn contract this transport carries the PostgreSQL wire
703 features the abstract C<future_io> transport cannot: LISTEN/NOTIFY
704 (L</listen> / L</notify>), COPY (L</copy_in>) and libpq pipelining. These
705 override the base's croaking defaults and are declared in
706 L</transport_capabilities> so a layer that requires them composes cleanly
707 (and core croaks loudly, never silently dropping the feature, when it cannot).
708  
709 =head1 METHODS
710  
711 =head2 sql_maker_class
712  
713 The L<DBIO::PostgreSQL::SQLMaker> subclass used to generate SQL. Shared with
714 the sync driver and the C<future_io> transport, so the maker keeps emitting
715 C<?> placeholders (translated to C<$N> internally by L</_transform_sql>).
716  
717 =head2 _sql_maker_args
718  
719 PostgreSQL SQLMaker construction args: double-quote identifier quoting, C<.>
720 name separator, LIMIT/OFFSET dialect. Matches the sync driver and the
721 C<future_io> transport.
722  
723 =head2 _post_insert_sql
724  
725 Returns C< RETURNING *> so an INSERT yields every populated column (autoinc PK
726 + retrieve-on-insert defaults); the inherited runner folds the row onto the
727 supplied data to build the returned-columns hashref (ADR 0031 §3).
728  
729 =head2 future_class
730  
731 Returns C<'Future'> -- uses L<Future.pm|Future> from CPAN. Plain
732 L<Future/Future> C<< ->then >> callbacks auto-wrap a non-Future return value
733 into a resolved Future (ADR 0031 §4), so ResultSet/Row C<< *_async >>
734 callbacks that return plain values resolve without an explicit
735 C<< Future->done(...) >> wrap.
736  
737 =head2 transport_capabilities
738  
739 my @caps = DBIO::PostgreSQL::EV::Storage->transport_capabilities;
740  
741 Class method (see L<DBIO::Storage::Async/transport_capabilities>). Declares the
742 wire capabilities this transport really provides, so
743 L<DBIO::Storage::DBI/_async_storage> lets an async extension layer that requires
744 any of them compose onto it (and croaks naming the gap otherwise, rather than
745 silently dropping a feature). This transport provides:
746  
747 =over 4
748  
749 =item * C<on_connect_replay> -- its pool (L<DBIO::PostgreSQL::EV::Pool>, a
750 L<DBIO::Storage::PoolBase>) drives core's
751 L<DBIO::Storage::Async/_setup_pool_connection> on every freshly-spawned
752 connection, and L</_run_pool_connect_statement> replays the owning sync
753 storage's C<on_connect_do>/C<on_connect_call> against it (karr #68).
754  
755 =item * C<listen> / C<notify> -- LISTEN/NOTIFY (L</listen>, L</unlisten>,
756 L</notify>).
757  
758 =item * C<copy> -- COPY FROM STDIN bulk load (L</copy_in>).
759  
760 =item * C<pipeline> -- libpq pipeline mode (L</_pipeline_enter> /
761 L</_pipeline_sync> / L</_pipeline_exit> under the inherited scaffold).
762  
763 =back
764  
765 =head2 connect_info
766  
767 $storage->connect_info([ \%conninfo, \%opts ]);
768  
769 Set connection parameters. C<%conninfo> is passed to L<EV::Pg> as libpq
770 connection parameters (host, dbname, user, ...). When the embedding sync
771 storage feeds its own DBI-form connect info
772 (C<< ['dbi:Pg:...', $user, $pass, \%attrs] >>) it is translated into the async
773 C<< [ \%conninfo, \%opts ] >> shape first. AccessBroker connect info
774 (C<< [ $broker ] >>) is detected and wired to the per-spawn credential provider
775 (the base broker seam), exactly as the sync path does.
776  
777 This override (rather than the inherited base C<connect_info>) is retained
778 because the EV transport (a) folds the DBI-form DSN into libpq conninfo inline
779 and (b) also tears down the dedicated LISTEN connection on reconnect.
780  
781 =head2 _async_broker_conninfo
782  
783 my $conninfo = $storage->_async_broker_conninfo($mode);
784  
785 AccessBroker seam (see L<DBIO::Storage::Async/ACCESSBROKER CONSUMPTION>): return
786 one fresh, storage-native libpq conninfo hash for a single new pool connection,
787 built from the current broker credentials via the inherited normalisation.
788  
789 =head2 pool
790  
791 Returns the L<DBIO::PostgreSQL::EV::Pool> connection pool, created lazily on
792 first access. The pool is wired with C<< storage => $self >> so its
793 core-shared spawn path (L<DBIO::Storage::PoolBase/_spawn_connection>) replays
794 the owning sync storage's connect actions on each new connection via
795 L</_run_pool_connect_statement> (karr #68). Fed the per-spawn
796 C<conninfo_provider> when an AccessBroker is attached, otherwise the static
797 conninfo string.
798  
799 =head2 _txn_context_class
800  
801 The pinned-connection transaction context the inherited
802 L<DBIO::Storage::Async/txn_do_async> hands to its coderef:
803 L<DBIO::PostgreSQL::EV::TransactionContext>.
804  
805 =head2 _txn_conn_accessor
806  
807 The constructor key the pinned connection is passed under -- C<pg>, matching
808 L<DBIO::PostgreSQL::EV::TransactionContext>.
809  
810 =head2 _transform_sql
811  
812 Transport-internal SQL shaping (core #70 / ADR 0032). Rewrite C<?> placeholders
813 to PostgreSQL positional C<$N>, skipping quoted literals / identifiers and the
814 JSONB C<@?> operator. Called first by L</_query_async> / L</_query_async_pinned>
815 on the raw C<sql_maker> output; idempotent on already-C<$N> SQL (no bare C<?>
816 to touch), so a C<$N> passthrough stays intact.
817  
818 =head2 _query_async
819  
820 Transport seam. Execute a query on a freshly-acquired pooled connection,
821 releasing it once the Future is ready. Returns a L<Future> of the raw result
822 rows (list of column arrayrefs for a result set, or the affected-row count for
823 plain DML -- ADR 0031 §3), exactly what the inherited C<_run_crud> expects.
824  
825 Receives SQL in the C<sql_maker> C<?>-placeholder dialect and shapes it into
826 PostgreSQL's positional C<$N> B<internally> (via L</_transform_sql>) before it
827 reaches libpq -- the core #70 / ADR 0032 seam contract.
828  
829 =head2 _query_async_pinned
830  
831 Transport seam. Like L</_query_async> but runs on the supplied pinned
832 connection and does B<not> release it -- used for queries inside a pinned
833 transaction. Shapes the incoming C<?>-dialect SQL internally via
834 L</_transform_sql> exactly as L</_query_async> does.
835  
836 =head2 _run_pool_connect_statement
837  
838 $storage->_run_pool_connect_statement($conn, $sql, $attrs, @bind);
839  
840 Native-backend override of the core connect-action runner seam
841 (L<DBIO::Storage::Async/_run_pool_connect_statement>). The base default drives a
842 blocking DBI C<do> and croaks on a non-DBI connection; an EV::Pg handle is
843 neither a C<< { dbh => $dbh } >> wrapper nor a do-capable DBI handle, so this
844 override drives the statement B<synchronously to completion> on that very
845 connection over the EV loop.
846  
847 Called once per freshly-spawned pool connection from
848 L<DBIO::Storage::Async/_setup_pool_connection>, so the owning sync storage's
849 C<on_connect_do> / C<on_connect_call> (including C<connect_call_*> methods such
850 as an extension's C<connect_call_load_age>) replay on every new EV pool
851 connection, identical to the C<future_io> pool. The freshly-spawned EV::Pg
852 handle may still be mid-connect, so we first drive the loop until it is up, then
853 run the statement and drive the loop until it completes. C<$attrs> (the DBI
854 attribute hashref) has no EV::Pg analogue and is ignored.
855  
856 =head2 _pipeline_enter
857  
858 Open libpq pipeline mode on the connection.
859  
860 =head2 _pipeline_sync
861  
862 Flush the batched queries and resolve once the pipeline sync point has been
863 acknowledged. EV::Pg's C<pipeline_sync> takes a completion callback; we adapt it
864 to the Future the inherited scaffold expects.
865  
866 =head2 _pipeline_exit
867  
868 Close libpq pipeline mode on the connection.
869  
870 =head2 listen
871  
872 $storage->listen($channel, sub {
873 my ($channel, $payload, $sender_pid) = @_;
874 # Handle notification
875 });
876  
877 Subscribe to PostgreSQL LISTEN/NOTIFY notifications on the given channel. The
878 callback fires each time a notification arrives. Transport value-add: overrides
879 the base's croaking default (declared as the C<listen> capability).
880  
881 =head2 unlisten
882  
883 $storage->unlisten($channel);
884  
885 Unsubscribe from a notification channel.
886  
887 =head2 notify
888  
889 $storage->notify($channel, $payload?);
890  
891 Send a PostgreSQL NOTIFY to the given channel with an optional payload.
892 Returns a L<Future> that resolves when the NOTIFY has been dispatched.
893  
894 Unlike L</listen>, this does not require a dedicated connection — it uses
895 a pooled connection from the normal pool.
896  
897 =head2 copy_in
898  
899 $storage->copy_in($table, \@columns, sub {
900 my ($put) = @_;
901 $put->(['Miles Davis', 'Jazz']);
902 $put->(['John Coltrane', 'Jazz']);
903 });
904  
905 Bulk load data via PostgreSQL COPY FROM STDIN. The callback receives a writer
906 function that accepts arrayrefs of column values. Transport value-add:
907 overrides the base's croaking default (declared as the C<copy> capability).
908  
909 =head2 deploy_async
910  
911 my $future = $storage->deploy_async($schema, \%opts);
912 $future->get;
913  
914 Deploys C<$schema> via the native DBIO deploy pipeline, executing every
915 DDL statement on EV::Pg inside a single async transaction. The Future
916 resolves on success (COMMIT committed) or fails on the first DDL error
917 (ROLLBACK rolled the whole batch back).
918  
919 C<%opts>:
920  
921 =over 4
922  
923 =item add_drop_table => 1
924  
925 Prepend C<DROP TABLE IF EXISTS ... CASCADE> for every source in the
926 schema, so a re-run on a populated database is idempotent. Default 0.
927  
928 =back
929  
930 Requires C<$schema> to expose C<pg_install_ddl> — typically a
931 L<DBIO::PostgreSQL> schema (e.g. via C<< use DBIO Schema => -pg >>). The
932 DDL is generated locally from the schema classes (no DB roundtrips for
933 DDL construction); only the execution hits libpq.
934  
935 =head1 AUTHOR
936  
937 DBIO Authors
938  
939 =head1 COPYRIGHT AND LICENSE
940  
941 Copyright (C) 2026 DBIO Authors
942  
943 This is free software; you can redistribute it and/or modify it under
944 the same terms as the Perl 5 programming language system itself.
945  
946 =cut
« EV/TestHarness.pm ↑ Summary EV/Pool.pm »