Async.pm

filter: Statementstmt 40.0% 206 / 515 Branchbran 21.2% 54 / 254 Conditioncond 31.1% 43 / 138 MC/DCmcdc 15.2% 13 / 85 Subroutinesub 64.8% 35 / 54 Podpod 100% 2 / 2 totaltotal 33.6% 353 / 1048 CC 194 SCAR 57.8
CC
194
Cov
33%
__ANON__
1640.0
__ANON__
240.0
_resolve_placeholders
240.0
CRAP 323.3
↑ Summary Async/Row.pm »
1 package DBIx::Class::Async;
2  
3 101 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 101 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 101 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 101 our $VERSION = qv('v1.2.0');
8 101 our $AUTHORITY = 'cpan:MANWAR';
9  
10 =encoding utf8
11  
12 =head1 NAME
13  
14 DBIx::Class::Async - Non-blocking, multi-worker asynchronous wrapper for DBIx::Class
15  
16 =head1 VERSION
17  
18 Version v1.2.0
19  
20 =head1 DISCLAIMER
21  
22 B<This is pure experimental currently.>
23  
24 You are encouraged to try and share your suggestions.
25  
26 =head1 DATABASE SUPPORT
27  
28 =head2 Oracle
29  
30 DBIx::Class::Async has been tested against Oracle AI Database 23ai Free
31 (running via Docker) using L<DBD::Oracle> and the C<FREEPDB1> pluggable
32 database. The following features were verified to work correctly:
33  
34 =over 4
35  
36 =item * CRUD operations (create, read, update, delete)
37  
38 =item * search(), count(), and all()
39  
40 =item * belongs_to and has_many relationships
41  
42 =item * Transactions via txn_do()
43  
44 =item * Concurrent async queries across multiple workers
45  
46 =back
47  
48 To run the Oracle integration tests yourself, set the following environment
49 variables and run the test in C<xt/>:
50  
51 DBIC_ASYNC_ORACLE_DSN='dbi:Oracle:host=localhost;port=1521;service_name=FREEPDB1' \
52 DBIC_ASYNC_ORACLE_USER='your_user' \
53 DBIC_ASYNC_ORACLE_PASS='your_password' \
54 prove -lv xt/001-oracle.t
55  
56 B<Note:> L<Math::Base36> E<gt>= 0.07 is required for Oracle support.
57  
58 =head2 MySQL
59  
60 DBIx::Class::Async has been tested against MySQL 8.0.45 (Ubuntu 24.04) using
61 L<DBD::mysql>. The following features were verified to work correctly:
62  
63 =over 4
64  
65 =item * CRUD operations (create, read, update, delete)
66  
67 =item * search(), count(), and all()
68  
69 =item * belongs_to and has_many relationships
70  
71 =item * Transactions via txn_do()
72  
73 =item * Concurrent async queries across multiple workers
74  
75 =back
76  
77 To run the MySQL integration tests against your instance, set the following
78 environment variables and run the test in C<xt/>:
79  
80 DBIC_ASYNC_MYSQL_DSN='dbi:mysql:database=your_db;host=localhost;port=3306' \
81 DBIC_ASYNC_MYSQL_USER='your_user' \
82 DBIC_ASYNC_MYSQL_PASS='your_password' \
83 prove -lv xt/002-mysql.t
84  
85 =head2 PostgreSQL
86  
87 DBIx::Class::Async has been tested against PostgreSQL using
88 L<Test::PostgreSQL::v2> which spins up a temporary PostgreSQL instance
89 automatically - no manual database setup required.
90  
91 The following features were verified to work correctly:
92  
93 =over 4
94  
95 =item * CRUD operations (create, find, update, delete)
96  
97 =item * InflateColumn::DateTime inflation through the async worker path
98  
99 =item * DateTime stringification with correct PostgreSQL-aware formatting
100 via L<DateTime::Format::Pg> (space separator with timezone offset)
101  
102 =back
103  
104 The PostgreSQL test also covers two known bugs that were fixed on the
105 async path (equivalent of DBIx-Class PR#138):
106  
107 =over 4
108  
109 =item * B<BUG 1> - InflateColumn::DateTime not firing through the async
110 worker, returning a plain string instead of a DateTime object.
111  
112 =item * B<BUG 2> - No formatter set on the inflated DateTime object,
113 causing stringification to fall back to bare ISO8601 output instead of
114 PostgreSQL-native format.
115  
116 =back
117  
118 To run the PostgreSQL integration tests:
119  
120 prove -lv t/156-resultset-inflate-datetime.t
121  
122 The test requires L<DBD::Pg>, L<DateTime::Format::Pg>, and
123 L<Test::PostgreSQL::v2> E<gt>= 2.02. If any of these are missing the
124 test skips gracefully.
125  
126 =head2 SQLite
127  
128 Fully supported and used as the primary database for the standard test suite.
129  
130 =head1 QUICK START
131  
132 This example demonstrates how to set up a small C<SQLite> database and
133 perform an asynchronous B<"Create and Count"> operation.
134  
135 use strict;
136 use warnings;
137 use IO::Async::Loop;
138 use DBIx::Class::Async::Schema;
139  
140 my $loop = IO::Async::Loop->new;
141  
142 # 1. Connect to your database
143 my $schema = DBIx::Class::Async::Schema->connect(
144 "dbi:SQLite:dbname=myapp.db", undef, undef, {},
145 {
146 workers => 2, # Keep 2 database connections ready
147 schema_class => 'MyApp::Schema' # Your DBIC Schema name
148 }
149 );
150  
151 # 2. Deploy (Create tables if they don't exist)
152 $schema->await($schema->deploy);
153  
154 # 3. Non-blocking workflow
155 # We don't "wait" for the DB; we tell the loop what to do when it's done.
156 $schema->resultset('User')
157 ->create({ name => 'Starlight', email => 'star@perl.org' })
158 ->then(
159 sub {
160 return $schema->resultset('User')->count;
161 })
162 ->on_done(
163 sub {
164 my $count = shift;
165 print "User saved! Total users now: $count\n";
166 })
167 ->on_fail(
168 sub {
169 warn "Something went wrong: @_\n";
170 });
171  
172 # 4. Start the engine
173 $loop->run;
174  
175 =head1 SYNOPSIS
176  
177 use IO::Async::Loop;
178 use DBIx::Class::Async::Schema;
179  
180 my $loop = IO::Async::Loop->new;
181  
182 # Connect returns a "Virtual Schema" that behaves like DBIC
183 # but returns Futures instead of data.
184 my $schema = DBIx::Class::Async::Schema->connect(
185 "dbi:SQLite:dbname=app.db", undef, undef, {},
186 {
187 workers => 4, # Parallel database connections
188 schema_class => 'My::Schema', # Your standard DBIC Schema
189 async_loop => $loop,
190 }
191 );
192  
193 # 1. Simple CRUD (Returns a Future)
194 my $future = $schema->resultset('User')->find(1);
195  
196 $future->on_done(sub {
197 my $user = shift;
198 print "Found: " . $user->name . "\n" if $user;
199 });
200  
201 # 2. Modern Async/Await style
202 async sub get_user_count {
203 my $count = await $schema->resultset('User')->count;
204 return $count;
205 }
206  
207 # 3. Batch Transactions
208 my $tx = await $schema->txn_do([
209 { action => 'create', resultset => 'User', data => { name => 'Alice' }, name => 'new_user' },
210 { action => 'create', resultset => 'Log', data => { msg => "Created user \$new_user.id" } }
211 ]);
212  
213 =head1 THE ASYNC DESIGN APPROACH
214  
215 The "Real Truth" about L<DBIx::Class> is that it is inherently synchronous. Under the hood, L<DBI> and most database drivers (like L<DBD::SQLite> or L<DBD::mysql>) block the entire Perl process while waiting for the database to respond.
216  
217 =head2 How it used to be (The Old Design)
218  
219 In traditional async Perl, developers often tried to wrap DBIC calls in a simple L<Future>. However, because the underlying L<DBI> call was still blocking, one slow query would "freeze" the entire event loop. Your UI would hang, and other network requests would stop.
220  
221 =head2 How we do it now (The "Bridge & Worker" Design)
222  
223 C<DBIx::Class::Async> uses a B<Worker-Pool Architecture>.
224  
225 =over 4
226  
227 =item * The Bridge (Main Process)
228  
229 When you call C<find>, C<search>, or C<create>, the main process doesn't talk to the database. It packages your request and sends it over a pipe to an available worker. It then immediately returns a L<Future> and goes back to work handling other events.
230  
231 =item * The Workers (Background Processes)
232  
233 We maintain a pool of background processes. Each worker has its own dedicated connection to the database. The worker performs the blocking DBIC call, serialises the result, and sends it back to the Bridge.
234  
235 =item * The Result
236  
237 The Bridge receives the data, resolves the C<Future>, and your code continues.
238  
239 =back
240  
241 =head2 Why this is better:
242  
243 =over 4
244  
245 =item * Zero Loop Freezing
246  
247 Even if a query takes 10 seconds, your main application loop remains 100% responsive.
248  
249 =item * True Parallelism
250  
251 With 4 workers, you can execute 4 heavy database queries simultaneously. Standard DBIC can only do 1 at a time.
252  
253 =item * Automatic Serialisation
254  
255 We handle the complex task of turning "live" DBIC objects into data structures that can safely travel between processes.
256  
257 =back
258  
259 =cut
260  
261 101 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
262 101 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
263 101 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
264  
265 101 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
266  
267 101 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
268 101 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
269 101 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
270 101 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
271 101 ▶use IO::Async::Function;
Subroutine BEGIN: called CC=1 SCAR=0.0
272 101 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
273 101 ▶use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
274 101 ▶use Type::Params qw(compile);
Subroutine BEGIN: called CC=1 SCAR=0.0
275 101 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
276 101 ▶use DBIx::Class::Async::Row;
Subroutine BEGIN: called CC=1 SCAR=0.0
277 101 ▶use Types::Standard qw(Str ScalarRef HashRef ArrayRef Maybe Int CodeRef);
Subroutine BEGIN: called CC=1 SCAR=0.0
278  
279 101 ▶use DBIx::Class::Async::Exception::Factory;
Subroutine BEGIN: called CC=1 SCAR=0.0
280  
281 101 ▶use constant ASYNC_TRACE => $ENV{ASYNC_TRACE} || 0;
Subroutine BEGIN: called CC=2 SCAR=7.1
Condition50%1/2
$ENV{'ASYNC_TRACE'} || 0
l!l
0101
MC/DC0%0/1
$ENV{'ASYNC_TRACE'} || 0
$ENV{'ASYNC_TRACE'}
Truth table50%1/2
A
A= $ENV{'ASYNC_TRACE'}
Aresult
11
00
282 101 our $METRICS;
283  
284 101 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
285 101 DEFAULT_WORKERS => 4,
286 DEFAULT_CACHE_TTL => 0,
287 DEFAULT_QUERY_TIMEOUT => 30,
288 DEFAULT_RETRIES => 3,
289 HEALTH_CHECK_INTERVAL => 300,
290 101 };
291  
292 =head1 METHODS
293  
294 =head2 create_async_db
295  
296 Initialises the async environment and spawns workers.
297  
298 my $db = DBIx::Class::Async->create_async_db(
299 schema_class => 'MyApp::Schema',
300 connect_info => [ 'dbi:SQLite:db.sqlite' ],
301 workers => 4,
302 cache_ttl => 300, # 5 minutes
303 enable_retry => 1,
304 );
305  
306 B<Options:>
307  
308 =over 4
309  
310 =item * C<schema_class> (required) - Your L<DBIx::Class::Schema> class name.
311  
312 =item * C<connect_info> (required) - Arrayref of DBI connect arguments.
313  
314 =item * C<workers> - Number of background worker processes (default: 4).
315  
316 =item * C<loop> or C<async_loop> - An existing L<IO::Async::Loop> instance.
317 Both names are accepted as aliases. If omitted, a new loop is created
318 internally and owned by the async_db (it will be stopped on disconnect).
319  
320 =item * C<cache_ttl> - Default Time-To-Live for cached queries in seconds.
321 Defaults to B<0> (caching B<disabled>). Set a positive integer to enable.
322 B<Warning:> Cached data can become stale; avoid caching queries that use
323 non-deterministic SQL functions like C<NOW()> or C<RAND()>.
324  
325 =item * C<enable_retry> - Automatically retry on transient errors (default: 0).
326  
327 =back
328  
329 =cut
330  
331 119 ▶sub create_async_db {
Subroutine create_async_db: called CC=25 SCAR=35.4
Pod documented
332 119 my ($class, %args) = @_;
333  
334 119 ▶ my $schema_class = $args{schema_class} or croak "schema_class required";
Branch: 1 branch
BranchTrueFalseTotal
my $schema_class = $args{"schema_class"} or croak("schema_class required") 119 0 119
335 119 ▶ my $connect_info = $args{connect_info} or croak "connect_info required";
Branch: 1 branch
BranchTrueFalseTotal
my $connect_info = $args{"connect_info"} or croak("connect_info required") 119 0 119
336 119 ▶ my $workers = $args{workers} || DEFAULT_WORKERS;
Condition50%1/2
$args{'workers'} || 4
l!l
1190
MC/DC0%0/1
$args{'workers'} || 4
$args{'workers'}
Truth table50%1/2
A
A= $args{'workers'}
Aresult
11
00
337  
338 119 ▶ unless (eval { $schema_class->can('connect') } || eval { DBIx::Class::Async::_safe_require_class($schema_class) }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { $schema_class->can("connect") } } or eval { do { _safe_require_class($schema_class) } }) 0 119 119
Condition66%2/3
eval { do { $schema_class->can("connect") } } or eval { do { _safe_require_class($schema_class) } }
l!l&&r!l&&!r
11810
MC/DC0%0/2
eval { do { $schema_class->can("connect") } } or eval { do { _safe_require_class($schema_class) } }
eval { do { $schema_class->can("connect") } } eval { do { _safe_require_class($schema_class) } }
Truth table66%2/3
A or B
A= eval { do { $schema_class->can("connect") } }B= eval { do { _safe_require_class($schema_class) } }
ABresult
1X1
011
000
339 0 croak "Cannot load schema class $schema_class: $@";
340 }
341  
342 my $cache_ttl = exists $args{cache_ttl}
343 ? $args{cache_ttl}
344 119 ▶ : DEFAULT_CACHE_TTL;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'cache_ttl'} ? : 116 3 119
345  
346 # 1. Extract Column Metadata (Inflators/Deflators)
347 # We do this before creating the hashref so we can include it
348 119 my $custom_inflators = {};
349 119 ▶ if ($schema_class->can('sources')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema_class->can("sources")) 119 0 119
350 119 foreach my $source_name ($schema_class->sources) {
351 1180 my $source = $schema_class->source($source_name);
352 1180 foreach my $col ($source->columns) {
353 5074 my $info = $source->column_info($col);
354 5074 ▶ if ($info->{deflate} || $info->{inflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{"deflate"} or $info->{"inflate"}) 0 5074 5074
Condition33%1/3
$info->{"deflate"} or $info->{"inflate"}
l!l&&r!l&&!r
005074
MC/DC0%0/2
$info->{"deflate"} or $info->{"inflate"}
$info->{"deflate"} $info->{"inflate"}
Truth table33%1/3
A or B
A= $info->{"deflate"}B= $info->{"inflate"}
ABresult
1X1
011
000
355 $custom_inflators->{$source_name}{$col} = {
356 deflate => $info->{deflate},
357 inflate => $info->{inflate},
358 0 };
359 }
360 }
361 }
362 }
363  
364 # Save SIGCHLD state before IO::Async installs its handler
365 119 my $old_sigchld = $SIG{CHLD};
366 119 my $user_supplied_loop = exists $args{async_loop};
367  
368 # 2. Build the async_db state hashref
369 my $async_db = {
370 _schema_class => $schema_class,
371 _connect_info => $connect_info,
372 _custom_inflators => $custom_inflators,
373 _loop => $args{async_loop} || IO::Async::Loop->new,
374 _owns_loop => !$user_supplied_loop,
375 _old_sigchld => $old_sigchld,
376 _workers => [],
377 _workers_config => {
378 _count => $workers,
379 _query_timeout => $args{query_timeout} || DEFAULT_QUERY_TIMEOUT,
380 _on_connect_do => $args{on_connect_do} || [],
381 },
382 _cache => $args{cache} || ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef),
383 _cache_ttl => $cache_ttl,
384 _enable_retry => $args{enable_retry} // 0,
385 _retry_config => {
386 _max_retries => $args{max_retries} || DEFAULT_RETRIES,
387 _delay => $args{retry_delay} || 1,
388 _factor => 2,
389 },
390 _enable_metrics => $args{enable_metrics} // 0,
391 _is_connected => 1,
392 _worker_idx => 0,
393 _query_cache => {},
394 _stats => {
395 _queries => 0,
396 _errors => 0,
397 _cache_hits => 0,
398 _cache_misses => 0,
399 _deadlocks => 0,
400 _retries => 0,
401 },
402 119 ▶ _debug => $args{debug} || 0,
Branch: 1 branch
BranchTrueFalseTotal
$cache_ttl > 0 ? : 89 29 118
Condition70%14/20
$args{'async_loop'} || 'IO::Async::Loop'->new
l!l&&r!l&&!r
108110
$args{'query_timeout'} || 30
l!l
0119
$args{'on_connect_do'} || []
l!l
0119
$args{'cache'} || ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef)
l!l&&r!l&&!r
18929
$args{"enable_retry"} // 0
l!l
2117
$args{'max_retries'} || 3
l!l
0119
$args{'retry_delay'} || 1
l!l
0119
$args{"enable_metrics"} // 0
l!l
2117
$args{'debug'} || 0
l!l
0119
MC/DC0%0/2
$args{'async_loop'} || 'IO::Async::Loop'->new
$args{'async_loop'} 'IO::Async::Loop'->new
MC/DC0%0/1
$args{'query_timeout'} || 30
$args{'query_timeout'}
MC/DC0%0/1
$args{'on_connect_do'} || []
$args{'on_connect_do'}
MC/DC100%2/2
$args{'cache'} || ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef)
$args{'cache'} ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef)
MC/DC100%1/1
$args{"enable_retry"} // 0
$args{"enable_retry"}
MC/DC0%0/1
$args{'max_retries'} || 3
$args{'max_retries'}
MC/DC0%0/1
$args{'retry_delay'} || 1
$args{'retry_delay'}
MC/DC100%1/1
$args{"enable_metrics"} // 0
$args{"enable_metrics"}
MC/DC0%0/1
$args{'debug'} || 0
$args{'debug'}
Truth table66%2/3
A || B
A= $args{'async_loop'}B= 'IO::Async::Loop'->new
ABresult
1X1
011
000
Truth table50%1/2
A
A= $args{'query_timeout'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'on_connect_do'}
Aresult
11
00
Truth table100%3/3
A || B
A= $args{'cache'}B= ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef)
ABresult
1X1
011
000
Truth table100%2/2
A
A= $args{"enable_retry"}
Aresult
11
00
Truth table50%1/2
A
A= $args{'max_retries'}
Aresult
11
00
Truth table50%1/2
A
A= $args{'retry_delay'}
Aresult
11
00
Truth table100%2/2
A
A= $args{"enable_metrics"}
Aresult
11
00
Truth table50%1/2
A
A= $args{'debug'}
Aresult
11
00
403 };
404  
405 119 ▶ _init_metrics($async_db) if $async_db->{_enable_metrics};
Branch: 1 branch
BranchTrueFalseTotal
if $async_db->{"_enable_metrics"} 0 119 119
406 119 _init_workers($async_db);
407  
408 119 ▶ if (my $interval = $args{health_check} // HEALTH_CHECK_INTERVAL) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $interval = $args{"health_check"} // 300) 118 1 119
Condition100%2/2
$args{"health_check"} // 300
l!l
1118
MC/DC100%1/1
$args{"health_check"} // 300
$args{"health_check"}
Truth table100%2/2
A
A= $args{"health_check"}
Aresult
11
00
409 118 _start_health_checks($async_db, $interval);
410 }
411  
412 119 return $async_db;
413 }
414  
415 =head2 disconnect
416  
417 Gracefully shuts down all background workers and clears timers. Always call
418 this before your application exits to prevent zombie processes.
419  
420 DBIx::Class::Async->disconnect($db);
421  
422 Internally this performs cleanup in the correct order required by
423 L<IO::Async::Function>: each worker is first removed from the event loop
424 (C<< $loop->remove >>) and then stopped (C<< $function->stop >>). Reversing
425 this order causes C<remove()> to silently fail, leaving orphaned notifiers
426 in the loop's registry that trigger a C<SEGV> during Perl global destruction.
427  
428 =cut
429  
430 119 ▶sub disconnect {
Subroutine disconnect: called CC=12 SCAR=25.3
Pod documented
431 119 my ($db) = @_;
432  
433 119 ▶ return unless $db && ref $db eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $db and ref $db eq "HASH" 0 119 119
Condition33%1/3
$db and ref $db eq "HASH"
!ll&&!rl&&r
00119
MC/DC0%0/2
$db and ref $db eq "HASH"
$db ref $db eq "HASH"
Truth table33%1/3
A and B
A= $dbB= ref $db eq "HASH"
ABresult
0X0
100
111
434 119 ▶ return unless $db->{_loop};
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_loop"} 1 118 119
435  
436 # 1. Clear the health check timer
437 # remove() BEFORE stop() - same ordering rule as workers below.
438 118 ▶ if ($db->{_health_check_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_health_check_timer"}) 116 2 118
439 116 eval { $db->{_loop}->remove($db->{_health_check_timer}) };
440 116 eval { $db->{_health_check_timer}->stop };
441 116 delete $db->{_health_check_timer};
442 }
443  
444 # 2. Remove and stop each worker.
445 #
446 # CRITICAL ORDER: remove() MUST be called BEFORE stop().
447 #
448 # IO::Async::Function::stop() sets an internal {stopping} flag and
449 # begins tearing down IPC channels. Once that flag is set, remove()
450 # silently fails - the notifier stays in the loop's internal registry,
451 # keeping the loop (and its SIGCHLD handler) alive past the point where
452 # we expect them to be freed. During Perl global destruction the loop's
453 # XS destructor then accesses already-freed memory -> SEGV.
454 #
455 # Calling remove() first detaches the Function and all its child
456 # notifiers (Streams, Handles, Processes) cleanly, then stop() signals
457 # the worker processes to exit and returns a Future we can await.
458 118 ▶ if ($db->{_workers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_workers"}) 118 0 118
459 118 my @stop_futures;
460 118 foreach my $worker_info (@{ $db->{_workers} }) {
461 227 ▶ my $instance = $worker_info->{instance} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $instance = $worker_info->{"instance"} or next 227 0 227
462 227 eval { $db->{_loop}->remove($instance) };
463 227 my $f = eval { $instance->stop };
464 227 ▶ push @stop_futures, $f if $f && ref $f;
Branch: 1 branch
BranchTrueFalseTotal
if $f and ref $f 227 0 227
Condition33%1/3
$f and ref $f
!ll&&!rl&&r
00227
MC/DC0%0/2
$f and ref $f
$f ref $f
Truth table33%1/3
A and B
A= $fB= ref $f
ABresult
0X0
100
111
465 }
466 118 $db->{_workers} = [];
467  
468 # Await the stop Futures so worker processes begin their shutdown
469 # sequence before we proceed. stop() returns a Future that resolves
470 # when the IPC channels are closed (not when the OS process exits,
471 # but close enough to prevent the SEGV in the common case).
472 118 ▶ if (@stop_futures) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stop_futures) 117 1 118
473 117 eval { $db->{_loop}->await(Future->needs_all(@stop_futures)) };
474 }
475 }
476  
477 # 3. Clean up global IO::Async state that outlives the loop object.
478 #
479 # IO::Async::Loop maintains a $ONE_TRUE_LOOP singleton and installs a
480 # SIGCHLD handler when workers are forked. Both hold strong references
481 # to the loop object, preventing garbage collection even after all our
482 # Perl-level references are dropped. In global destruction this causes
483 # a SEGV because the loop's XS destructor runs after other XS objects
484 # it depends on have already been freed.
485 #
486 # We only do this when we own the loop (i.e. we created it internally).
487 # For user-supplied loops the caller is responsible for lifecycle.
488 118 ▶ if ($db->{_owns_loop}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_owns_loop"}) 11 107 118
489 11 undef $IO::Async::Loop::ONE_TRUE_LOOP;
490 11 $SIG{CHLD} = $db->{_old_sigchld};
491 }
492  
493 # 4. Final state update
494 118 $db->{_is_connected} = 0;
495  
496 118 return 1;
497 }
498  
499 #
500 #
501 # PRIVATE METHODS
502  
503 1102 ▶sub _call_worker {
Subroutine _call_worker: called CC=9 SCAR=25.4
504 1102 my ($db, $operation, @args) = @_;
505  
506 1102 warn "[PID $$] Bridge - sending '$operation' to worker." if ASYNC_TRACE;
507  
508 # ------------------------------------------------------------------
509 # Derive result_class from the payload so it is available throughout
510 # this method without changing the call signature at 13 call sites.
511 #
512 # Every call site passes a payload hashref as $args[0] containing a
513 # source_name key. We resolve that to a fully-qualified result class
514 # via the schema, which is exactly what the Factory needs for its
515 # relationship-detection logic.
516 # ------------------------------------------------------------------
517 1102 my $result_class;
518 1102 ▶ if ( ref($args[0]) eq 'HASH' && $args[0]->{source_name} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[0] eq "HASH" and $args[0]{"source_name"}) 985 117 1102
Condition100%3/3
ref $args[0] eq "HASH" and $args[0]{"source_name"}
!ll&&!rl&&r
1098985
MC/DC100%2/2
ref $args[0] eq "HASH" and $args[0]{"source_name"}
ref $args[0] eq "HASH" $args[0]{"source_name"}
Truth table100%3/3
A and B
A= ref $args[0] eq "HASH"B= $args[0]{"source_name"}
ABresult
0X0
100
111
519 985 $result_class = eval {
520 $db->{_schema_class}->source( $args[0]->{source_name} )
521 985 ->result_class
522 };
523 # eval failure (unknown source, not yet loaded) leaves $result_class
524 # undef -- both the pre-flight and the Factory handle undef gracefully.
525 }
526  
527 # ------------------------------------------------------------------
528 # Pre-flight: catch undef relationship keys before hitting the worker.
529 # Returns a failed Future immediately so the caller's ->then/->catch
530 # chain handles it the same way as any other async error.
531 # ------------------------------------------------------------------
532 1102 ▶ if ( $result_class && ref($args[0]) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($result_class and ref $args[0] eq "HASH") 985 117 1102
Condition66%2/3
$result_class and ref $args[0] eq "HASH"
!ll&&!rl&&r
1170985
MC/DC50%1/2
$result_class and ref $args[0] eq "HASH"
$result_class ref $args[0] eq "HASH"
Truth table66%2/3
A and B
A= $result_classB= ref $args[0] eq "HASH"
ABresult
0X0
100
111
533 my $data_hashref = $args[0]->{data} # create / populate
534 985 ▶ // $args[0]->{updates}; # update
Condition100%3/3
$args[0]{"data"} // $args[0]{"updates"}
l!l&&r!l&&!r
50635444
MC/DC100%2/2
$args[0]{"data"} // $args[0]{"updates"}
$args[0]{"data"} $args[0]{"updates"}
Truth table100%3/3
A // B
A= $args[0]{"data"}B= $args[0]{"updates"}
ABresult
1X1
011
000
535  
536 985 ▶ if ( ref($data_hashref) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data_hashref eq "HASH") 519 466 985
537 my $exception = DBIx::Class::Async::Exception::Factory->validate_or_fail(
538 args => $data_hashref,
539 schema => $db->{_schema_class},
540 519 result_class => $result_class,
541 operation => $operation,
542 );
543 519 ▶ return Future->fail($exception) if $exception;
Branch: 1 branch
BranchTrueFalseTotal
if $exception 0 519 519
544 }
545 }
546  
547 1102 my $worker = _next_worker($db);
548  
549 my $worker_future = $worker->call(
550 args => [
551 $db->{_schema_class},
552 $db->{_connect_info},
553 $db->{_workers_config},
554 $operation,
555 @args,
556 1102 ▶ $db->{_debug} || 0,
Condition50%1/2
$db->{'_debug'} || 0
l!l
01102
MC/DC0%0/1
$db->{'_debug'} || 0
$db->{'_debug'}
Truth table50%1/2
A
A= $db->{'_debug'}
Aresult
11
00
557 ],
558 );
559  
560 # ------------------------------------------------------------------
561 # Shared helper: translate any raw error (string, DBIC exception, or
562 # already-typed exception) into a DBIx::Class::Async::Exception.
563 # If the error is already one of ours, pass it through untouched.
564 # ------------------------------------------------------------------
565 6 ▶ my $make_exception = sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
566 6 my ($raw) = @_;
567 6 ▶ return $raw
Branch: 1 branch
BranchTrueFalseTotal
if ref $raw and $raw->isa("DBIx::Class::Async::Exception") 0 6 6
Condition66%2/3
ref $raw and $raw->isa("DBIx::Class::Async::Exception")
!ll&&!rl&&r
510
MC/DC0%0/2
ref $raw and $raw->isa("DBIx::Class::Async::Exception")
ref $raw $raw->isa("DBIx::Class::Async::Exception")
Truth table66%2/3
A and B
A= ref $rawB= $raw->isa("DBIx::Class::Async::Exception")
ABresult
0X0
100
111
568 if ref $raw && $raw->isa('DBIx::Class::Async::Exception');
569 return DBIx::Class::Async::Exception::Factory->make_from_dbic_error(
570 error => $raw,
571 schema => $db->{_schema_class},
572 6 result_class => $result_class,
573 operation => $operation,
574 );
575 1102 };
576  
577 1102 ▶ return $worker_future->followed_by(sub {
Subroutine __ANON__: called CC=7 SCAR=28.0
578 1102 my ($f) = @_;
579  
580 # ------------------------------------------------------------------
581 # Worker future failed outright
582 # ------------------------------------------------------------------
583 1102 ▶ if ( $f->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f->is_failed) 0 1102 1102
584 0 $db->{_stats}->{_errors}++;
585 0 return Future->fail( $make_exception->( $f->failure ) );
586 }
587  
588 1102 my $result = ($f->get)[0];
589  
590 # ------------------------------------------------------------------
591 # Result is itself a Future -- unwrap it
592 # ------------------------------------------------------------------
593 1102 ▶ if ( Scalar::Util::blessed($result) && $result->isa('Future') ) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($result) and $result->isa("Future")) 0 1102 1102
Condition33%1/3
builtin::blessed($result) and $result->isa("Future")
!ll&&!rl&&r
110200
MC/DC0%0/2
builtin::blessed($result) and $result->isa("Future")
builtin::blessed($result) $result->isa("Future")
Truth table33%1/3
A and B
A= builtin::blessed($result)B= $result->isa("Future")
ABresult
0X0
100
111
594 0 ▶ return $result->followed_by(sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
595 0 my ($inner_f) = @_;
596  
597 0 ▶ if ( $inner_f->is_failed ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inner_f->is_failed) 0 0 0
598 0 $db->{_stats}->{_errors}++;
599 0 return Future->fail( $make_exception->( $inner_f->failure ) );
600 }
601  
602 0 my $inner_result = ($inner_f->get)[0];
603  
604 0 ▶ if ( ref($inner_result) eq 'HASH' && exists $inner_result->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $inner_result eq "HASH" and exists $inner_result->{"error"}) 0 0 0
Condition0%0/3
ref $inner_result eq "HASH" and exists $inner_result->{"error"}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $inner_result eq "HASH" and exists $inner_result->{"error"}
ref $inner_result eq "HASH" exists $inner_result->{"error"}
Truth table0%0/3
A and B
A= ref $inner_result eq "HASH"B= exists $inner_result->{"error"}
ABresult
0X0
100
111
605 0 $db->{_stats}->{_errors}++;
606 0 return Future->fail( $make_exception->( $inner_result->{error} ) );
607 }
608  
609 0 ▶ $db->{_stats}->{_queries}++
Branch: 1 branch
BranchTrueFalseTotal
unless $operation =~ /^(?:ping|health_check|deploy)$/u 0 0 0
610 unless $operation =~ /^(?:ping|health_check|deploy)$/;
611 0 return Future->done($inner_result);
612 0 });
613 }
614  
615 # ------------------------------------------------------------------
616 # Non-Future result -- check for worker error hashref
617 # ------------------------------------------------------------------
618 1102 ▶ if ( ref($result) eq 'HASH' && exists $result->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH" and exists $result->{"error"}) 6 1096 1102
Condition100%3/3
ref $result eq "HASH" and exists $result->{"error"}
!ll&&!rl&&r
4985986
MC/DC100%2/2
ref $result eq "HASH" and exists $result->{"error"}
ref $result eq "HASH" exists $result->{"error"}
Truth table100%3/3
A and B
A= ref $result eq "HASH"B= exists $result->{"error"}
ABresult
0X0
100
111
619 6 $db->{_stats}->{_errors}++;
620 6 return Future->fail( $make_exception->( $result->{error} ) );
621 }
622  
623 1096 ▶ $db->{_stats}->{_queries}++
Branch: 1 branch
BranchTrueFalseTotal
unless $operation =~ /^(?:ping|health_check|deploy)$/u 992 104 1096
624 unless $operation =~ /^(?:ping|health_check|deploy)$/;
625 1096 return Future->done($result);
626 1102 });
627 }
628  
629 119 ▶sub _init_workers {
Subroutine _init_workers: called CC=2 SCAR=17.2
630 119 my $db = shift;
631  
632 119 for my $worker_id (1..$db->{_workers_config}{_count}) {
633 my $worker = IO::Async::Function->new(
634 0 ▶ code => sub {
Subroutine __ANON__: not called CC=13 SCAR=51.4
635 101 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
636 101 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
637 101 ▶ use feature 'state';
Subroutine BEGIN: called CC=1 SCAR=0.0
638  
639  
640 0 my ($schema_class, $connect_info, $worker_config, $operation, $payload, $debug_flag) = @_;
641  
642 0 ▶ $debug_flag ||= 0;
Condition0%0/2
$debug_flag ||= 0
l!l
00
MC/DC0%0/1
$debug_flag ||= 0
$debug_flag
Truth table0%0/2
A
A= $debug_flag
Aresult
11
00
643  
644 0 if (ASYNC_TRACE) {
645 warn "[PID $$] Worker CODE block started";
646 warn "[PID $$] Worker received " . scalar(@_) . " arguments";
647 warn "[PID $$] Schema class: $schema_class";
648 warn "[PID $$] Operation: $operation";
649 warn "[PID $$] Debug flag: $debug_flag";
650 warn "[PID $$] STAGE 4 (Worker): Received operation: $operation";
651 }
652  
653 0 my $deflator;
654 0 ▶ $deflator = sub {
Subroutine __ANON__: not called CC=7 SCAR=40.3
655 0 my ($data) = @_;
656 0 ▶ return $data unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 0 0
657  
658 0 ▶ if ( eval { $data->isa('DBIx::Class::Row') } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $data->isa("DBIx::Class::Row") } }) 0 0 0
659 0 my %cols = $data->get_inflated_columns;
660 # Recurse for prefetched relations
661 0 foreach my $k (keys %cols) {
662 0 ▶ if (ref $cols{$k}) { $cols{$k} = $deflator->($cols{$k}) }
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cols{$k}) 0 0 0
663 }
664 0 return \%cols;
665 }
666  
667 0 ▶ if ( eval { $data->isa('DBIx::Class::ResultSet') } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (eval { do { $data->isa("DBIx::Class::ResultSet") } }) 0 0 0
668 0 return [ map { $deflator->($_) } $data->all ];
669 }
670 0 ▶ if ( ref($data) eq 'ARRAY' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "ARRAY") 0 0 0
671 0 return [ map { $deflator->($_) } @$data ];
672 }
673  
674 0 return $data;
675 0 };
676  
677 0 ▶ my $log_sql = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
678 0 my ($debug_enabled, $sql, $bind) = @_;
679 0 ▶ return unless $debug_enabled;
Branch: 1 branch
BranchTrueFalseTotal
unless $debug_enabled 0 0 0
680  
681 # Log to STDERR in the worker process
682 # The parent's debugobj won't be accessible in the worker
683 0 warn "SQL: $sql\n";
684 0 ▶ if ($bind && @$bind) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bind and @$bind) 0 0 0
Condition0%0/3
$bind and @$bind
!ll&&!rl&&r
000
MC/DC0%0/2
$bind and @$bind
$bind @$bind
Truth table0%0/3
A and B
A= $bindB= @$bind
ABresult
0X0
100
111
685 0 ▶ warn "BIND: " . join(", ", map { defined $_ ? "'$_'" : "NULL" } @$bind) . "\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $_ ? : 0 0 0
686 }
687 0 };
688  
689 # Create or reuse schema connection
690 0 state $schema_cache = {};
691 0 my $pid = $$;
692  
693 0 warn "[PID $$] Checking schema cache for PID $pid" if ASYNC_TRACE;
694  
695 0 ▶ unless (exists $schema_cache->{$pid}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $schema_cache->{$pid}) 0 0 0
696 0 if (ASYNC_TRACE) {
697 warn "[PID $$] Worker initialising new schema connection";
698 warn "[PID $$] About to require $schema_class";
699 }
700  
701  
702 # Load schema class in worker process
703 0 my $require_result = eval { _safe_require_class($schema_class); 1 };
704 0 ▶ if (!$require_result || $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $require_result or $@) 0 0 0
Condition0%0/3
not $require_result or $@
l!l&&r!l&&!r
000
MC/DC0%0/2
not $require_result or $@
not $require_result $@
Truth table0%0/3
not(A) or B
A= not $require_resultB= $@
ABresult
1X1
011
000
705 0 ▶ my $err = $@ || 'Unknown error';
Condition0%0/2
$@ || 'Unknown error'
l!l
00
MC/DC0%0/1
$@ || 'Unknown error'
$@
Truth table0%0/2
A
A= $@
Aresult
11
00
706 0 warn "[PID $$] FAILED to load schema class: $err"
707 if ASYNC_TRACE;
708 0 die "Worker Load Fail: $err";
709 }
710  
711 0 warn "[PID $$] Schema class loaded successfully"
712 if ASYNC_TRACE;
713  
714 0 ▶ unless ($schema_class->can('connect')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema_class->can("connect")) 0 0 0
715 0 warn "[PID $$] Schema class has no 'connect' method!"
716 if ASYNC_TRACE;
717 0 die "Schema class $schema_class does not provide 'connect' method";
718 }
719  
720 0 warn "[PID $$] Attempting database connection..."
721 if ASYNC_TRACE;
722  
723 # Connect to database
724 0 my $schema = eval { $schema_class->connect(@$connect_info); };
725 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
726 0 warn "[PID $$] Database connection FAILED: $@"
727 if ASYNC_TRACE;
728 0 die "Failed to connect to database: $@";
729 }
730 0 ▶ unless (defined $schema) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $schema) 0 0 0
731 0 warn "[PID $$] Schema connection returned undef!"
732 if ASYNC_TRACE;
733 0 die "Schema connection returned undef";
734 }
735  
736 0 ▶ if ($debug_flag && $schema->storage) {
Branch: 1 branch
BranchTrueFalseTotal
if ($debug_flag and $schema->storage) 0 0 0
Condition0%0/3
$debug_flag and $schema->storage
!ll&&!rl&&r
000
MC/DC0%0/2
$debug_flag and $schema->storage
$debug_flag $schema->storage
Truth table0%0/3
A and B
A= $debug_flagB= $schema->storage
ABresult
0X0
100
111
737 0 $schema->storage->debug($debug_flag);
738 0 warn "[PID $$] Worker storage debug enabled at level $debug_flag"
739 if ASYNC_TRACE;
740 }
741  
742 # https://github.com/manwar/DBIx-Class-Async/issues/9
743 #
744 # When the worker process exits, Perl tries to clean up
745 # the database handle. But the parent process also has a
746 # reference to what it thinks is the same handle (it's
747 # not, it's a fork). Without InactiveDestroy, both
748 # processes try to close the connection, causing:
749 #
750 # 1) Parent closes connection
751 # 2) Worker tries to close same connection -> SEGV
752 # (trying to free already-freed memory)
753 #
754 # InactiveDestroy = 1 tells DBI: "This handle was
755 # inherited from a fork, don't close it when the child
756 # exits"
757  
758 0 ▶ if ($schema->storage && $schema->storage->dbh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema->storage and $schema->storage->dbh) 0 0 0
Condition0%0/3
$schema->storage and $schema->storage->dbh
!ll&&!rl&&r
000
MC/DC0%0/2
$schema->storage and $schema->storage->dbh
$schema->storage $schema->storage->dbh
Truth table0%0/3
A and B
A= $schema->storageB= $schema->storage->dbh
ABresult
0X0
100
111
759 0 $schema->storage->dbh->{InactiveDestroy} = 1;
760 0 $schema->storage->dbh->{AutoInactiveDestroy} = 1;
761 0 warn "[PID $$] Set InactiveDestroy on worker database handle"
762 if ASYNC_TRACE;
763 }
764  
765 0 warn "[PID $$] Database connected successfully"
766 if ASYNC_TRACE;
767  
768 0 $schema_cache->{$pid} = $schema;
769  
770 0 warn "[PID $$] Worker initialisation complete"
771 if ASYNC_TRACE;
772 }
773  
774 0 warn "[PID $$] STAGE 5 (Worker): Executing operation: $operation"
775 if ASYNC_TRACE;
776  
777 0 ▶ my $result = try {
Subroutine __ANON__: not called CC=40 SCAR=74.0
778 0 my $schema = $schema_cache->{$pid};
779  
780 0 warn "[PID $$] Schema from cache: " . (defined $schema ? ref($schema) : "UNDEF")
781 if ASYNC_TRACE;
782  
783 0 ▶ if ($operation =~ /^(count|sum|max|min|avg|average)$/) {
Branch: 14 branches
BranchTrueFalseTotal
if ($operation =~ /^(count|sum|max|min|avg|average)$/u) { } 0 0 0
elsif ($operation eq 'search' or $operation eq 'all') { } 0 0 0
elsif ($operation eq 'update') { } 0 0 0
elsif ($operation eq 'create') { } 0 0 0
elsif ($operation eq 'delete') { } 0 0 0
elsif ($operation =~ /^populate(?:_bulk)?$/u) { } 0 0 0
elsif ($operation eq 'find') { } 0 0 0
elsif ($operation eq 'deploy') { } 0 0 0
elsif ($operation eq 'txn_batch') { } 0 0 0
elsif ($operation eq 'txn_do') { } 0 0 0
elsif ($operation eq 'txn_begin') { } 0 0 0
elsif ($operation eq 'txn_commit') { } 0 0 0
elsif ($operation eq 'txn_rollback') { } 0 0 0
elsif ($operation eq 'ping' or $operation eq 'health_check') { } 0 0 0
784 0 warn "[PID $$] STAGE 6 (Worker): Performing aggregate $operation"
785 if ASYNC_TRACE;
786  
787 0 my $source_name = $payload->{source_name};
788 0 ▶ my $cond = $payload->{cond} // {};
Condition0%0/2
$payload->{"cond"} // {}
l!l
00
MC/DC0%0/1
$payload->{"cond"} // {}
$payload->{"cond"}
Truth table0%0/2
A
A= $payload->{"cond"}
Aresult
11
00
789 0 ▶ my $attrs = $payload->{attrs} // {};
Condition0%0/2
$payload->{"attrs"} // {}
l!l
00
MC/DC0%0/1
$payload->{"attrs"} // {}
$payload->{"attrs"}
Truth table0%0/2
A
A= $payload->{"attrs"}
Aresult
11
00
790 0 my $column = $payload->{column};
791  
792 0 my $rs = $schema->resultset($source_name)->search($cond, $attrs);
793  
794 # Use eval to catch DBIC errors (e.g., column doesn't exist)
795 0 my $val = eval {
796 0 ▶ if ($operation eq 'count') {
Branch: 1 branch
BranchTrueFalseTotal
if ($operation eq "count") 0 0 0
797 0 ▶ return $column ? $rs->get_column($column)->func('COUNT') : $rs->count;
Branch: 1 branch
BranchTrueFalseTotal
$column ? : 0 0 0
798 }
799  
800 0 ▶ if ($operation =~ /^(avg|average)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($operation =~ /^(avg|average)$/u) 0 0 0
801 0 return $rs->get_column($column)->func('AVG');
802 }
803  
804 0 return $rs->get_column($column)->$operation;
805 };
806  
807 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
808 0 warn "[PID $$] WORKER ERROR: $@" if ASYNC_TRACE;
809 0 return { error => $@ };
810 }
811 else {
812 # IMPORTANT: Force to scalar to avoid HASH(0x...) in Parent
813 # This stringifies potential Math::BigInt objects or references
814 0 warn "[PID $$] $operation complete: $val"
815 if ASYNC_TRACE;
816 0 ▶ return defined $val ? "$val" : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 0 0 0
817 }
818 }
819 ▶ elsif ($operation eq 'search' || $operation eq 'all') {
Condition0%0/3
$operation eq "search" or $operation eq "all"
l!l&&r!l&&!r
000
MC/DC0%0/2
$operation eq "search" or $operation eq "all"
$operation eq "search" $operation eq "all"
Truth table0%0/3
A or B
A= $operation eq "search"B= $operation eq "all"
ABresult
1X1
011
000
820 0 my $source_name = $payload->{source_name};
821 0 ▶ my $attrs = $payload->{attrs} || {};
Condition0%0/2
$payload->{'attrs'} || {}
l!l
00
MC/DC0%0/1
$payload->{'attrs'} || {}
$payload->{'attrs'}
Truth table0%0/2
A
A= $payload->{'attrs'}
Aresult
11
00
822  
823 # Force collapse so DBIC merges the JOINed rows into nested objects
824 0 ▶ $attrs->{collapse} = 1 if $attrs->{prefetch};
Branch: 1 branch
BranchTrueFalseTotal
if $attrs->{"prefetch"} 0 0 0
825  
826 0 my $rs = $schema->resultset($source_name)->search($payload->{cond}, $attrs);
827 0 my @rows = $rs->all;
828  
829 # Use your proven old-design logic here
830 return [
831 0 map { _serialise_row_with_prefetch($_, $attrs->{prefetch}, {}) } @rows
832 ];
833 }
834 elsif ($operation eq 'update') {
835 0 my $source_name = $payload->{source_name};
836 0 my $cond = $payload->{cond};
837 0 my $updates = $payload->{updates};
838  
839 0 ▶ if (!$updates || !keys %$updates) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $updates && keys %$updates) { } 0 0 0
Condition0%0/3
$updates && keys %$updates
!ll&&!rl&&r
000
MC/DC0%0/2
$updates && keys %$updates
$updates keys %$updates
Truth table0%0/3
A && B
A= $updatesB= keys %$updates
ABresult
0X0
100
111
840 0 return 0;
841 }
842 else {
843 0 return $schema->resultset($source_name)
844 ->search($cond)
845 ->update($updates);
846 }
847 }
848 elsif ($operation eq 'create') {
849 0 my $source_name = $payload->{source_name};
850 0 my $data = $payload->{data};
851  
852 # Perform the actual DBIC insert
853 0 my $row = $schema->resultset($source_name)->create($data);
854  
855 # Sync with DB to get the Auto-Increment ID
856 # Some DBD drivers need this to populate the primary key in the object
857 0 $row->discard_changes;
858  
859 0 my %raw = $row->get_columns;
860 0 my %clean_data;
861 0 for my $key (keys %raw) {
862 # Force stringification/numification to strip any DBIC internal "magic"
863 0 ▶ $clean_data{$key} = defined $raw{$key} ? "$raw{$key}" : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $raw{$key} ? : 0 0 0
864 }
865 0 return \%clean_data;
866 }
867 elsif ($operation eq 'delete') {
868 0 my $source_name = $payload->{source_name};
869 0 my $cond = $payload->{cond};
870  
871 # Direct delete on the resultset matching the condition
872 0 return $schema->resultset($source_name)->search($cond)->delete + 0;
873 }
874 elsif ($operation =~ /^populate(?:_bulk)?$/) {
875 0 my $source_name = $payload->{source_name};
876 0 my $data = $payload->{data};
877  
878 0 my $val = eval {
879 0 my $rs = $schema->resultset($source_name);
880  
881 0 ▶ if ($operation eq 'populate') {
Branch: 1 branch
BranchTrueFalseTotal
if ($operation eq 'populate') { } 0 0 0
882 # Standard populate can return objects.
883 # We inflate them to HashRefs to pass back.
884 0 my @rows = $rs->populate($data);
885 0 return [ map { _serialise_row_with_prefetch($_, undef, {}) } @rows ];
886 }
887 else {
888 # populate_bulk is for speed; typically returns a count or truthy
889 0 $rs->populate($data); # DBIC void context usually
890 0 return 1;
891 }
892 };
893  
894 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
895 0 warn "[PID $$] WORKER ERROR: $@" if ASYNC_TRACE;
896 0 return { error => "$@" };
897 }
898 else {
899 0 return $val;
900 }
901 }
902 elsif ($operation eq 'find') {
903 0 my $source_name = $payload->{source_name};
904 0 my $query = $payload->{query};
905 0 ▶ my $attrs = $payload->{attrs} || {};
Condition0%0/2
$payload->{'attrs'} || {}
l!l
00
MC/DC0%0/1
$payload->{'attrs'} || {}
$payload->{'attrs'}
Truth table0%0/2
A
A= $payload->{'attrs'}
Aresult
11
00
906  
907 0 my $row = $schema->resultset($source_name)->find($query, $attrs);
908  
909 0 ▶ if ($row) {
Branch: 1 branch
BranchTrueFalseTotal
if ($row) { } 0 0 0
910 0 return _serialise_row_with_prefetch($row, undef, $attrs);
911 }
912 else {
913 0 return;
914 }
915 }
916 elsif ($operation eq 'deploy') {
917 0 ▶ my ($sqlt_args, $dir) = (ref $payload eq 'ARRAY') ? @$payload : ($payload);
Branch: 1 branch
BranchTrueFalseTotal
ref $payload eq 'ARRAY' ? : 0 0 0
918 0 eval {
919 0 ▶ $schema->deploy($sqlt_args // {}, $dir);
Condition0%0/2
$sqlt_args // {}
l!l
00
MC/DC0%0/1
$sqlt_args // {}
$sqlt_args
Truth table0%0/2
A
A= $sqlt_args
Aresult
11
00
920 };
921 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
922 0 return { error => "Deploy operation failed: $@" };
923 }
924 else {
925 0 return { success => 1 };
926 }
927 }
928 elsif ($operation eq 'txn_batch') {
929 0 my $operations = $payload;
930  
931 0 my $batch_result = eval {
932 0 ▶ $schema->txn_do(sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
933 0 my $success_count = 0;
934 0 foreach my $op (@$operations) {
935 0 my $type = $op->{type};
936 0 my $rs_name = $op->{resultset};
937  
938 0 ▶ if ($type eq 'update') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'update') { } 0 0 0
elsif ($type eq 'create') { } 0 0 0
elsif ($type eq 'delete') { } 0 0 0
elsif ($type eq 'raw') { } 0 0 0
939 0 my $row = $schema->resultset($rs_name)->find($op->{id});
940 0 ▶ die "Record not found for update: $rs_name ID $op->{id}\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
941 unless $row;
942 0 $row->update($op->{data});
943 0 $success_count++;
944 }
945 elsif ($type eq 'create') {
946 0 $schema->resultset($rs_name)->create($op->{data});
947 0 $success_count++;
948 }
949 elsif ($type eq 'delete') {
950 0 my $row = $schema->resultset($rs_name)->find($op->{id});
951 0 ▶ die "Record not found for delete: $rs_name ID $op->{id}\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
952 unless $row;
953 0 $row->delete;
954 0 $success_count++;
955 }
956 elsif ($type eq 'raw') {
957 0 ▶ $schema->storage->dbh->do($op->{sql}, undef, @{$op->{bind} || []});
Condition0%0/2
$op->{'bind'} || []
l!l
00
MC/DC0%0/1
$op->{'bind'} || []
$op->{'bind'}
Truth table0%0/2
A
A= $op->{'bind'}
Aresult
11
00
958 0 $success_count++;
959 }
960 else {
961 0 die "Unknown operation type: $type\n";
962 }
963 }
964 0 return { count => $success_count, success => 1 };
965 0 });
966 };
967  
968 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) { } 0 0 0
969 0 return { error => "Batch Transaction Aborted: $@", success => 0 };
970 }
971 else {
972 0 return $batch_result;
973 }
974 }
975 elsif ($operation eq 'txn_do') {
976 0 my $steps = $payload;
977 0 my %register;
978  
979 0 my $txn_result = eval {
980 0 ▶ $schema->txn_do(sub {
Subroutine __ANON__: not called CC=15 SCAR=54.8
981 0 my @step_results;
982  
983 0 foreach my $step (@$steps) {
984 0 ▶ next unless $step && ref $step eq 'HASH'; # Skip empty/invalid steps
Branch: 1 branch
BranchTrueFalseTotal
unless $step and ref $step eq "HASH" 0 0 0
Condition0%0/3
$step and ref $step eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$step and ref $step eq "HASH"
$step ref $step eq "HASH"
Truth table0%0/3
A and B
A= $stepB= ref $step eq "HASH"
ABresult
0X0
100
111
985 0 ▶ next unless $step->{action}; # Skip steps with no action
Branch: 1 branch
BranchTrueFalseTotal
unless $step->{"action"} 0 0 0
986  
987 # 1. Resolve variables from previous steps
988 # e.g., changing '$user_id' to the actual ID found in step 1
989 0 _resolve_placeholders($step, \%register);
990  
991 # my $rs = $schema->resultset($step->{resultset});
992 0 my $action = $step->{action};
993 0 my $result_data;
994  
995 0 ▶ if ($action eq 'raw') {
Branch: 1 branch
BranchTrueFalseTotal
if ($action eq 'raw') { } 0 0 0
996 # Raw SQL bypasses the Resultset layer
997 0 my $dbh = $schema->storage->dbh;
998 0 ▶ $dbh->do($step->{sql}, undef, @{$step->{bind} || []});
Condition0%0/2
$step->{'bind'} || []
l!l
00
MC/DC0%0/1
$step->{'bind'} || []
$step->{'bind'}
Truth table0%0/2
A
A= $step->{'bind'}
Aresult
11
00
999 0 $result_data = { success => 1 };
1000 }
1001 else {
1002 # CRUD operations require a Resultset
1003 my $rs_name = $step->{resultset}
1004 0 ▶ or die "txn_do: action '$action' requires a 'resultset' parameter";
Branch: 1 branch
BranchTrueFalseTotal
my $rs_name = $step->{"resultset"} or die "txn_do: action '${action}' requires a 'resultset' parameter" 0 0 0
1005 0 my $rs = $schema->resultset($rs_name);
1006  
1007 0 ▶ if ($action eq 'create') {
Branch: 3 branches
BranchTrueFalseTotal
if ($action eq 'create') { } 0 0 0
elsif ($action eq 'find') { } 0 0 0
elsif ($action eq 'update') { } 0 0 0
1008 0 my $row = $rs->create($step->{data});
1009 0 $result_data = { id => $row->id, data => { $row->get_columns } };
1010 }
1011 elsif ($action eq 'find') {
1012 0 my $row = $rs->find($step->{id});
1013 0 ▶ die "txn_do: record not found" unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
1014 0 $result_data = { id => $row->id, data => { $row->get_columns } };
1015 }
1016 elsif ($action eq 'update') {
1017 0 my $row = $rs->find($step->{id});
1018 0 ▶ die "txn_do: record not found for update" unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
1019 0 $row->update($step->{data});
1020 0 $result_data = { success => 1, id => $row->id };
1021 }
1022 }
1023  
1024 0 ▶ if ($step->{name} && $result_data->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($step->{"name"} and $result_data->{"id"}) 0 0 0
Condition0%0/3
$step->{"name"} and $result_data->{"id"}
!ll&&!rl&&r
000
MC/DC0%0/2
$step->{"name"} and $result_data->{"id"}
$step->{"name"} $result_data->{"id"}
Truth table0%0/3
A and B
A= $step->{"name"}B= $result_data->{"id"}
ABresult
0X0
100
111
1025 0 $register{ '$' . $step->{name} . '.id' } = $result_data->{id};
1026 }
1027 0 push @step_results, $result_data;
1028 }
1029 0 return { results => \@step_results, success => 1 };
1030 0 });
1031 };
1032  
1033 0 ▶ return $@ ? { error => "Transaction failed: $@", success => 0 }
Branch: 1 branch
BranchTrueFalseTotal
$@ ? : 0 0 0
1034 : $txn_result;
1035 }
1036 elsif ($operation eq 'txn_begin') {
1037 0 $schema->storage->txn_begin;
1038 0 return { success => 1 };
1039 }
1040 elsif ($operation eq 'txn_commit') {
1041 0 $schema->storage->txn_commit;
1042 0 return { success => 1 };
1043 }
1044 elsif ($operation eq 'txn_rollback') {
1045 0 $schema->storage->txn_rollback;
1046 0 return { success => 1 };
1047 }
1048 ▶ elsif ($operation eq 'ping' || $operation eq 'health_check') {
Condition0%0/3
$operation eq "ping" or $operation eq "health_check"
l!l&&r!l&&!r
000
MC/DC0%0/2
$operation eq "ping" or $operation eq "health_check"
$operation eq "ping" $operation eq "health_check"
Truth table0%0/3
A or B
A= $operation eq "ping"B= $operation eq "health_check"
ABresult
1X1
011
000
1049 0 my $alive = eval { $schema->storage->dbh->do("SELECT 1") };
1050 0 ▶ return { success => ($alive ? 1 : 0), status => "pong" };
Branch: 1 branch
BranchTrueFalseTotal
$alive ? : 0 0 0
1051 }
1052 else {
1053 0 die "Unknown operation: $operation";
1054 }
1055 }
1056 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1057 0 warn "[PID $$] Worker execution error: $_"
1058 if ASYNC_TRACE;
1059 0 return { error => "$_", success => 0 };
1060 0 };
1061  
1062 0 my $safe_result = $deflator->($result);
1063 0 if (ASYNC_TRACE) {
1064 warn "[PID $$] Worker returning result type: " . ref($safe_result);
1065 warn "[PID $$] Worker returning: $safe_result";
1066 }
1067 0 return $safe_result;
1068 },
1069 231 max_workers => 1,
1070 );
1071  
1072 231 $db->{_loop}->add($worker);
1073  
1074 231 push @{$db->{_workers}}, {
1075 instance => $worker,
1076 healthy => 1,
1077 pid => undef,
1078 };
1079 }
1080 }
1081  
1082 0 ▶sub _init_metrics {
Subroutine _init_metrics: not called CC=2 SCAR=17.9
1083 0 my $db = shift;
1084  
1085 # Try to load Metrics::Any
1086 0 eval {
1087 0 require Metrics::Any;
1088 0 Metrics::Any->import('$METRICS');
1089  
1090 # Initialise metrics
1091 0 $METRICS->make_counter('db_async_queries_total');
1092 0 $METRICS->make_counter('db_async_cache_hits_total');
1093 0 $METRICS->make_counter('db_async_cache_misses_total');
1094 0 $METRICS->make_histogram('db_async_query_duration_seconds');
1095 0 $METRICS->make_gauge('db_async_workers_active');
1096  
1097 };
1098  
1099 # Silently ignore if Metrics::Any is not available
1100 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
1101 0 $db->{_enable_metrics} = 0;
1102 0 undef $METRICS;
1103 }
1104 }
1105  
1106 1106 ▶sub _next_worker {
Subroutine _next_worker: called CC=6 SCAR=18.1
1107 1106 my ($db) = @_;
1108  
1109 1106 ▶ return unless $db->{_workers} && @{$db->{_workers}};
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_workers"} and @{$db->{"_workers"};} 0 1106 1106
Condition33%1/3
$db->{"_workers"} and @{$db->{"_workers"};}
!ll&&!rl&&r
001106
MC/DC0%0/2
$db->{"_workers"} and @{$db->{"_workers"};}
$db->{"_workers"} @{$db->{"_workers"};}
Truth table33%1/3
A and B
A= $db->{"_workers"}B= @{$db->{"_workers"};}
ABresult
0X0
100
111
1110  
1111 # Find the next healthy worker using round-robin
1112 # starting at current index
1113 1106 my $count = @{$db->{_workers}};
1114 1106 ▶ my $start = $db->{_worker_idx} // 0;
Condition50%1/2
$db->{"_worker_idx"} // 0
l!l
11060
MC/DC0%0/1
$db->{"_worker_idx"} // 0
$db->{"_worker_idx"}
Truth table50%1/2
A
A= $db->{"_worker_idx"}
Aresult
11
00
1115  
1116 1106 ▶ for (my $i = 0; $i < $count; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $count) 1109 1 1110
1117 1109 my $idx = ($start + $i) % $count;
1118 1109 my $worker_info = $db->{_workers}[$idx];
1119  
1120 1109 ▶ if ($worker_info->{healthy}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($worker_info->{"healthy"}) 1105 4 1109
1121 1105 $db->{_worker_idx} = ($idx + 1) % $count;
1122 1105 return $worker_info->{instance};
1123 }
1124 }
1125  
1126 # Fallback to standard round-robin if all marked
1127 # unhealthy (allows attempt to re-ping)
1128 1 my $idx = $start % $count;
1129 1 my $worker = $db->{_workers}[$idx];
1130 1 $db->{_worker_idx} = ($idx + 1) % $count;
1131  
1132 1 return $worker->{instance};
1133 }
1134  
1135 118 ▶sub _start_health_checks {
Subroutine _start_health_checks: called CC=3 SCAR=11.5
1136 118 my ($db, $interval) = @_;
1137  
1138 118 ▶ return if $interval <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $interval <= 0 0 118 118
1139  
1140 # Try to create the timer
1141 118 eval {
1142 118 require IO::Async::Timer::Periodic;
1143  
1144 my $timer = IO::Async::Timer::Periodic->new(
1145 interval => $interval,
1146 0 ▶ on_tick => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1147 # Don't use async here - just fire and forget
1148 0 _health_check($db)->retain;
1149 },
1150 118 );
1151  
1152 118 $db->{_loop}->add($timer);
1153 118 $timer->start;
1154  
1155 118 $db->{_health_check_timer} = $timer;
1156 };
1157  
1158 118 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 118 118
1159 # If repeat fails, try a different approach or disable health checks
1160 0 warn "Failed to start health checks: $@" if ASYNC_TRACE;
1161 }
1162 }
1163  
1164 0 ▶sub _health_check {
Subroutine _health_check: not called CC=1 SCAR=6.9
1165 0 my $db = shift;
1166  
1167 my @checks = map {
1168 0 my $worker_info = $_;
1169 0 my $worker = $worker_info->{instance};
1170 $worker->call(
1171 args => [
1172 $db->{_schema_class},
1173 $db->{_connect_info},
1174 $db->{_workers_config},
1175 'health_check',
1176 ],
1177 timeout => 5,
1178 )->then(
1179 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1180 0 $worker_info->{healthy} = 1;
1181 0 return Future->done(1);
1182 },
1183 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1184 0 $worker_info->{healthy} = 0;
1185 0 return Future->done(0);
1186 })
1187 0 } @{$db->{_workers}};
1188  
1189 0 ▶ return Future->wait_all(@checks)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
1190 0 my @results = @_;
1191 0 my $healthy_count = grep { $_->get } @results;
1192  
1193 0 _record_metric($db, 'set', 'db_async_workers_active', $healthy_count);
1194  
1195 0 return Future->done($healthy_count);
1196 0 });
1197 }
1198  
1199 0 ▶sub _record_metric {
Subroutine _record_metric: not called CC=6 SCAR=37.4
1200 0 my ($db, $type, $name, @args) = @_;
1201  
1202 0 ▶ return unless $db->{_enable_metrics} && defined $METRICS;
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_enable_metrics"} and defined $DBIx::Class::Async::METRICS 0 0 0
Condition0%0/3
$db->{"_enable_metrics"} and defined $DBIx::Class::Async::METRICS
!ll&&!rl&&r
000
MC/DC0%0/2
$db->{"_enable_metrics"} and defined $DBIx::Class::Async::METRICS
$db->{"_enable_metrics"} defined $DBIx::Class::Async::METRICS
Truth table0%0/3
A and B
A= $db->{"_enable_metrics"}B= defined $DBIx::Class::Async::METRICS
ABresult
0X0
100
111
1203  
1204 0 ▶ if ($type eq 'inc') {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'inc') { } 0 0 0
elsif ($type eq 'observe') { } 0 0 0
elsif ($type eq 'set') { } 0 0 0
1205 0 $METRICS->inc($name, @args);
1206 }
1207 elsif ($type eq 'observe') {
1208 0 $METRICS->observe($name, @args);
1209 }
1210 elsif ($type eq 'set') {
1211 0 $METRICS->set($name, @args);
1212 }
1213 }
1214  
1215 0 ▶sub _resolve_placeholders {
Subroutine _resolve_placeholders: not called CC=15 SCAR=54.8
1216 0 my ($item, $reg) = @_;
1217 0 ▶ return unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 0 0
1218  
1219 0 ▶ if (ref $item eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $item eq 'HASH') { } 0 0 0
elsif (ref $item eq 'ARRAY') { } 0 0 0
1220 0 for my $key (keys %$item) {
1221 # CPANSec CWE-89: never substitute register values into the
1222 # 'sql' key of a txn_do/txn_batch step. That string is handed
1223 # to $dbh->do($step->{sql}, ...) as literal SQL text, so any
1224 # substitution here, even the "exact match" swap, would splice
1225 # a value directly into a query instead of passing it as a
1226 # genuine DBI bind parameter. Chained values that need to reach
1227 # a 'raw' step's query MUST go through the 'bind' arrayref
1228 # (still safely resolved below) with a placeholder (?) in 'sql',
1229 # never through inline text substitution.
1230 0 ▶ next if $key eq 'sql';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "sql" 0 0 0
1231  
1232 0 ▶ if (ref $item->{$key}) {
Branch: 3 branches
BranchTrueFalseTotal
if (ref $item->{$key}) { } 0 0 0
elsif (defined $item->{$key} and exists $$reg{$item->{$key}}) { } 0 0 0
elsif (defined $item->{$key} and not ref $item->{$key}) { } 0 0 0
1233 # Dive deeper into nested structures
1234 0 _resolve_placeholders($item->{$key}, $reg);
1235 }
1236 ▶ elsif (defined $item->{$key} && exists $reg->{$item->{$key}}) {
Condition0%0/3
defined $item->{$key} and exists $$reg{$item->{$key}}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $item->{$key} and exists $$reg{$item->{$key}}
defined $item->{$key} exists $$reg{$item->{$key}}
Truth table0%0/3
A and B
A= defined $item->{$key}B= exists $$reg{$item->{$key}}
ABresult
0X0
100
111
1237 # Exact match: Swap '$user.id' for 42
1238 0 $item->{$key} = $reg->{$item->{$key}};
1239 }
1240 ▶ elsif (defined $item->{$key} && !ref $item->{$key}) {
Condition0%0/3
defined $item->{$key} and not ref $item->{$key}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $item->{$key} and not ref $item->{$key}
defined $item->{$key} not ref $item->{$key}
Truth table0%0/3
A and not(B)
A= defined $item->{$key}B= not ref $item->{$key}
ABresult
0X0
100
111
1241 # String interpolation: Handle "ID is $user.id"
1242 0 $item->{$key} = _interpolate_string($item->{$key}, $reg);
1243 }
1244 }
1245 }
1246 elsif (ref $item eq 'ARRAY') {
1247 0 for my $i (0 .. $#$item) {
1248 0 ▶ if (ref $item->[$i]) {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $item->[$i]) { } 0 0 0
elsif (defined $item->[$i] and exists $$reg{$item->[$i]}) { } 0 0 0
1249 0 _resolve_placeholders($item->[$i], $reg);
1250 }
1251 ▶ elsif (defined $item->[$i] && exists $reg->{$item->[$i]}) {
Condition0%0/3
defined $item->[$i] and exists $$reg{$item->[$i]}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $item->[$i] and exists $$reg{$item->[$i]}
defined $item->[$i] exists $$reg{$item->[$i]}
Truth table0%0/3
A and B
A= defined $item->[$i]B= exists $$reg{$item->[$i]}
ABresult
0X0
100
111
1252 0 $item->[$i] = $reg->{$item->[$i]};
1253 }
1254 }
1255 }
1256 }
1257  
1258 189 ▶sub _safe_require_class {
Subroutine _safe_require_class: called CC=8 SCAR=21.0
1259 189 my ($class) = @_;
1260  
1261 189 ▶ die "Invalid class name: '$class'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and $class =~ /\A\w+(?:::\w+)*\z/u 5 184 189
Condition66%2/3
defined $class and $class =~ /\A\w+(?:::\w+)*\z/u
!ll&&!rl&&r
05184
MC/DC50%1/2
defined $class and $class =~ /\A\w+(?:::\w+)*\z/u
defined $class $class =~ /\A\w+(?:::\w+)*\z/u
Truth table66%2/3
A and B
A= defined $classB= $class =~ /\A\w+(?:::\w+)*\z/u
ABresult
0X0
100
111
1262 unless defined $class && $class =~ /\A\w+(?:::\w+)*\z/;
1263  
1264 101 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1265 # Cheap pre-checks (mirrors Class::C3::Componentised::ensure_class_loaded):
1266 # avoid re-requiring a class that's already loaded or already has some
1267 # symbol table presence.
1268 184 ▶ return 1 if ${"${class}::VERSION"};
Branch: 1 branch
BranchTrueFalseTotal
if ${"${class}::VERSION";} 0 184 184
1269 184 ▶ return 1 if @{"${class}::ISA"};
Branch: 1 branch
BranchTrueFalseTotal
if @{"${class}::ISA";} 102 82 184
1270  
1271 82 my $file = join('/', split(/::/, $class)) . '.pm';
1272 82 ▶ return 1 if $INC{$file};
Branch: 1 branch
BranchTrueFalseTotal
if $INC{$file} 0 82 82
1273  
1274 82 for (keys %{"${class}::"}) {
1275 166 ▶ return 1 if *{"${class}::$_"}{CODE};
Branch: 1 branch
BranchTrueFalseTotal
if *{"${class}::$_";}{"CODE"} 0 166 166
1276 }
1277  
1278 82 require $file;
1279 82 return 1;
1280 }
1281  
1282 0 ▶sub _interpolate_string {
Subroutine _interpolate_string: not called CC=3 SCAR=24.8
1283 0 my ($string, $reg) = @_;
1284 0 ▶ return $string unless $string =~ /\$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $string =~ /\$/u 0 0 0
1285  
1286 # Use a regex to find all keys in the register and replace them
1287 # Example: "INSERT INTO logs VALUES ('Created user $user.id')"
1288 0 foreach my $key (keys %$reg) {
1289 0 my $val = $reg->{$key};
1290 # Escape the key for regex safety (since it contains $)
1291 0 my $quoted_key = quotemeta($key);
1292 0 $string =~ s/$quoted_key/$val/g;
1293 }
1294 0 return $string;
1295 }
1296  
1297 89 ▶sub _build_default_cache {
Subroutine _build_default_cache: called CC=4 SCAR=15.2
1298 89 my ($ttl) = @_;
1299  
1300 # If ttl is 0 or undef, we might not want to initialise the cache driver
1301 # depending on how CHI handles undef (never expire) vs 0 (expire immediately)
1302 89 ▶ return undef if !defined $ttl || $ttl == 0;
Branch: 1 branch
BranchTrueFalseTotal
if not defined $ttl or $ttl == 0 0 89 89
Condition33%1/3
not defined $ttl or $ttl == 0
l!l&&r!l&&!r
0089
MC/DC0%0/2
not defined $ttl or $ttl == 0
not defined $ttl $ttl == 0
Truth table33%1/3
not(A) or B
A= not defined $ttlB= $ttl == 0
ABresult
1X1
011
000
1303  
1304 # CPANSec CWE-639: this caches object is created once per connect() call
1305 # and stored on the $async_db hashref of that connection, hence every
1306 # ResultSet of that connection shares it via that one reference, no need
1307 # for global => 1 and the only thing it achieves is to cause
1308 # CHI::Driver::Memory to back all instances in process with the same
1309 # store, regardless of namespace. That is to say that two Schemas
1310 # connected to two different databases (two calls of this sub) would be
1311 # able to read and write to the same cache entries silently. Each
1312 # connection has to have its own separate store.
1313 89 my %params = (
1314 driver => 'Memory',
1315 global => 0,
1316 );
1317  
1318 # Add expires_in only if ttl is defined (undef means never expire in CHI)
1319 89 ▶ $params{expires_in} = $ttl if defined $ttl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ttl 89 0 89
1320  
1321 89 return CHI->new(%params);
1322 }
1323  
1324 0 ▶sub _normalise_prefetch {
Subroutine _normalise_prefetch: not called CC=5 SCAR=34.0
1325 0 my $pref = shift;
1326  
1327 0 ▶ return {} unless $pref;
Branch: 1 branch
BranchTrueFalseTotal
unless $pref 0 0 0
1328 0 ▶ return { $pref => undef } unless ref $pref;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pref 0 0 0
1329  
1330 0 ▶ if (ref $pref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pref eq "ARRAY") 0 0 0
1331 0 return { map { %{ _normalise_prefetch($_) } } @$pref };
1332 }
1333  
1334 0 ▶ if (ref $pref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pref eq "HASH") 0 0 0
1335 0 return $pref; # Already a spec
1336 }
1337  
1338 0 return {};
1339 }
1340  
1341 0 ▶sub _serialise_row_with_prefetch {
Subroutine _serialise_row_with_prefetch: not called CC=11 SCAR=48.8
1342 0 my ($row, $prefetch) = @_;
1343 0 ▶ return unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
1344  
1345 # 1. If it's a plain HASH (from HashRefInflator),
1346 # just return it. DBIC already structured it for us.
1347 0 ▶ return $row if ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $row eq "HASH" 0 0 0
1348  
1349 # 2. If it's an object, we proceed with manual extraction
1350 0 my %data = $row->get_columns;
1351  
1352 0 ▶ if ($prefetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefetch) 0 0 0
1353 0 my $spec = _normalise_prefetch($prefetch);
1354 0 foreach my $rel (keys %$spec) {
1355 # Only call methods if we have a blessed object
1356 0 ▶ if (blessed($row) && $row->can($rel)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($row) and $row->can($rel)) 0 0 0
Condition0%0/3
builtin::blessed($row) and $row->can($rel)
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($row) and $row->can($rel)
builtin::blessed($row) $row->can($rel)
Truth table0%0/3
A and B
A= builtin::blessed($row)B= $row->can($rel)
ABresult
0X0
100
111
1357 0 my $related = eval { $row->$rel };
1358 0 ▶ next if $@ || !defined $related;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not defined $related 0 0 0
Condition0%0/3
$@ or not defined $related
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not defined $related
$@ not defined $related
Truth table0%0/3
A or not(B)
A= $@B= not defined $related
ABresult
1X1
011
000
1359  
1360 0 ▶ if (blessed($related)
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($related) and $related->isa('DBIx::Class::ResultSet')) { } 0 0 0
Condition0%0/3
builtin::blessed($related) and $related->isa("DBIx::Class::ResultSet")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($related) and $related->isa("DBIx::Class::ResultSet")
builtin::blessed($related) $related->isa("DBIx::Class::ResultSet")
Truth table0%0/3
A and B
A= builtin::blessed($related)B= $related->isa("DBIx::Class::ResultSet")
ABresult
0X0
100
111
1361 && $related->isa('DBIx::Class::ResultSet')) {
1362 $data{$rel} = [
1363 map {
1364 0 _serialise_row_with_prefetch($_, $spec->{$rel})
1365 } $related->all
1366 ];
1367 }
1368 else {
1369 0 $data{$rel} = _serialise_row_with_prefetch($related, $spec->{$rel});
1370 }
1371 }
1372 }
1373 }
1374 0 return \%data;
1375 }
1376  
1377 =head1 EVENT LOOP INTEGRATION
1378  
1379 B<LOOP AGNOSTICISM>
1380  
1381 C<DBIx::Class::Async> is built atop L<IO::Async>, but it is designed to be
1382 loop-agnostic. It does not force you to use a specific event loop engine.
1383 This is critical for applications already running within an established
1384 ecosystem like L<Mojolicious>, L<AnyEvent>, etc.
1385  
1386 The bridge follows a B<"Smart Default"> pattern:
1387  
1388 =over 4
1389  
1390 =item * Implicit
1391  
1392 If no loop is provided, it automatically detects your OS and instantiates
1393 the best available L<IO::Async::Loop> (e.g., B<Epoll>, B<KQueue>, or B<Poll>).
1394  
1395 =item * Explicit
1396  
1397 If you provide a loop object via the B<loop> attribute, the bridge B<"slaves">
1398 itself to that engine.
1399  
1400 =back
1401  
1402 B<UNDER THE HOOD>
1403  
1404 When an external loop is provided, L<DBIx::Class::Async> performs the following
1405 steps:
1406  
1407 =over 4
1408  
1409 =item * Process Delegation
1410  
1411 The library initialises a pool of persistent background workers. These are
1412 separate processes that hold their own database handles to prevent blocking
1413 the main event loop.
1414  
1415 =item * Pipe Multiplexing
1416  
1417 Communication between your application and the workers happens via asynchronous
1418 pipes. Your event loop (Mojo, Poll, etc.) watches these pipes for "Read Ready"
1419 signals.
1420  
1421 =item * Heartbeat Sharing
1422  
1423 All internal timers (Health Checks, TTL Caching) are registered as Notifiers
1424 within the parent loop’s reactor, ensuring they only fire when the loop
1425 is "ticking".
1426  
1427 =item * Non-Blocking Flow
1428  
1429 Because the database I/O happens in a separate memory space, a 10-second
1430 query will not increase the "latency" or "lag" of your web server's main loop.
1431  
1432 =back
1433  
1434 B<EXAMPLE: MOJOLICIOUS INTEGRATION>
1435  
1436 To use this library inside a B<Mojolicious> application, use the L<IO::Async::Loop::Mojo>
1437 bridge. This allows your database workers to share the same reactor as your
1438 web server, preventing I/O starvation.
1439  
1440 use Mojolicious::Lite;
1441 use DBIx::Class::Async::Schema;
1442 use IO::Async::Loop::Mojo;
1443  
1444 # 1. Create a bridge between IO::Async and Mojo
1445 my $loop = IO::Async::Loop::Mojo->new;
1446  
1447 # 2. Connect your schema using the Mojo-backed loop
1448 helper db => sub {
1449 state $schema = DBIx::Class::Async::Schema->connect(
1450 $dsn, $user, $pass, \%dbic_attrs,
1451 {
1452 schema_class => 'My::App::Schema',
1453 workers => 4,
1454 loop => $loop, # The Magic Connection
1455 }
1456 );
1457 };
1458  
1459 # 3. Use non-blocking DBIC in your routes
1460 get '/stats' => sub {
1461 my $c = shift;
1462  
1463 $c->db->resultset('User')
1464 ->search({ active => 1 })
1465 ->all
1466 ->on_done(sub {
1467 my @users = @_;
1468 $c->render(json => { count => scalar @users });
1469 });
1470 };
1471  
1472 app->start;
1473  
1474 =head1 PERFORMANCE TIPS
1475  
1476 =over 4
1477  
1478 =item * Worker Count & CPU Affinity
1479  
1480 Adjust the C<workers> parameter based on your database connection limits and expected concurrency. Since each worker is a separate process, 2-4 workers per CPU core is the sweet spot. Too many workers can cause context-switching overhead on your OS.
1481  
1482 =item * Caching Strategy
1483  
1484 The new design uses C<CHI> for memory-efficient caching. For read-heavy workloads, ensure C<cache_ttl> is set. Setting it to C<0> will disable caching, which is useful for data that changes every second.
1485  
1486 =item * Batch Operations (Concurrent Execution)
1487  
1488 Instead of sequential C<await> calls, which force workers to sit idle, use C<Future->wait_all> or C<Future->needs_all> to fire multiple queries across your worker pool simultaneously.
1489  
1490 =item * Connection Persistence
1491  
1492 Each worker maintains a persistent connection to the database. This eliminates the "connection tax" (handshake time) for every query. Monitor your database's C<max_connections> setting to ensure it can handle C<Total Apps * Workers Per App>.
1493  
1494 =item * Timeout Guardrails
1495  
1496 The C<query_timeout> (default 30s) is your safety net. In the new design, a hung query only blocks B<one> worker; the others stay active. Without a timeout, a single "zombie" query could permanently reduce your pool size.
1497  
1498 =back
1499  
1500 =head1 SQL GENERATION CONSISTENCY
1501  
1502 L<DBIx::Class::Async> ensures deterministic SQL generation across multiple
1503 invocations of the same query. This is critical for query caching, performance
1504 analysis, and debugging.
1505  
1506 B<Deterministic Column Ordering>
1507  
1508 When you call C<search()> multiple times on the same ResultSet, the generated
1509 SQL will be identical, including column order:
1510  
1511 my $rs = $schema->resultset('User');
1512  
1513 # These produce identical SQL every time
1514 my $query1 = $rs->search({})->as_query;
1515 my $query2 = $rs->search({})->as_query;
1516  
1517 # SELECT me.id, me.name, me.email, ... FROM users me
1518 # (same order on every call)
1519  
1520 This consistency is maintained even with complex attribute merging:
1521  
1522 my $rs = $schema->resultset('User')
1523 ->search({}, { join => 'orders' })
1524 ->search({}, { join => 'profile' });
1525  
1526 # Joins are deduplicated and ordered consistently
1527  
1528 B<Attribute Deduplication>
1529  
1530 When chaining C<search()> calls, accumulating attributes (C<join>, C<prefetch>,
1531 C<columns>, C<select>, C<as>, C<order_by>, C<group_by>, C<having>) are
1532 automatically deduplicated:
1533  
1534 my $rs = $schema->resultset('User')
1535 ->search({}, { join => 'orders' })
1536 ->search({}, { join => 'orders' }) # Deduplicated
1537 ->search({}, { join => 'profile' });
1538  
1539 # Results in: JOIN orders, JOIN profile (not duplicate orders)
1540  
1541 Deduplication uses a stable serialisation of nested structures, so these
1542 are correctly recognised as duplicates:
1543  
1544 { orders => 'items' } # Same as:
1545 { orders => 'items' } # This duplicate
1546  
1547 B<Benefits>
1548  
1549 =over 4
1550  
1551 =item * B<Query Caching> - Identical SQL enables effective query caching
1552  
1553 =item * B<Performance Analysis> - Consistent SQL makes it easier to identify
1554 slow queries in logs
1555  
1556 =item * B<Testing> - Predictable SQL generation makes testing more reliable
1557  
1558 =item * B<Debugging> - Easier to trace and compare queries
1559  
1560 =back
1561  
1562 B<Debugging SQL>
1563  
1564 You can inspect generated SQL using the C<as_query> method or by enabling
1565 debug mode:
1566  
1567 # Using as_query
1568 my $rs = $schema->resultset('User')->search({ active => 1 });
1569 my $query = $rs->as_query;
1570 # Extract SQL from the returned structure
1571  
1572 # Using debug mode
1573 $schema->storage->debug(1);
1574 $rs->all; # SQL printed to STDERR in worker processes
1575  
1576 See L<debugobj|DBIx::Class::Async::Storage::DBI/debugobj> and
1577 L<debug|DBIx::Class::Async::Storage::DBI/debug> for more information on SQL
1578 debugging.
1579  
1580 =head1 ERROR HANDLING
1581  
1582 The bridge uses C<< Future->fail >> to propagate errors from the workers back to your main process. You should handle these using C<await> within a C<try/catch> block or the C<< ->catch >> method.
1583  
1584 =over 4
1585  
1586 =item * Worker Connectivity
1587  
1588 If a worker cannot connect to the DB, it will throw an exception during the first query or a health check.
1589  
1590 =item * Automatic Retries
1591  
1592 If C<enable_retry> is true, the bridge will automatically retry queries that fail due to transient issues (like database deadlocks) using an exponential backoff (starting at 1s, doubling each time).
1593  
1594 =item * Serialisation Failures
1595  
1596 Because data must travel between processes, any custom objects in your ResultSets must be serialiisable. The new design handles most DBIC inflation automatically, but be wary of passing "live" filehandles or sockets.
1597  
1598 =back
1599  
1600 =head1 METRICS
1601  
1602 If C<< enable_metrics => 1 >> is passed to the constructor and L<Metrics::Any> is available, the following gauges and counters are tracked:
1603  
1604 +------------------------------------+-----------+-----------------------------------------------------+
1605 | Metric | Type | Description |
1606 +------------------------------------+-----------+-----------------------------------------------------+
1607 | C<db_async_queries_total> | Counter | Total number of operations sent to workers. |
1608 | C<db_async_cache_hits_total> | Counter | Queries resolved via the internal C<CHI> cache. |
1609 | C<db_async_query_duration_seconds> | Histogram | Latency distribution of database operations. |
1610 | C<db_async_workers_active> | Gauge | Number of workers passing the periodic health check.|
1611 +------------------------------------+-----------+-----------------------------------------------------+
1612  
1613 =head1 DEDICATION
1614  
1615 This module is dedicated to the memory of B<Matt S. Trout (mst)>,
1616 a brilliant contributor to the Perl community, L<DBIx::Class> core developer,
1617 and friend who is deeply missed.
1618  
1619 =head1 AUTHOR
1620  
1621 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
1622  
1623 =head1 REPOSITORY
1624  
1625 L<https://github.com/manwar/DBIx-Class-Async>
1626  
1627 =head1 BUGS
1628  
1629 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/DBIx-Class-Async/issues>.
1630 I will be notified and then you'll automatically be notified of progress on your
1631 bug as I make changes.
1632  
1633 =head1 SUPPORT
1634  
1635 You can find documentation for this module with the perldoc command.
1636  
1637 perldoc DBIx::Class::Async
1638  
1639 You can also look for information at:
1640  
1641 =over 4
1642  
1643 =item * BUG Report
1644  
1645 L<https://github.com/manwar/DBIx-Class-Async/issues>
1646  
1647 =item * CPAN Ratings
1648  
1649 L<http://cpanratings.perl.org/d/DBIx-Class-Async>
1650  
1651 =item * Search MetaCPAN
1652  
1653 L<https://metacpan.org/dist/DBIx-Class-Async/>
1654  
1655 =back
1656  
1657 =head1 LICENSE AND COPYRIGHT
1658  
1659 Copyright (C) 2026 Mohammad Sajid Anwar.
1660  
1661 This program is free software; you can redistribute it and / or modify it under
1662 the terms of the the Artistic License (2.0). You may obtain a copy of the full
1663 license at:
1664 L<http://www.perlfoundation.org/artistic_license_2_0>
1665 Any use, modification, and distribution of the Standard or Modified Versions is
1666 governed by this Artistic License.By using, modifying or distributing the Package,
1667 you accept this license. Do not use, modify, or distribute the Package, if you do
1668 not accept this license.
1669 If your Modified Version has been derived from a Modified Version made by someone
1670 other than you,you are nevertheless required to ensure that your Modified Version
1671 complies with the requirements of this license.
1672 This license does not grant you the right to use any trademark, service mark,
1673 tradename, or logo of the Copyright Holder.
1674 This license includes the non-exclusive, worldwide, free-of-charge patent license
1675 to make, have made, use, offer to sell, sell, import and otherwise transfer the
1676 Package with respect to any patent claims licensable by the Copyright Holder that
1677 are necessarily infringed by the Package. If you institute patent litigation
1678 (including a cross-claim or counterclaim) against any party alleging that the
1679 Package constitutes direct or contributory patent infringement,then this Artistic
1680 License to you shall terminate on the date that such litigation is filed.
1681 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
1682 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
1683 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
1684 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
1685 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
1686 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
1687 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1688  
1689 =cut
1690  
1691 101 1; # End of DBIx::Class::Async
↑ Summary Async/Row.pm »