Async.pm

filter: Statementstmt 39.2% 200 / 510 Branchbran 19.5% 50 / 256 Conditioncond 31.3% 42 / 134 MC/DCmcdc 14.4% 12 / 83 Subroutinesub 64.8% 35 / 54 Podpod 100% 2 / 2 totaltotal 32.8% 341 / 1039 CC 193 SCAR 57.3
CC
193
Cov
32%
__ANON__
1560.0
__ANON__
240.0
_resolve_placeholders
240.0
CRAP 306.7
↑ Summary Async/Row.pm »
1 package DBIx::Class::Async;
2  
3 100 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 100 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 100 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 100 our $VERSION = qv('v1.1.0');
8 100 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.1.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 100 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
262 100 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
263 100 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
264  
265 100 ▶use v5.14;
Subroutine BEGIN: called CC=1 SCAR=0.0
266  
267 100 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
268 100 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
269 100 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
270 100 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
271 100 ▶use IO::Async::Function;
Subroutine BEGIN: called CC=1 SCAR=0.0
272 100 ▶use Time::HiRes qw(time);
Subroutine BEGIN: called CC=1 SCAR=0.0
273 100 ▶use Digest::MD5 qw(md5_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
274 100 ▶use Type::Params qw(compile);
Subroutine BEGIN: called CC=1 SCAR=0.0
275 100 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
276 100 ▶use DBIx::Class::Async::Row;
Subroutine BEGIN: called CC=1 SCAR=0.0
277 100 ▶use Types::Standard qw(Str ScalarRef HashRef ArrayRef Maybe Int CodeRef);
Subroutine BEGIN: called CC=1 SCAR=0.0
278  
279 100 ▶use DBIx::Class::Async::Exception::Factory;
Subroutine BEGIN: called CC=1 SCAR=0.0
280  
281 100 ▶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
0100
MC/DC0%0/1
$ENV{'ASYNC_TRACE'} || 0
$ENV{'ASYNC_TRACE'}
Truth table50%1/2
A
A= $ENV{'ASYNC_TRACE'}
Aresult
11
00
282 100 our $METRICS;
283  
284 use constant {
285 100 DEFAULT_WORKERS => 4,
286 DEFAULT_CACHE_TTL => 0,
287 DEFAULT_QUERY_TIMEOUT => 30,
288 DEFAULT_RETRIES => 3,
289 HEALTH_CHECK_INTERVAL => 300,
290 100 ▶};
Subroutine BEGIN: called CC=1 SCAR=0.0
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 sub create_async_db {
332 118 ▶ my ($class, %args) = @_;
Subroutine create_async_db: called CC=25 SCAR=37.4
Pod documented
333  
334 118 ▶ 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") 0 118 118
335 118 ▶ 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") 0 118 118
336 118 ▶ my $workers = $args{workers} || DEFAULT_WORKERS;
Condition50%1/2
$args{'workers'} || 4
l!l
1180
MC/DC0%0/1
$args{'workers'} || 4
$args{'workers'}
Truth table50%1/2
A
A= $args{'workers'}
Aresult
11
00
337  
338 118 ▶ 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 118 118
Condition33%1/3
eval { do { $schema_class->can("connect") } } or eval { do { _safe_require_class($schema_class) } }
l!l&&r!l&&!r
11800
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 table33%1/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 118 ▶ : DEFAULT_CACHE_TTL;
Branch: 1 branch
BranchTrueFalseTotal
exists $args{'cache_ttl'} ? : 116 2 118
345  
346 # 1. Extract Column Metadata (Inflators/Deflators)
347 # We do this before creating the hashref so we can include it
348 118 my $custom_inflators = {};
349 118 ▶ if ($schema_class->can('sources')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($schema_class->can("sources")) 118 0 118
350 118 foreach my $source_name ($schema_class->sources) {
351 1170 my $source = $schema_class->source($source_name);
352 1170 foreach my $col ($source->columns) {
353 5031 my $info = $source->column_info($col);
354 5031 ▶ if ($info->{deflate} || $info->{inflate}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($info->{"deflate"} or $info->{"inflate"}) 0 5031 5031
Condition33%1/3
$info->{"deflate"} or $info->{"inflate"}
l!l&&r!l&&!r
005031
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 118 my $old_sigchld = $SIG{CHLD};
366 118 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 118 ▶ _debug => $args{debug} || 0,
Branch: 1 branch
BranchTrueFalseTotal
$cache_ttl > 0 ? : 89 28 117
Condition70%14/20
$args{'async_loop'} || 'IO::Async::Loop'->new
l!l&&r!l&&!r
107110
$args{'query_timeout'} || 30
l!l
0118
$args{'on_connect_do'} || []
l!l
0118
$args{'cache'} || ($cache_ttl > 0 ? _build_default_cache($cache_ttl) : undef)
l!l&&r!l&&!r
18928
$args{"enable_retry"} // 0
l!l
2116
$args{'max_retries'} || 3
l!l
0118
$args{'retry_delay'} || 1
l!l
0118
$args{"enable_metrics"} // 0
l!l
2116
$args{'debug'} || 0
l!l
0118
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 118 ▶ _init_metrics($async_db) if $async_db->{_enable_metrics};
Branch: 1 branch
BranchTrueFalseTotal
if $async_db->{"_enable_metrics"} 0 118 118
406 118 _init_workers($async_db);
407  
408 118 ▶ if (my $interval = $args{health_check} // HEALTH_CHECK_INTERVAL) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $interval = $args{"health_check"} // 300) 118 0 118
Condition50%1/2
$args{"health_check"} // 300
l!l
0118
MC/DC0%0/1
$args{"health_check"} // 300
$args{"health_check"}
Truth table50%1/2
A
A= $args{"health_check"}
Aresult
11
00
409 118 _start_health_checks($async_db, $interval);
410 }
411  
412 118 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 sub disconnect {
431 118 ▶ my ($db) = @_;
Subroutine disconnect: called CC=12 SCAR=25.3
Pod documented
432  
433 118 ▶ return unless $db && ref $db eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $db and ref $db eq "HASH" 0 118 118
Condition33%1/3
$db and ref $db eq "HASH"
!ll&&!rl&&r
00118
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 118 ▶ return unless $db->{_loop};
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_loop"} 1 117 118
435  
436 # 1. Clear the health check timer
437 # remove() BEFORE stop() - same ordering rule as workers below.
438 117 ▶ if ($db->{_health_check_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_health_check_timer"}) 116 1 117
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 117 ▶ if ($db->{_workers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_workers"}) 117 0 117
459 117 my @stop_futures;
460 117 foreach my $worker_info (@{ $db->{_workers} }) {
461 224 ▶ my $instance = $worker_info->{instance} or next;
Branch: 1 branch
BranchTrueFalseTotal
my $instance = $worker_info->{"instance"} or next 0 224 224
462 224 eval { $db->{_loop}->remove($instance) };
463 224 my $f = eval { $instance->stop };
464 224 ▶ push @stop_futures, $f if $f && ref $f;
Branch: 1 branch
BranchTrueFalseTotal
if $f and ref $f 224 0 224
Condition33%1/3
$f and ref $f
!ll&&!rl&&r
00224
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 117 $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 117 ▶ if (@stop_futures) {
Branch: 1 branch
BranchTrueFalseTotal
if (@stop_futures) 116 1 117
473 116 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 117 ▶ if ($db->{_owns_loop}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($db->{"_owns_loop"}) 11 106 117
489 11 undef $IO::Async::Loop::ONE_TRUE_LOOP;
490 11 $SIG{CHLD} = $db->{_old_sigchld};
491 }
492  
493 # 4. Final state update
494 117 $db->{_is_connected} = 0;
495  
496 117 return 1;
497 }
498  
499 #
500 #
501 # PRIVATE METHODS
502  
503 sub _call_worker {
504 1102 ▶ my ($db, $operation, @args) = @_;
Subroutine _call_worker: called CC=9 SCAR=25.4
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 my $make_exception = sub {
566 6 ▶ my ($raw) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.4
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 return $worker_future->followed_by(sub {
578 1102 ▶ my ($f) = @_;
Subroutine __ANON__: called CC=7 SCAR=28.0
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 return $result->followed_by(sub {
595 0 ▶ my ($inner_f) = @_;
Subroutine __ANON__: not called CC=5 SCAR=34.0
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 sub _init_workers {
630 118 ▶ my $db = shift;
Subroutine _init_workers: called CC=2 SCAR=17.2
631  
632 118 for my $worker_id (1..$db->{_workers_config}{_count}) {
633 my $worker = IO::Async::Function->new(
634 code => sub {
635 100 ▶ use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
636 100 ▶ use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
637 100 ▶ 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) = @_;
Subroutine __ANON__: not called CC=13 SCAR=52.0
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 $deflator = sub {
655 0 ▶ my ($data) = @_;
Subroutine __ANON__: not called CC=7 SCAR=40.3
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 my $log_sql = sub {
678 0 ▶ my ($debug_enabled, $sql, $bind) = @_;
Subroutine __ANON__: not called CC=5 SCAR=34.0
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 my $result = try {
778 0 ▶ my $schema = $schema_cache->{$pid};
Subroutine __ANON__: not called CC=39 SCAR=73.5
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') { } 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 $schema->txn_do(sub {
933 0 ▶ my $success_count = 0;
Subroutine __ANON__: not called CC=9 SCAR=45.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} || []});
Branch: 1 branch
BranchTrueFalseTotal
$op->{"bind"} or [] 0 0 0
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 $schema->txn_do(sub {
981 0 ▶ my @step_results;
Subroutine __ANON__: not called CC=15 SCAR=54.8
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} || []});
Branch: 1 branch
BranchTrueFalseTotal
$step->{"bind"} or [] 0 0 0
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') {
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 catch {
1057 0 ▶ warn "[PID $$] Worker execution error: $_"
Subroutine __ANON__: not called CC=1 SCAR=6.9
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 228 max_workers => 1,
1070 );
1071  
1072 228 $db->{_loop}->add($worker);
1073  
1074 228 push @{$db->{_workers}}, {
1075 instance => $worker,
1076 healthy => 1,
1077 pid => undef,
1078 };
1079 }
1080 }
1081  
1082 sub _init_metrics {
1083 0 ▶ my $db = shift;
Subroutine _init_metrics: not called CC=2 SCAR=17.9
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 sub _next_worker {
1107 1102 ▶ my ($db) = @_;
Subroutine _next_worker: called CC=6 SCAR=19.5
1108  
1109 1102 ▶ return unless $db->{_workers} && @{$db->{_workers}};
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_workers"} and @{$db->{"_workers"};} 0 1102 1102
Condition33%1/3
$db->{"_workers"} and @{$db->{"_workers"};}
!ll&&!rl&&r
001102
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 1102 ▶ $db->{_worker_idx} //= 0;
Condition50%1/2
$db->{"_worker_idx"} //= 0
l!l
11020
MC/DC0%0/1
$db->{"_worker_idx"} //= 0
$db->{"_worker_idx"}
Truth table50%1/2
A
A= $db->{"_worker_idx"}
Aresult
11
00
1112  
1113 1102 ▶ die "No workers available" unless $db->{_workers} && @{$db->{_workers}};
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_workers"} and @{$db->{"_workers"};} 0 1102 1102
Condition33%1/3
$db->{"_workers"} and @{$db->{"_workers"};}
!ll&&!rl&&r
001102
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
1114  
1115 1102 my $idx = $db->{_worker_idx};
1116 1102 my $worker = $db->{_workers}[$idx];
1117  
1118 1102 $db->{_worker_idx} = ($idx + 1) % @{$db->{_workers}};
1119  
1120 1102 return $worker->{instance};
1121 }
1122  
1123 sub _start_health_checks {
1124 118 ▶ my ($db, $interval) = @_;
Subroutine _start_health_checks: called CC=3 SCAR=11.5
1125  
1126 118 ▶ return if $interval <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $interval <= 0 0 118 118
1127  
1128 # Try to create the timer
1129 118 eval {
1130 118 require IO::Async::Timer::Periodic;
1131  
1132 my $timer = IO::Async::Timer::Periodic->new(
1133 interval => $interval,
1134 on_tick => sub {
1135 # Don't use async here - just fire and forget
1136 0 ▶ _health_check($db)->retain;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1137 },
1138 118 );
1139  
1140 118 $db->{_loop}->add($timer);
1141 118 $timer->start;
1142  
1143 118 $db->{_health_check_timer} = $timer;
1144 };
1145  
1146 118 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 118 118
1147 # If repeat fails, try a different approach or disable health checks
1148 0 warn "Failed to start health checks: $@" if ASYNC_TRACE;
1149 }
1150 }
1151  
1152 sub _health_check {
1153 0 ▶ my $db = shift;
Subroutine _health_check: not called CC=1 SCAR=6.9
1154  
1155 my @checks = map {
1156 0 my $worker_info = $_;
1157 0 my $worker = $worker_info->{instance};
1158 $worker->call(
1159 args => [
1160 $db->{_schema_class},
1161 $db->{_connect_info},
1162 $db->{_workers_config},
1163 'health_check',
1164 ],
1165 timeout => 5,
1166 )->then(
1167 sub {
1168 0 ▶ $worker_info->{healthy} = 1;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1169 0 return Future->done(1);
1170 },
1171 sub {
1172 0 ▶ $worker_info->{healthy} = 0;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1173 0 return Future->done(0);
1174 })
1175 0 } @{$db->{_workers}};
1176  
1177 return Future->wait_all(@checks)->then(sub {
1178 0 ▶ my @results = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
1179 0 my $healthy_count = grep { $_->get } @results;
1180  
1181 0 _record_metric($db, 'set', 'db_async_workers_active', $healthy_count);
1182  
1183 0 return Future->done($healthy_count);
1184 0 });
1185 }
1186  
1187 sub _record_metric {
1188 0 ▶ my ($db, $type, $name, @args) = @_;
Subroutine _record_metric: not called CC=6 SCAR=37.4
1189  
1190 0 ▶ return unless $db->{_enable_metrics} && defined $METRICS;
Branch: 1 branch
BranchTrueFalseTotal
unless $db->{"_enable_metrics"} and defined $METRICS 0 0 0
Condition0%0/3
$db->{"_enable_metrics"} and defined $METRICS
!ll&&!rl&&r
000
MC/DC0%0/2
$db->{"_enable_metrics"} and defined $METRICS
$db->{"_enable_metrics"} defined $METRICS
Truth table0%0/3
A and B
A= $db->{"_enable_metrics"}B= defined $METRICS
ABresult
0X0
100
111
1191  
1192 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
1193 0 $METRICS->inc($name, @args);
1194 }
1195 elsif ($type eq 'observe') {
1196 0 $METRICS->observe($name, @args);
1197 }
1198 elsif ($type eq 'set') {
1199 0 $METRICS->set($name, @args);
1200 }
1201 }
1202  
1203 sub _resolve_placeholders {
1204 0 ▶ my ($item, $reg) = @_;
Subroutine _resolve_placeholders: not called CC=15 SCAR=54.8
1205 0 ▶ return unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 0 0 0
1206  
1207 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
1208 0 for my $key (keys %$item) {
1209 # CPANSec CWE-89: never substitute register values into the
1210 # 'sql' key of a txn_do/txn_batch step. That string is handed
1211 # to $dbh->do($step->{sql}, ...) as literal SQL text, so any
1212 # substitution here, even the "exact match" swap, would splice
1213 # a value directly into a query instead of passing it as a
1214 # genuine DBI bind parameter. Chained values that need to reach
1215 # a 'raw' step's query MUST go through the 'bind' arrayref
1216 # (still safely resolved below) with a placeholder (?) in 'sql',
1217 # never through inline text substitution.
1218 0 ▶ next if $key eq 'sql';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "sql" 0 0 0
1219  
1220 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
1221 # Dive deeper into nested structures
1222 0 _resolve_placeholders($item->{$key}, $reg);
1223 }
1224 ▶ 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
1225 # Exact match: Swap '$user.id' for 42
1226 0 $item->{$key} = $reg->{$item->{$key}};
1227 }
1228 ▶ 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
1229 # String interpolation: Handle "ID is $user.id"
1230 0 $item->{$key} = _interpolate_string($item->{$key}, $reg);
1231 }
1232 }
1233 }
1234 elsif (ref $item eq 'ARRAY') {
1235 0 for my $i (0 .. $#$item) {
1236 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
1237 0 _resolve_placeholders($item->[$i], $reg);
1238 }
1239 ▶ 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
1240 0 $item->[$i] = $reg->{$item->[$i]};
1241 }
1242 }
1243 }
1244 }
1245  
1246 sub _safe_require_class {
1247 188 ▶ my ($class) = @_;
Subroutine _safe_require_class: called CC=8 SCAR=21.0
1248  
1249 188 ▶ die "Invalid class name: '$class'\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $class and $class =~ /\A\w+(?:::\w+)*\z/u 5 183 188
Condition66%2/3
defined $class and $class =~ /\A\w+(?:::\w+)*\z/u
!ll&&!rl&&r
05183
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
1250 unless defined $class && $class =~ /\A\w+(?:::\w+)*\z/;
1251  
1252 100 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
1253 # Cheap pre-checks (mirrors Class::C3::Componentised::ensure_class_loaded):
1254 # avoid re-requiring a class that's already loaded or already has some
1255 # symbol table presence.
1256 183 ▶ return 1 if ${"${class}::VERSION"};
Branch: 1 branch
BranchTrueFalseTotal
if ${"${class}::VERSION";} 0 183 183
1257 183 ▶ return 1 if @{"${class}::ISA"};
Branch: 1 branch
BranchTrueFalseTotal
if @{"${class}::ISA";} 102 81 183
1258  
1259 81 my $file = join('/', split(/::/, $class)) . '.pm';
1260 81 ▶ return 1 if $INC{$file};
Branch: 1 branch
BranchTrueFalseTotal
if $INC{$file} 0 81 81
1261  
1262 81 for (keys %{"${class}::"}) {
1263 164 ▶ return 1 if *{"${class}::$_"}{CODE};
Branch: 1 branch
BranchTrueFalseTotal
if *{"${class}::$_";}{"CODE"} 0 164 164
1264 }
1265  
1266 81 require $file;
1267 81 return 1;
1268 }
1269  
1270 sub _interpolate_string {
1271 0 ▶ my ($string, $reg) = @_;
Subroutine _interpolate_string: not called CC=3 SCAR=24.8
1272 0 ▶ return $string unless $string =~ /\$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $string =~ /\$/u 0 0 0
1273  
1274 # Use a regex to find all keys in the register and replace them
1275 # Example: "INSERT INTO logs VALUES ('Created user $user.id')"
1276 0 foreach my $key (keys %$reg) {
1277 0 my $val = $reg->{$key};
1278 # Escape the key for regex safety (since it contains $)
1279 0 my $quoted_key = quotemeta($key);
1280 0 $string =~ s/$quoted_key/$val/g;
1281 }
1282 0 return $string;
1283 }
1284  
1285 sub _build_default_cache {
1286 89 ▶ my ($ttl) = @_;
Subroutine _build_default_cache: called CC=4 SCAR=15.2
1287  
1288 # If ttl is 0 or undef, we might not want to initialise the cache driver
1289 # depending on how CHI handles undef (never expire) vs 0 (expire immediately)
1290 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
1291  
1292 # CPANSec CWE-639: this caches object is created once per connect() call
1293 # and stored on the $async_db hashref of that connection, hence every
1294 # ResultSet of that connection shares it via that one reference, no need
1295 # for global => 1 and the only thing it achieves is to cause
1296 # CHI::Driver::Memory to back all instances in process with the same
1297 # store, regardless of namespace. That is to say that two Schemas
1298 # connected to two different databases (two calls of this sub) would be
1299 # able to read and write to the same cache entries silently. Each
1300 # connection has to have its own separate store.
1301 89 my %params = (
1302 driver => 'Memory',
1303 global => 0,
1304 );
1305  
1306 # Add expires_in only if ttl is defined (undef means never expire in CHI)
1307 89 ▶ $params{expires_in} = $ttl if defined $ttl;
Branch: 1 branch
BranchTrueFalseTotal
if defined $ttl 89 0 89
1308  
1309 89 return CHI->new(%params);
1310 }
1311  
1312 sub _normalise_prefetch {
1313 0 ▶ my $pref = shift;
Subroutine _normalise_prefetch: not called CC=5 SCAR=34.0
1314  
1315 0 ▶ return {} unless $pref;
Branch: 1 branch
BranchTrueFalseTotal
unless $pref 0 0 0
1316 0 ▶ return { $pref => undef } unless ref $pref;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pref 0 0 0
1317  
1318 0 ▶ if (ref $pref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pref eq "ARRAY") 0 0 0
1319 0 return { map { %{ _normalise_prefetch($_) } } @$pref };
1320 }
1321  
1322 0 ▶ if (ref $pref eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $pref eq "HASH") 0 0 0
1323 0 return $pref; # Already a spec
1324 }
1325  
1326 0 return {};
1327 }
1328  
1329 sub _serialise_row_with_prefetch {
1330 0 ▶ my ($row, $prefetch) = @_;
Subroutine _serialise_row_with_prefetch: not called CC=11 SCAR=48.8
1331 0 ▶ return unless $row;
Branch: 1 branch
BranchTrueFalseTotal
unless $row 0 0 0
1332  
1333 # 1. If it's a plain HASH (from HashRefInflator),
1334 # just return it. DBIC already structured it for us.
1335 0 ▶ return $row if ref($row) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $row eq "HASH" 0 0 0
1336  
1337 # 2. If it's an object, we proceed with manual extraction
1338 0 my %data = $row->get_columns;
1339  
1340 0 ▶ if ($prefetch) {
Branch: 1 branch
BranchTrueFalseTotal
if ($prefetch) 0 0 0
1341 0 my $spec = _normalise_prefetch($prefetch);
1342 0 foreach my $rel (keys %$spec) {
1343 # Only call methods if we have a blessed object
1344 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
1345 0 my $related = eval { $row->$rel };
1346 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
1347  
1348 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
1349 && $related->isa('DBIx::Class::ResultSet')) {
1350 $data{$rel} = [
1351 map {
1352 0 _serialise_row_with_prefetch($_, $spec->{$rel})
1353 } $related->all
1354 ];
1355 }
1356 else {
1357 0 $data{$rel} = _serialise_row_with_prefetch($related, $spec->{$rel});
1358 }
1359 }
1360 }
1361 }
1362 0 return \%data;
1363 }
1364  
1365 =head1 EVENT LOOP INTEGRATION
1366  
1367 B<LOOP AGNOSTICISM>
1368  
1369 C<DBIx::Class::Async> is built atop L<IO::Async>, but it is designed to be
1370 loop-agnostic. It does not force you to use a specific event loop engine.
1371 This is critical for applications already running within an established
1372 ecosystem like L<Mojolicious>, L<AnyEvent>, etc.
1373  
1374 The bridge follows a B<"Smart Default"> pattern:
1375  
1376 =over 4
1377  
1378 =item * Implicit
1379  
1380 If no loop is provided, it automatically detects your OS and instantiates
1381 the best available L<IO::Async::Loop> (e.g., B<Epoll>, B<KQueue>, or B<Poll>).
1382  
1383 =item * Explicit
1384  
1385 If you provide a loop object via the B<loop> attribute, the bridge B<"slaves">
1386 itself to that engine.
1387  
1388 =back
1389  
1390 B<UNDER THE HOOD>
1391  
1392 When an external loop is provided, L<DBIx::Class::Async> performs the following
1393 steps:
1394  
1395 =over 4
1396  
1397 =item * Process Delegation
1398  
1399 The library initialises a pool of persistent background workers. These are
1400 separate processes that hold their own database handles to prevent blocking
1401 the main event loop.
1402  
1403 =item * Pipe Multiplexing
1404  
1405 Communication between your application and the workers happens via asynchronous
1406 pipes. Your event loop (Mojo, Poll, etc.) watches these pipes for "Read Ready"
1407 signals.
1408  
1409 =item * Heartbeat Sharing
1410  
1411 All internal timers (Health Checks, TTL Caching) are registered as Notifiers
1412 within the parent loop’s reactor, ensuring they only fire when the loop
1413 is "ticking".
1414  
1415 =item * Non-Blocking Flow
1416  
1417 Because the database I/O happens in a separate memory space, a 10-second
1418 query will not increase the "latency" or "lag" of your web server's main loop.
1419  
1420 =back
1421  
1422 B<EXAMPLE: MOJOLICIOUS INTEGRATION>
1423  
1424 To use this library inside a B<Mojolicious> application, use the L<IO::Async::Loop::Mojo>
1425 bridge. This allows your database workers to share the same reactor as your
1426 web server, preventing I/O starvation.
1427  
1428 use Mojolicious::Lite;
1429 use DBIx::Class::Async::Schema;
1430 use IO::Async::Loop::Mojo;
1431  
1432 # 1. Create a bridge between IO::Async and Mojo
1433 my $loop = IO::Async::Loop::Mojo->new;
1434  
1435 # 2. Connect your schema using the Mojo-backed loop
1436 helper db => sub {
1437 state $schema = DBIx::Class::Async::Schema->connect(
1438 $dsn, $user, $pass, \%dbic_attrs,
1439 {
1440 schema_class => 'My::App::Schema',
1441 workers => 4,
1442 loop => $loop, # The Magic Connection
1443 }
1444 );
1445 };
1446  
1447 # 3. Use non-blocking DBIC in your routes
1448 get '/stats' => sub {
1449 my $c = shift;
1450  
1451 $c->db->resultset('User')
1452 ->search({ active => 1 })
1453 ->all
1454 ->on_done(sub {
1455 my @users = @_;
1456 $c->render(json => { count => scalar @users });
1457 });
1458 };
1459  
1460 app->start;
1461  
1462 =head1 PERFORMANCE TIPS
1463  
1464 =over 4
1465  
1466 =item * Worker Count & CPU Affinity
1467  
1468 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.
1469  
1470 =item * Caching Strategy
1471  
1472 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.
1473  
1474 =item * Batch Operations (Concurrent Execution)
1475  
1476 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.
1477  
1478 =item * Connection Persistence
1479  
1480 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>.
1481  
1482 =item * Timeout Guardrails
1483  
1484 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.
1485  
1486 =back
1487  
1488 =head1 SQL GENERATION CONSISTENCY
1489  
1490 L<DBIx::Class::Async> ensures deterministic SQL generation across multiple
1491 invocations of the same query. This is critical for query caching, performance
1492 analysis, and debugging.
1493  
1494 B<Deterministic Column Ordering>
1495  
1496 When you call C<search()> multiple times on the same ResultSet, the generated
1497 SQL will be identical, including column order:
1498  
1499 my $rs = $schema->resultset('User');
1500  
1501 # These produce identical SQL every time
1502 my $query1 = $rs->search({})->as_query;
1503 my $query2 = $rs->search({})->as_query;
1504  
1505 # SELECT me.id, me.name, me.email, ... FROM users me
1506 # (same order on every call)
1507  
1508 This consistency is maintained even with complex attribute merging:
1509  
1510 my $rs = $schema->resultset('User')
1511 ->search({}, { join => 'orders' })
1512 ->search({}, { join => 'profile' });
1513  
1514 # Joins are deduplicated and ordered consistently
1515  
1516 B<Attribute Deduplication>
1517  
1518 When chaining C<search()> calls, accumulating attributes (C<join>, C<prefetch>,
1519 C<columns>, C<select>, C<as>, C<order_by>, C<group_by>, C<having>) are
1520 automatically deduplicated:
1521  
1522 my $rs = $schema->resultset('User')
1523 ->search({}, { join => 'orders' })
1524 ->search({}, { join => 'orders' }) # Deduplicated
1525 ->search({}, { join => 'profile' });
1526  
1527 # Results in: JOIN orders, JOIN profile (not duplicate orders)
1528  
1529 Deduplication uses a stable serialisation of nested structures, so these
1530 are correctly recognised as duplicates:
1531  
1532 { orders => 'items' } # Same as:
1533 { orders => 'items' } # This duplicate
1534  
1535 B<Benefits>
1536  
1537 =over 4
1538  
1539 =item * B<Query Caching> - Identical SQL enables effective query caching
1540  
1541 =item * B<Performance Analysis> - Consistent SQL makes it easier to identify
1542 slow queries in logs
1543  
1544 =item * B<Testing> - Predictable SQL generation makes testing more reliable
1545  
1546 =item * B<Debugging> - Easier to trace and compare queries
1547  
1548 =back
1549  
1550 B<Debugging SQL>
1551  
1552 You can inspect generated SQL using the C<as_query> method or by enabling
1553 debug mode:
1554  
1555 # Using as_query
1556 my $rs = $schema->resultset('User')->search({ active => 1 });
1557 my $query = $rs->as_query;
1558 # Extract SQL from the returned structure
1559  
1560 # Using debug mode
1561 $schema->storage->debug(1);
1562 $rs->all; # SQL printed to STDERR in worker processes
1563  
1564 See L<debugobj|DBIx::Class::Async::Storage::DBI/debugobj> and
1565 L<debug|DBIx::Class::Async::Storage::DBI/debug> for more information on SQL
1566 debugging.
1567  
1568 =head1 ERROR HANDLING
1569  
1570 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.
1571  
1572 =over 4
1573  
1574 =item * Worker Connectivity
1575  
1576 If a worker cannot connect to the DB, it will throw an exception during the first query or a health check.
1577  
1578 =item * Automatic Retries
1579  
1580 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).
1581  
1582 =item * Serialisation Failures
1583  
1584 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.
1585  
1586 =back
1587  
1588 =head1 METRICS
1589  
1590 If C<< enable_metrics => 1 >> is passed to the constructor and L<Metrics::Any> is available, the following gauges and counters are tracked:
1591  
1592 +------------------------------------+-----------+-----------------------------------------------------+
1593 | Metric | Type | Description |
1594 +------------------------------------+-----------+-----------------------------------------------------+
1595 | C<db_async_queries_total> | Counter | Total number of operations sent to workers. |
1596 | C<db_async_cache_hits_total> | Counter | Queries resolved via the internal C<CHI> cache. |
1597 | C<db_async_query_duration_seconds> | Histogram | Latency distribution of database operations. |
1598 | C<db_async_workers_active> | Gauge | Number of workers passing the periodic health check.|
1599 +------------------------------------+-----------+-----------------------------------------------------+
1600  
1601 =head1 DEDICATION
1602  
1603 This module is dedicated to the memory of B<Matt S. Trout (mst)>,
1604 a brilliant contributor to the Perl community, L<DBIx::Class> core developer,
1605 and friend who is deeply missed.
1606  
1607 =head1 AUTHOR
1608  
1609 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
1610  
1611 =head1 REPOSITORY
1612  
1613 L<https://github.com/manwar/DBIx-Class-Async>
1614  
1615 =head1 BUGS
1616  
1617 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/DBIx-Class-Async/issues>.
1618 I will be notified and then you'll automatically be notified of progress on your
1619 bug as I make changes.
1620  
1621 =head1 SUPPORT
1622  
1623 You can find documentation for this module with the perldoc command.
1624  
1625 perldoc DBIx::Class::Async
1626  
1627 You can also look for information at:
1628  
1629 =over 4
1630  
1631 =item * BUG Report
1632  
1633 L<https://github.com/manwar/DBIx-Class-Async/issues>
1634  
1635 =item * CPAN Ratings
1636  
1637 L<http://cpanratings.perl.org/d/DBIx-Class-Async>
1638  
1639 =item * Search MetaCPAN
1640  
1641 L<https://metacpan.org/dist/DBIx-Class-Async/>
1642  
1643 =back
1644  
1645 =head1 LICENSE AND COPYRIGHT
1646  
1647 Copyright (C) 2026 Mohammad Sajid Anwar.
1648  
1649 This program is free software; you can redistribute it and / or modify it under
1650 the terms of the the Artistic License (2.0). You may obtain a copy of the full
1651 license at:
1652 L<http://www.perlfoundation.org/artistic_license_2_0>
1653 Any use, modification, and distribution of the Standard or Modified Versions is
1654 governed by this Artistic License.By using, modifying or distributing the Package,
1655 you accept this license. Do not use, modify, or distribute the Package, if you do
1656 not accept this license.
1657 If your Modified Version has been derived from a Modified Version made by someone
1658 other than you,you are nevertheless required to ensure that your Modified Version
1659 complies with the requirements of this license.
1660 This license does not grant you the right to use any trademark, service mark,
1661 tradename, or logo of the Copyright Holder.
1662 This license includes the non-exclusive, worldwide, free-of-charge patent license
1663 to make, have made, use, offer to sell, sell, import and otherwise transfer the
1664 Package with respect to any patent claims licensable by the Copyright Holder that
1665 are necessarily infringed by the Package. If you institute patent litigation
1666 (including a cross-claim or counterclaim) against any party alleging that the
1667 Package constitutes direct or contributory patent infringement,then this Artistic
1668 License to you shall terminate on the date that such litigation is filed.
1669 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
1670 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
1671 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
1672 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
1673 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
1674 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
1675 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1676  
1677 =cut
1678  
1679 100 1; # End of DBIx::Class::Async
↑ Summary Async/Row.pm »