Async/Schema.pm

filter: Statementstmt 83.4% 293 / 351 Branchbran 62.5% 90 / 144 Conditioncond 51.5% 51 / 99 MC/DCmcdc 29.8% 17 / 57 Subroutinesub 86.3% 57 / 66 Podpod 56.4% 22 / 39 totaltotal 70.1% 530 / 756 CC 115 SCAR 21.0
CC
115
Cov
73%
_record_metric
28.7
connect
25.8
source_
20.0
CRAP 8.2
« Async/Exception/Factory.pm ↑ Summary Async/Storage/DBI.pm »
1 package DBIx::Class::Async::Schema;
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.2.0');
8 100 our $AUTHORITY = 'cpan:MANWAR';
9  
10 =encoding utf8
11  
12 =head1 NAME
13  
14 DBIx::Class::Async::Schema - Non-blocking, worker-pool based Proxy for DBIx::Class::Schema
15  
16 =head1 VERSION
17  
18 Version v1.2.0
19  
20 =head1 SYNOPSIS
21  
22 use IO::Async::Loop;
23 use DBIx::Class::Async::Schema;
24  
25 my $loop = IO::Async::Loop->new;
26  
27 # Connect returns a proxy object immediately
28 my $schema = DBIx::Class::Async::Schema->connect(
29 "dbi:SQLite:dbname=myapp.db", undef, undef, {},
30 {
31 schema_class => 'MyApp::Schema',
32 workers => 4,
33 enable_metrics => 1,
34 loop => $loop,
35 }
36 );
37  
38 # Use the 'await' helper for one-off scripts
39 my $count = $schema->await( $schema->resultset('User')->count_future );
40  
41 # Or use standard Future chaining for web/event apps
42 $schema->resultset('User')->find_future(1)->then(sub {
43 my $user = shift;
44 print "Found async user: " . $user->name;
45 })->retain;
46  
47 =head1 DESCRIPTION
48  
49 C<DBIx::Class::Async::Schema> acts as a non-blocking bridge to your standard
50 L<DBIx::Class> schemas. Instead of executing queries in the main event loop
51 (which would block your UI or web server), this module offloads queries to a
52 managed pool of background worker processes.
53  
54 =cut
55  
56 100 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
57  
58 100 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
59 100 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 100 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 100 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
62 100 ▶use DBIx::Class::Async;
Subroutine BEGIN: called CC=1 SCAR=0.0
63 100 ▶use DBIx::Class::Async::Storage;
Subroutine BEGIN: called CC=1 SCAR=0.0
64 100 ▶use DBIx::Class::Async::ResultSet;
Subroutine BEGIN: called CC=1 SCAR=0.0
65 100 ▶use DBIx::Class::Async::Storage::DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
66 100 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
67  
68 100 our $METRICS;
69 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
70  
71 =head1 METHODS
72  
73 =head2 connect
74  
75 my $schema = DBIx::Class::Async::Schema->connect($dsn, $user, $pass, $dbi_attrs, \%async_attrs);
76  
77 Initialises the worker pool and returns a proxy schema instance.
78  
79 =over 4
80  
81 =item * C<schema_class> (Required): The name of your existing DBIC Schema class.
82  
83 =item * C<workers>: Number of background processes (Default: 2).
84  
85 =item * C<loop>: An L<IO::Async::Loop> instance. If not provided, one will be created.
86  
87 =item * C<enable_retry>: Automatically retry deadlocks/transient errors.
88  
89 =back
90  
91 =cut
92  
93 119 ▶sub connect {
Subroutine connect: called CC=17 SCAR=32.5
Pod documented
94 119 my ($class, @args) = @_;
95  
96 # Separate async options from connect_info
97 119 my $async_options = {};
98 119 ▶ if (ref $args[-1] eq 'HASH' && !exists $args[-1]->{RaiseError}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $args[-1] eq "HASH" and not exists $args[-1]{"RaiseError"}) 118 1 119
Condition66%2/3
ref $args[-1] eq "HASH" and not exists $args[-1]{"RaiseError"}
!ll&&!rl&&r
10118
MC/DC50%1/2
ref $args[-1] eq "HASH" and not exists $args[-1]{"RaiseError"}
ref $args[-1] eq "HASH" not exists $args[-1]{"RaiseError"}
Truth table66%2/3
A and not(B)
A= ref $args[-1] eq "HASH"B= not exists $args[-1]{"RaiseError"}
ABresult
0X0
100
111
99 118 $async_options = pop @args;
100 }
101  
102 my $schema_class = $async_options->{schema_class}
103 119 ▶ or croak "schema_class is required in async options";
Branch: 1 branch
BranchTrueFalseTotal
my $schema_class = $async_options->{"schema_class"} or croak("schema_class is required in async options") 117 2 119
104  
105 # CPANSec CWE-94 hardening: validate the class name looks like a legal
106 # Perl package name before any loading attempt below. Every branch
107 # here used to hand $schema_class straight to eval STRING (either via
108 # "require $schema_class" or, worse, an interpolated
109 # "package main; \$${schema_class}::VERSION ..." assignment), both
110 # execute the interpolated text as Perl source, so an unvalidated
111 # $schema_class is a code-injection vector for any caller that ever
112 # builds this value from anything other than trusted, hardcoded
113 # configuration.
114 117 ▶ croak "Invalid schema_class name: '$schema_class'"
Branch: 1 branch
BranchTrueFalseTotal
unless $schema_class =~ /\A\w+(?:::\w+)*\z/ 1 116 117
115 unless $schema_class =~ /\A\w+(?:::\w+)*\z/;
116  
117 116 my $schema_loaded = 0;
118 116 ▶ if (eval { $schema_class->can('connect') }) {
Branch: 2 branches
BranchTrueFalseTotal
if (eval { do { $schema_class->can('connect') } }) { } 35 81 116
elsif (eval { do { DBIx::Class::Async::_safe_require_class($schema_class) } }) { } 81 0 81
119 35 $schema_loaded = 1;
120 }
121 81 elsif (eval { DBIx::Class::Async::_safe_require_class($schema_class) }) {
122 81 $schema_loaded = 1;
123 }
124 else {
125 # Fallback for schema classes defined inline in the caller's own
126 # script (no separate .pm file to require): fake a VERSION so it's
127 # considered loaded. $schema_class is already validated above, so
128 # this symbolic-reference assignment cannot execute injected code
129 # the way the previous eval-string form could.
130 100 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
131 0 ▶ ${"${schema_class}::VERSION"} ||= '0.01';
Condition0%0/2
${"${schema_class}::VERSION";} ||= "0.01"
l!l
00
MC/DC0%0/1
${"${schema_class}::VERSION";} ||= "0.01"
${"${schema_class}::VERSION";}
Truth table0%0/2
A
A= ${"${schema_class}::VERSION";}
Aresult
11
00
132 0 $schema_loaded = 1;
133 }
134  
135 116 ▶ unless ($schema_loaded) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($schema_loaded) 0 116 116
136 0 croak "Cannot load schema class $schema_class: $@";
137 }
138  
139 116 ▶ $async_options->{cache_ttl} //= 0; # Caching is OFF by default.
Condition100%2/2
$async_options->{"cache_ttl"} //= 0
l!l
9323
MC/DC100%1/1
$async_options->{"cache_ttl"} //= 0
$async_options->{"cache_ttl"}
Truth table100%2/2
A
A= $async_options->{"cache_ttl"}
Aresult
11
00
140  
141 116 my $async_db = eval {
142 116 DBIx::Class::Async->create_async_db(
143 schema_class => $schema_class,
144 connect_info => \@args,
145 %$async_options,
146 );
147 };
148  
149 116 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 116 116
150 0 croak "Failed to create async engine: $@";
151 }
152  
153 116 my $native_schema = $schema_class->connect(@args);
154  
155 116 my $self = bless {
156 _async_db => $async_db,
157 _native_schema => $native_schema,
158 _sources_cache => {},
159 }, $class;
160  
161 # Populate the inflator map
162 116 $async_db->{_custom_inflators} = $self->_build_inflator_map($native_schema);
163  
164 # Store the datetime formatter once at connect time.
165 # _inflate_row uses this to re-inflate datetime columns that
166 # InflateColumn::DateTime handles in the worker but sends back
167 # as raw strings to the parent.
168 116 ▶ my $dsn = ref($args[0]) eq 'ARRAY' ? $args[0][0] : $args[0] // '';
Branch: 1 branch
BranchTrueFalseTotal
ref $args[0] eq 'ARRAY' ? : 0 116 116
Condition50%1/2
$args[0] // ""
l!l
1160
MC/DC0%0/1
$args[0] // ""
$args[0]
Truth table50%1/2
A
A= $args[0]
Aresult
11
00
169 116 my $formatter;
170 116 ▶ if ($dsn =~ /dbi:Pg/i) {
Branch: 3 branches
BranchTrueFalseTotal
if ($dsn =~ /dbi:Pg/i) { } 0 116 116
elsif ($dsn =~ /dbi:mysql/i) { } 0 116 116
elsif ($dsn =~ /dbi:SQLite/i) { } 116 0 116
171 0 eval { require DateTime::Format::Pg;
172 0 $formatter = DateTime::Format::Pg->new };
173 }
174 elsif ($dsn =~ /dbi:mysql/i) {
175 0 eval { require DateTime::Format::MySQL;
176 0 $formatter = DateTime::Format::MySQL->new };
177 }
178 elsif ($dsn =~ /dbi:SQLite/i) {
179 116 eval { require DateTime::Format::SQLite;
180 0 $formatter = DateTime::Format::SQLite->new };
181 }
182 116 ▶ $async_db->{_datetime_formatter} = $formatter if $formatter;
Branch: 1 branch
BranchTrueFalseTotal
if $formatter 0 116 116
183  
184 116 my $storage = DBIx::Class::Async::Storage::DBI->new(
185 schema => $self,
186 async_db => $async_db,
187 );
188  
189 116 $self->{_storage} = $storage;
190  
191 116 return $self;
192 }
193  
194 259 ▶sub await {
Subroutine await: called CC=8 SCAR=20.8
Pod documented
195 259 my ($self, $future) = @_;
196  
197 259 my $loop = $self->{_async_db}->{_loop};
198 259 my @results = $loop->await($future);
199  
200 # Unwrap nested Futures
201 259 ▶ while (@results == 1
Branch: 1 branch
BranchTrueFalseTotal
if (@results == 1 and defined $results[0] and builtin::blessed($results[0]) and $results[0]->isa("Future")) 259 254 513
Condition100%9/9
@results == 1 and defined $results[0] and builtin::blessed($results[0]) and $results[0]->isa("Future")
!ll&&!rl&&r
19757259
@results == 1 and defined $results[0] and builtin::blessed($results[0])
!ll&&!rl&&r
8189316
@results == 1 and defined $results[0]
!ll&&!rl&&r
62505
MC/DC100%4/4
@results == 1 and defined $results[0] and builtin::blessed($results[0]) and $results[0]->isa("Future")
@results == 1 defined $results[0] builtin::blessed($results[0]) $results[0]->isa("Future")
Truth table100%5/5
A and B and C and D
A= @results == 1B= defined $results[0]C= builtin::blessed($results[0])D= $results[0]->isa("Future")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
202 && defined $results[0]
203 && Scalar::Util::blessed($results[0])
204 && $results[0]->isa('Future')) {
205  
206 259 ▶ if (!$results[0]->is_ready) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $results[0]->is_ready) { } 0 259 259
elsif ($results[0]->is_failed) { } 5 254 259
207 0 @results = $loop->await($results[0]);
208 } elsif ($results[0]->is_failed) {
209 5 my ($error) = $results[0]->failure;
210 5 die $error;
211 } else {
212 254 @results = $results[0]->get;
213 }
214 }
215  
216 254 ▶ return wantarray ? @results : $results[0];
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 4 250 254
217 }
218  
219 4 ▶sub await_all {
Subroutine await_all: called CC=1 SCAR=0.0
Pod documented
220 4 my ($self, @futures) = @_;
221  
222 4 my $combined = Future->needs_all(@futures);
223 4 return $self->await($combined);
224 }
225  
226 2 ▶sub run_parallel {
Subroutine run_parallel: called CC=1 SCAR=0.0
Pod documented
227 2 my ($self, @tasks) = @_;
228 2 my @futures = map { $_->($self) } @tasks;
229 2 return Future->needs_all(@futures);
230 }
231  
232 # Cache specific
233 2 ▶sub cache_hits { shift->{_async_db}->{_stats}->{_cache_hits} // 0 }
Subroutine cache_hits: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"_async_db"}{"_stats"}{"_cache_hits"} // 0
l!l
20
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_cache_hits"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_cache_hits"}
Truth table50%1/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_cache_hits"}
Aresult
11
00
234 2 ▶sub cache_misses { shift->{_async_db}->{_stats}->{_cache_misses} // 0 }
Subroutine cache_misses: called CC=2 SCAR=7.6
Pod undocumented
Condition50%1/2
+(shift())->{"_async_db"}{"_stats"}{"_cache_misses"} // 0
l!l
20
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_cache_misses"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_cache_misses"}
Truth table50%1/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_cache_misses"}
Aresult
11
00
235 0 ▶sub cache_retries { shift->{_async_db}->{_stats}->{_retries} // 0 }
Subroutine cache_retries: not called CC=2 SCAR=17.9
Pod undocumented
Condition0%0/2
+(shift())->{"_async_db"}{"_stats"}{"_retries"} // 0
l!l
00
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_retries"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_retries"}
Truth table0%0/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_retries"}
Aresult
11
00
236  
237 # Execution specific
238 0 ▶sub total_queries { shift->{_async_db}->{_stats}->{_queries} // 0 }
Subroutine total_queries: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
+(shift())->{"_async_db"}{"_stats"}{"_queries"} // 0
l!l
00
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_queries"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_queries"}
Truth table0%0/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_queries"}
Aresult
11
00
239 0 ▶sub error_count { shift->{_async_db}->{_stats}->{_errors} // 0 }
Subroutine error_count: not called CC=2 SCAR=17.9
Pod documented
Condition0%0/2
+(shift())->{"_async_db"}{"_stats"}{"_errors"} // 0
l!l
00
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_errors"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_errors"}
Truth table0%0/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_errors"}
Aresult
11
00
240 0 ▶sub deadlock_count{ shift->{_async_db}->{_stats}->{_deadlocks} // 0 }
Subroutine deadlock_count: not called CC=2 SCAR=17.9
Pod undocumented
Condition0%0/2
+(shift())->{"_async_db"}{"_stats"}{"_deadlocks"} // 0
l!l
00
MC/DC0%0/1
+(shift())->{"_async_db"}{"_stats"}{"_deadlocks"} // 0
+(shift())->{"_async_db"}{"_stats"}{"_deadlocks"}
Truth table0%0/2
A
A= +(shift())->{"_async_db"}{"_stats"}{"_deadlocks"}
Aresult
11
00
241  
242  
243 974 ▶sub class {
Subroutine class: called CC=4 SCAR=13.9
Pod documented
244 974 my ($self, $source_name) = @_;
245  
246 974 ▶ croak("source_name required") unless defined $source_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source_name 2 972 974
247  
248 # Fetch metadata (this uses your existing _sources_cache)
249 972 my $source = eval { $self->source($source_name) };
250  
251 972 ▶ if ($@ || !$source) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $source) 4 968 972
Condition66%2/3
$@ or not $source
l!l&&r!l&&!r
04968
MC/DC50%1/2
$@ or not $source
$@ not $source
Truth table66%2/3
A or not(B)
A= $@B= not $source
ABresult
1X1
011
000
252 4 croak("No such source '$source_name'");
253 }
254  
255 968 return $source->{result_class};
256 }
257  
258 32 ▶sub clone {
Subroutine clone: called CC=4 SCAR=13.9
Pod documented
259 32 my ($self, %args) = @_;
260  
261 32 my $orig_db = $self->{_async_db};
262  
263 # Decide whether to share the parent's worker pool or create a new one.
264 #
265 # DEFAULT (no arguments): share the pool.
266 # Clones that connect to the same database have no need for independent
267 # worker processes. Sharing avoids spawning/tearing down extra
268 # IO::Async::Function instances, which is the root cause of the SEGV
269 # in global destruction when many clones are created in tests.
270 #
271 # EXPLICIT workers => N: create an independent pool.
272 # This supports the legitimate use case of a "heavy reporting" clone
273 # with more workers than the parent, or a "read-only" clone with fewer.
274 # The caller is responsible for calling disconnect() on these clones.
275 32 my $independent = exists $args{workers};
276 32 my $new_async_db;
277  
278 32 ▶ if ($independent && $orig_db) {
Branch: 1 branch
BranchTrueFalseTotal
if ($independent and $orig_db) { } 2 30 32
Condition66%2/3
$independent and $orig_db
!ll&&!rl&&r
3002
MC/DC50%1/2
$independent and $orig_db
$independent $orig_db
Truth table66%2/3
A and B
A= $independentB= $orig_db
ABresult
0X0
100
111
279 $new_async_db = DBIx::Class::Async->create_async_db(
280 schema_class => $orig_db->{_schema_class},
281 connect_info => $orig_db->{_connect_info},
282 workers => $args{workers},
283 async_loop => $orig_db->{_loop},
284 enable_metrics => $orig_db->{_enable_metrics},
285 enable_retry => $orig_db->{_enable_retry},
286 2 );
287 }
288 else {
289 30 $new_async_db = $orig_db; # shared - not a new pool
290 }
291  
292 32 my $new_self = bless {
293 %$self,
294 _async_db => $new_async_db,
295 _sources_cache => {},
296 _is_clone => !$independent, # shared clones must not disconnect workers
297 }, ref $self;
298  
299 # Re-attach storage
300 32 ▶ if ($new_async_db) {
Branch: 1 branch
BranchTrueFalseTotal
if ($new_async_db) 32 0 32
301 32 $new_self->{_storage} = DBIx::Class::Async::Storage::DBI->new(
302 schema => $new_self,
303 async_db => $new_async_db,
304 );
305 }
306  
307 32 return $new_self;
308 }
309  
310 100 ▶sub deploy {
Subroutine deploy: called CC=1 SCAR=0.0
Pod undocumented
311 100 my ($self, $sqlt_args, $dir) = @_;
312  
313 100 my $async_db = $self->{_async_db};
314  
315 return DBIx::Class::Async::_call_worker(
316 $async_db, 'deploy', [ $sqlt_args, $dir ],
317 100 ▶ )->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
318 100 my ($res) = @_;
319  
320 # Return the result (usually { success => 1 } or similar)
321 # or return $self if you want to allow chaining.
322 100 return $res;
323 100 });
324 }
325  
326 117 ▶sub disconnect {
Subroutine disconnect: called CC=2 SCAR=7.0
Pod documented
327 117 my $self = shift;
328  
329 # Delegate all worker/loop cleanup to the functional library, which
330 # handles the correct remove()-before-stop() ordering and cleans up
331 # IO::Async global state (ONE_TRUE_LOOP, SIGCHLD handler).
332 117 ▶ if (ref $self->{_async_db} eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $self->{"_async_db"} eq "HASH") 117 0 117
333 117 DBIx::Class::Async::disconnect($self->{_async_db});
334 }
335  
336 # Remove the manager reference and flush metadata cache.
337 117 delete $self->{_async_db};
338 117 $self->{_sources_cache} = {};
339  
340 117 return $self;
341 }
342  
343 142 ▶sub DESTROY {
Subroutine DESTROY: called CC=4 SCAR=13.9
344 142 my $self = shift;
345  
346 # Skip cleanup during global destruction: by the time Perl runs END
347 # and tears down globals, IO::Async's XS internals may already be
348 # partially freed. Calling disconnect() at that point risks a SEGV.
349 # Workers are stopped earlier (during RUN phase) when the schema
350 # object normally goes out of scope.
351 142 ▶ return if ${^GLOBAL_PHASE} eq 'DESTRUCT';
Branch: 1 branch
BranchTrueFalseTotal
if ${^GLOBAL_PHASE} eq "DESTRUCT" 0 142 142
352  
353 # Clones share the parent's worker pool (_is_clone flag set in clone()).
354 # Only the original schema object owns the workers and should shut them
355 # down. Clones just drop their reference to the shared _async_db.
356 142 ▶ if ($self->{_is_clone}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_is_clone"}) 30 112 142
357 30 delete $self->{_async_db};
358 30 return;
359 }
360  
361 112 ▶ $self->disconnect if $self->{_async_db};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_async_db"} 9 103 112
362 }
363  
364 2 ▶sub health_check {
Subroutine health_check: called CC=2 SCAR=7.3
Pod undocumented
365 2 my ($self) = @_;
366  
367 2 my $async_db = $self->{_async_db};
368  
369 2 my @futures;
370 2 for (1 .. $async_db->{_workers_config}->{_count}) {
371 4 push @futures, DBIx::Class::Async::_call_worker($async_db, 'ping', {});
372 }
373  
374 2 ▶ return Future->wait_all(@futures)->then(sub {
Subroutine __ANON__: called CC=4 SCAR=15.9
375 2 my @res_futures = @_;
376  
377 # Count how many actually returned a successful ping
378 my $healthy_count = grep {
379 2 ▶ $_->is_done && !$_->failure && ($_->get->{success} // 0)
Condition37%3/8
$_->is_done && !$_->failure && ($_->get->{'success'} // 0)
!ll&&!rl&&r
004
$_->is_done and not $_->failure
!ll&&!rl&&r
004
$_->get->{"success"} // 0
l!l
40
MC/DC0%0/3
$_->is_done && !$_->failure && ($_->get->{'success'} // 0)
$_->is_done not $_->failure $_->get->{"success"}
Truth table25%1/4
A and not(B) && C
A= $_->is_doneB= not $_->failureC= $_->get->{"success"}
ABCresult
0XX0
10X0
1100
1111
380 } @res_futures;
381  
382 # Record the metric
383 2 $self->_record_metric('set', 'db_async_workers_active', $healthy_count);
384  
385 2 return Future->done($healthy_count);
386 2 });
387 }
388  
389 1 ▶sub inflate_column {
Subroutine inflate_column: called CC=3 SCAR=12.2
Pod undocumented
390 1 my ($self, $source_name, $column, $handlers) = @_;
391  
392 1 my $schema = $self->{_native_schema};
393  
394 1 my @known_sources = $schema->sources;
395 1 warn "[PID $$] Parent Schema class: " . ref($schema) if ASYNC_TRACE;
396  
397 # Attempt lookup
398 1 my $source = eval { $schema->source($source_name) };
399  
400 1 ▶ if (!$source) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($source) 0 1 1
401 0 warn "[PID $$] Source '$source_name' not found. Attempting force-load via resultset..."
402 if ASYNC_TRACE;
403 0 eval { $schema->resultset($source_name) };
404 0 $source = eval { $schema->source($source_name) };
405 }
406  
407 1 ▶ croak "Could not find result source for '$source_name' in Parent process."
Branch: 1 branch
BranchTrueFalseTotal
unless $source 0 1 1
408 unless $source;
409  
410 # Apply the handlers to the Parent's schema instance
411 1 my $col_info = $source->column_info($column);
412 $source->add_column($column => {
413 %$col_info,
414 inflate => $handlers->{inflate},
415 deflate => $handlers->{deflate},
416 1 });
417  
418 # Registry for Parent-side inflation of results coming back from Worker
419 1 $self->{_async_db}{_custom_inflators}{$source_name}{$column} = $handlers;
420 }
421  
422 1 ▶sub loop { shift->{_async_db}->{_loop} }
Subroutine loop: called CC=1 SCAR=0.0
Pod undocumented
423 1 ▶sub stats { shift->{_async_db}->{_stats} }
Subroutine stats: called CC=1 SCAR=0.0
Pod undocumented
424 0 ▶sub native_schema { shift->{_native_schema} }
Subroutine native_schema: not called CC=1 SCAR=6.9
Pod undocumented
425  
426 18 ▶sub populate {
Subroutine populate: called CC=6 SCAR=18.0
Pod documented
427 18 my ($self, $source_name, $data) = @_;
428  
429 # 1. Standard Guard Clauses
430 18 ▶ croak("Schema is disconnected") unless $self->{_async_db};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_async_db"} 0 18 18
431 18 ▶ croak("source_name required") unless defined $source_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source_name 1 17 18
432 17 ▶ croak("data required") unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 17 17
433 17 ▶ croak("data must be an arrayref") unless ref $data eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "ARRAY" 1 16 17
434 16 ▶ croak("data cannot be empty") unless scalar @$data;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$data 1 15 16
435  
436 # 2. Delegate to ResultSet
437 # This creates the RS and immediately triggers the bulk insert logic
438 15 return $self->resultset($source_name)->populate($data);
439 }
440  
441 1 ▶sub register_class {
Subroutine register_class: called CC=7 SCAR=26.8
Pod undocumented
442 1 my ($self, $source_name, $result_class) = @_;
443  
444 1 ▶ croak("source_name and result_class required")
Branch: 1 branch
BranchTrueFalseTotal
unless $source_name and $result_class 0 1 1
Condition33%1/3
$source_name and $result_class
!ll&&!rl&&r
001
MC/DC0%0/2
$source_name and $result_class
$source_name $result_class
Truth table33%1/3
A and B
A= $source_nameB= $result_class
ABresult
0X0
100
111
445 unless $source_name && $result_class;
446  
447 # 1. Load the class in the Parent process
448 # We do this to extract metadata (columns, relationships)
449 1 ▶ unless ($result_class->can('result_source_instance')) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($result_class->can("result_source_instance")) 0 1 1
450 0 eval { DBIx::Class::Async::_safe_require_class($result_class) };
451 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
452 0 croak("Failed to load Result class '$result_class': $@");
453 }
454 }
455  
456 # 2. Get the ResultSource instance from the class
457 # This contains the column definitions and table name
458 1 my $source = eval { $result_class->result_source_instance };
459 1 ▶ if ($@ || !$source) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $source) 0 1 1
Condition33%1/3
$@ or not $source
l!l&&r!l&&!r
001
MC/DC0%0/2
$@ or not $source
$@ not $source
Truth table33%1/3
A or not(B)
A= $@B= not $source
ABresult
1X1
011
000
460 0 croak("Class '$result_class' does not appear to be a valid DBIx::Class Result class");
461 }
462  
463 # 3. Register the source
464 # This will populate your { _sources_cache } or internal metadata map
465 1 return $self->register_source($source_name, $source);
466 }
467  
468 2 ▶sub register_source {
Subroutine register_source: called CC=2 SCAR=7.0
Pod undocumented
469 2 my ($self, $source_name, $source) = @_;
470  
471 # 1. Update Parent Instance
472 2 $self->{_sources_cache}->{$source_name} = $source;
473  
474 # 2. Track this for Workers
475 # Store the 'source' metadata so we can send it to workers if needed
476 2 $self->{_dynamic_sources}->{$source_name} = $source;
477  
478 # 3. Class-level registration (for future local instances)
479 2 my $schema_class = $self->{_schema_class};
480 2 ▶ $schema_class->register_source($source_name, $source) if $schema_class;
Branch: 1 branch
BranchTrueFalseTotal
if $schema_class 0 2 2
481  
482 2 return $source;
483 }
484  
485 =head2 resultset
486  
487 my $rs = $schema->resultset('Source');
488  
489 Returns a L<DBIx::Class::Async::ResultSet> object. This RS behaves like
490 standard DBIC but provides C<*_future> variants (e.g., C<all_future>,
491 C<count_future>).
492  
493 =cut
494  
495 938 ▶sub resultset {
Subroutine resultset: called CC=4 SCAR=13.9
Pod documented
496 938 my ($self, $source_name) = @_;
497  
498 938 ▶ unless (defined $source_name && length $source_name) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $source_name and length $source_name) 1 937 938
Condition66%2/3
defined $source_name and length $source_name
!ll&&!rl&&r
10937
MC/DC50%1/2
defined $source_name and length $source_name
defined $source_name length $source_name
Truth table66%2/3
A and B
A= defined $source_nameB= length $source_name
ABresult
0X0
100
111
499 1 croak("resultset() requires a source name");
500 }
501  
502 # 1. Check our cache for the source metadata
503 # (In DBIC, a 'source' contains column info, class names, etc.)
504 937 my $source = $self->{_sources_cache}{$source_name};
505  
506 937 ▶ unless ($source) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($source) 152 785 937
507 # Fetch metadata from the real DBIx::Class::Schema class
508 152 $source = $self->_resolve_source($source_name);
509 146 $self->{_sources_cache}{$source_name} = $source;
510 }
511  
512 931 my $result_class = $self->class($source_name);
513 # 2. Create the new Async ResultSet
514 return DBIx::Class::Async::ResultSet->new(
515 source_name => $source_name,
516 schema_instance => $self, # Access to _record_metric
517 async_db => $self->{_async_db}, # Access to _call_worker
518 931 result_class => $result_class,
519 );
520 }
521  
522 4 ▶sub search_with_prefetch {
Subroutine search_with_prefetch: called CC=2 SCAR=6.9
Pod documented
523 4 my ($self, $source_name, $cond, $prefetch, $attrs) = @_;
524  
525 4 ▶ $attrs ||= {};
Condition100%2/2
$attrs ||= {}
l!l
22
MC/DC100%1/1
$attrs ||= {}
$attrs
Truth table100%2/2
A
A= $attrs
Aresult
11
00
526 4 my %merged_attrs = ( %$attrs, prefetch => $prefetch, collapse => 1 );
527  
528 return $self->resultset($source_name)
529 ->search($cond, \%merged_attrs)
530 ->all_future
531 4 ▶ ->then(sub { my ($rows) = @_; return $rows; });
Subroutine __ANON__: called CC=1 SCAR=0.0
532 }
533  
534 0 ▶sub set_default_context {
Subroutine set_default_context: not called CC=1 SCAR=6.9
Pod undocumented
535 0 my $self = shift;
536  
537 # No-op for compatibility with external libraries
538 # that expect a standard DBIC Schema interface.
539 # In an Async world, we avoid global context to prevent
540 # cross-talk between event loop cycles.
541  
542 0 return $self;
543 }
544  
545 3 ▶sub schema_version {
Subroutine schema_version: called CC=3 SCAR=11.2
Pod documented
546 3 my $self = shift;
547 3 my $class = $self->{_async_db}->{_schema_class};
548  
549 3 ▶ unless ($class) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class) 1 2 3
550 1 croak("schema_class is not defined in " . ref($self));
551 }
552  
553 2 ▶ return $class->schema_version if $class->can('schema_version');
Branch: 1 branch
BranchTrueFalseTotal
if $class->can("schema_version") 2 0 2
554  
555 0 return undef;
556 }
557  
558 0 ▶sub sync_metadata {
Subroutine sync_metadata: not called CC=2 SCAR=17.9
Pod undocumented
559 0 my ($self) = @_;
560  
561 0 my $async_db = $self->{_async_db};
562 0 my @futures;
563  
564 # Ping every worker in the pool
565 0 for (1 .. $async_db->{_workers_config}->{_count}) {
566 0 push @futures, DBIx::Class::Async::_call_worker($async_db, 'ping', {});
567 }
568  
569 0 return Future->wait_all(@futures);
570 }
571  
572 3 ▶sub schema_class { shift->{_async_db}->{_schema_class}; }
Subroutine schema_class: called CC=1 SCAR=0.0
Pod documented
573  
574 0 ▶sub source_ {
Subroutine source_: not called CC=4 SCAR=30.0
Pod undocumented
575 0 my ($self, $source_name) = @_;
576  
577 0 ▶ unless (exists $self->{_sources_cache}{$source_name}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $self->{"_sources_cache"}{$source_name}) 0 0 0
578 0 my $source = eval { $self->{_native_schema}->source($source_name) };
579  
580 0 ▶ croak("No such source '$source_name'") if $@ || !$source;
Branch: 1 branch
BranchTrueFalseTotal
if $@ or not $source 0 0 0
Condition0%0/3
$@ or not $source
l!l&&r!l&&!r
000
MC/DC0%0/2
$@ or not $source
$@ not $source
Truth table0%0/3
A or not(B)
A= $@B= not $source
ABresult
1X1
011
000
581  
582 0 $self->{_sources_cache}{$source_name} = $source;
583 }
584  
585 0 return $self->{_sources_cache}{$source_name};
586 }
587  
588 0 ▶sub sources_ { shift->{_native_schema}->sources; }
Subroutine sources_: not called CC=1 SCAR=6.9
Pod undocumented
589  
590 16 ▶sub storage { shift->{_storage}; }
Subroutine storage: called CC=1 SCAR=0.0
Pod documented
591  
592 1929 ▶sub source {
Subroutine source: called CC=6 SCAR=17.9
Pod documented
593 1929 my ($self, $source_name) = @_;
594  
595 # 1. Retrieve the cached entry
596 1929 my $cached = $self->{_sources_cache}{$source_name};
597  
598 # 2. Check if we need to (re)fetch:
599 # Either we have no entry, or it's a raw HASH (autovivification artifact)
600 1929 ▶ if (!$cached || !blessed($cached)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cached and builtin::blessed($cached)) 180 1749 1929
Condition100%3/3
$cached and builtin::blessed($cached)
!ll&&!rl&&r
341461749
MC/DC100%2/2
$cached and builtin::blessed($cached)
$cached builtin::blessed($cached)
Truth table100%3/3
A and B
A= $cachedB= builtin::blessed($cached)
ABresult
0X0
100
111
601  
602 # Clean up any "ghost" hash before re-fetching
603 180 delete $self->{_sources_cache}{$source_name};
604  
605 # 3. Use the persistent provider to keep ResultSource objects alive
606 180 ▶ $self->{_metadata_provider} ||= do {
Condition66%2/3
$self->{"_metadata_provider"} ||= do { my $class = $self->{"_async_db"}{"_schema_class"}; eval { do { DBIx::Class::Async::_safe_require_class($class) } } or die "Could not load schema class ${class}: $@"; $class->connect(@{$$self{"_async_db"}{"_connect_info"};}) }
l!l&&r!l&&!r
791010
MC/DC0%0/2
$self->{"_metadata_provider"} ||= do { my $class = $self->{"_async_db"}{"_schema_class"}; eval { do { DBIx::Class::Async::_safe_require_class($class) } } or die "Could not load schema class ${class}: $@"; $class->connect(@{$$self{"_async_db"}{"_connect_info"};}) }
$self->{"_metadata_provider"} do { my $class = $self->{"_async_db"}{"_schema_class"}; eval { do { DBIx::Class::Async::_safe_require_class($class) } } or die "Could not load schema class ${class}: $@"; $class->connect(@{$$self{"_async_db"}{"_connect_info"};}) }
Truth table66%2/3
A ||= B
A= $self->{"_metadata_provider"}B= do { my $class = $self->{"_async_db"}{"_schema_class"}; eval { do { DBIx::Class::Async::_safe_require_class($class) } } or die "Could not load schema class ${class}: $@"; $class->connect(@{$$self{"_async_db"}{"_connect_info"};}) }
ABresult
1X1
011
000
607 101 my $class = $self->{_async_db}->{_schema_class};
608 101 ▶ eval { DBIx::Class::Async::_safe_require_class($class) }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { DBIx::Class::Async::_safe_require_class($class) } } or die "Could not load schema class ${class}: $@" 101 0 101
609 or die "Could not load schema class $class: $@";
610 101 $class->connect(@{$self->{_async_db}->{_connect_info}});
611 };
612  
613 # 4. Fetch the source and validate its blessing
614 180 my $source_obj = eval { $self->{_metadata_provider}->source($source_name) };
615  
616 180 ▶ if (blessed($source_obj)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($source_obj)) { } 176 4 180
617 176 $self->{_sources_cache}{$source_name} = $source_obj;
618 } else {
619 4 return undef;
620 }
621 }
622  
623 1925 return $self->{_sources_cache}{$source_name};
624 }
625  
626 6 ▶sub sources {
Subroutine sources: called CC=1 SCAR=0.0
Pod documented
627 6 my $self = shift;
628  
629 6 my $schema_class = $self->{_async_db}->{_schema_class};
630 6 my $connect_info = $self->{_async_db}->{_connect_info};
631 6 my $temp_schema = $schema_class->connect(@{$connect_info});
632 6 my @sources = $temp_schema->sources;
633  
634 6 $temp_schema->storage->disconnect;
635  
636 6 return @sources;
637 }
638  
639 2 ▶sub txn_begin {
Subroutine txn_begin: called CC=1 SCAR=0.0
Pod documented
640 2 my $self = shift;
641  
642 # We return the future so the caller can wait for the 'BEGIN' to finish
643 return DBIx::Class::Async::_call_worker(
644 $self->{_async_db},
645 2 'txn_begin',
646 {}
647 );
648 }
649  
650 1 ▶sub txn_commit {
Subroutine txn_commit: called CC=1 SCAR=0.0
Pod documented
651 1 my $self = shift;
652  
653 return DBIx::Class::Async::_call_worker(
654 $self->{_async_db},
655 1 'txn_commit',
656 {}
657 );
658 }
659  
660 1 ▶sub txn_rollback {
Subroutine txn_rollback: called CC=1 SCAR=0.0
Pod documented
661 1 my $self = shift;
662  
663 return DBIx::Class::Async::_call_worker(
664 $self->{_async_db},
665 1 'txn_rollback',
666 {}
667 );
668 }
669  
670 3 ▶sub txn_do {
Subroutine txn_do: called CC=2 SCAR=7.5
Pod undocumented
671 3 my ($self, $steps) = @_;
672  
673 3 ▶ croak "txn_do requires an ARRAYREF of steps"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $steps eq "ARRAY" 0 3 3
674 unless ref $steps eq 'ARRAY';
675  
676 return DBIx::Class::Async::_call_worker(
677 $self->{_async_db},
678 'txn_do',
679 $steps
680 2 ▶ )->then(sub {
Subroutine __ANON__: called CC=3 SCAR=12.5
681 2 my ($result) = @_;
682 2 ▶ return Future->fail($result->{error}) if ref $result eq 'HASH' && $result->{error};
Branch: 1 branch
BranchTrueFalseTotal
if ref $result eq "HASH" and $result->{"error"} 0 2 2
Condition33%1/3
ref $result eq "HASH" and $result->{"error"}
!ll&&!rl&&r
020
MC/DC0%0/2
ref $result eq "HASH" and $result->{"error"}
ref $result eq "HASH" $result->{"error"}
Truth table33%1/3
A and B
A= ref $result eq "HASH"B= $result->{"error"}
ABresult
0X0
100
111
683 2 return Future->done($result);
684 3 });
685 }
686  
687 6 ▶sub txn_batch {
Subroutine txn_batch: called CC=8 SCAR=23.9
Pod documented
688 6 my ($self, @args) = @_;
689  
690 croak "Async database handle not initialised in schema."
691 6 ▶ unless $self->{_async_db};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_async_db"} 0 6 6
692  
693 # Allow both txn_batch([$h1, $h2]) and txn_batch($h1, $h2)
694 6 ▶ my @operations = (ref $args[0] eq 'ARRAY') ? @{$args[0]} : @args;
Branch: 1 branch
BranchTrueFalseTotal
ref $args[0] eq 'ARRAY' ? : 6 0 6
695  
696 # 1. Parent-side Validation
697 6 for my $op (@operations) {
698 croak "Each operation must be a hashref with 'type' key"
699 13 ▶ unless (ref $op eq 'HASH' && $op->{type});
Branch: 1 branch
BranchTrueFalseTotal
unless ref $op eq "HASH" and $op->{"type"} 0 13 13
Condition33%1/3
ref $op eq "HASH" and $op->{"type"}
!ll&&!rl&&r
0013
MC/DC0%0/2
ref $op eq "HASH" and $op->{"type"}
ref $op eq "HASH" $op->{"type"}
Truth table33%1/3
A and B
A= ref $op eq "HASH"B= $op->{"type"}
ABresult
0X0
100
111
700  
701 13 ▶ if ($op->{type} =~ /^(update|delete|create)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($op->{"type"} =~ /^(update|delete|create)$/) 13 0 13
702 croak "Operation type '$op->{type}' requires 'resultset' parameter"
703 13 ▶ unless $op->{resultset};
Branch: 1 branch
BranchTrueFalseTotal
unless $op->{"resultset"} 0 13 13
704 }
705 }
706  
707 # 2. Direct call to the worker
708 return DBIx::Class::Async::_call_worker(
709 $self->{_async_db},
710 'txn_batch',
711 \@operations
712 5 ▶ )->then(sub {
Subroutine __ANON__: called CC=3 SCAR=13.3
713 5 my ($result) = @_;
714  
715 # Ensure we handle the result correctly
716 5 ▶ if (ref $result eq 'HASH' && $result->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH" and $result->{"error"}) 0 5 5
Condition33%1/3
ref $result eq "HASH" and $result->{"error"}
!ll&&!rl&&r
050
MC/DC0%0/2
ref $result eq "HASH" and $result->{"error"}
ref $result eq "HASH" $result->{"error"}
Truth table33%1/3
A and B
A= ref $result eq "HASH"B= $result->{"error"}
ABresult
0X0
100
111
717 0 return Future->fail($result->{error});
718 }
719  
720 5 return Future->done($result);
721 6 });
722 }
723  
724 3 ▶sub unregister_source {
Subroutine unregister_source: called CC=4 SCAR=14.6
Pod undocumented
725 3 my ($self, $source_name) = @_;
726  
727 3 ▶ croak("source_name is required") unless defined $source_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source_name 0 3 3
728  
729 # 1. Reach into the manager hashref (the "Async DB" manager)
730 3 my $class = $self->{_async_db}->{_schema_class};
731 3 ▶ unless ($class) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($class) 0 3 3
732 0 croak("schema_class is not defined in manager for " . ref($self));
733 }
734  
735 # 2. Local Cache Cleanup
736 # Even if the file stays on disk, we prevent the Parent from
737 # attempting to generate new ResultSets for this source.
738 3 delete $self->{_sources_cache}->{$source_name};
739  
740 # 3. Class-Level Cleanup
741 # This prevents any future workers (or re-initialisations)
742 # from seeing this source definition.
743 3 ▶ if ($class->can('unregister_source')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($class->can("unregister_source")) 3 0 3
744 3 $class->unregister_source($source_name);
745 }
746  
747 3 return $self;
748 }
749  
750 1 ▶sub AUTOLOAD {
Subroutine AUTOLOAD: called CC=6 SCAR=22.9
751 1 my $self = shift;
752  
753 1 ▶ return unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 1 1
754  
755 1 our $AUTOLOAD;
756 1 my ($method) = $AUTOLOAD =~ /([^:]+)$/;
757  
758 1 ▶ return if $method eq 'DESTROY';
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "DESTROY" 0 1 1
759  
760 1 ▶ if ($self->{_async_db} && exists $self->{_async_db}->{schema}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_async_db"} and exists $self->{"_async_db"}{"schema"}) 0 1 1
Condition33%1/3
$self->{"_async_db"} and exists $self->{"_async_db"}{"schema"}
!ll&&!rl&&r
010
MC/DC0%0/2
$self->{"_async_db"} and exists $self->{"_async_db"}{"schema"}
$self->{"_async_db"} exists $self->{"_async_db"}{"schema"}
Truth table33%1/3
A and B
A= $self->{"_async_db"}B= exists $self->{"_async_db"}{"schema"}
ABresult
0X0
100
111
761 0 my $real_schema = $self->{_async_db}->{schema};
762 0 ▶ if ($real_schema->can($method)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($real_schema->can($method)) 0 0 0
763 0 return $real_schema->$method(@_);
764 }
765 }
766  
767 1 croak "Method $method not found in " . ref($self);
768 }
769  
770 #
771 #
772 # PRIVATE METHODS
773  
774 2 ▶sub _record_metric {
Subroutine _record_metric: called CC=7 SCAR=33.6
775 2 my ($self, $type, $name, @args) = @_;
776  
777 # 1. Check if metrics are enabled via the async_db state
778 # 2. Ensure the global $METRICS object exists
779 return unless $self->{_async_db}
780 && $self->{_async_db}{_enable_metrics}
781 2 ▶ && defined $METRICS;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_async_db"} and $self->{"_async_db"}{"_enable_metrics"} and defined $DBIx::Class::Async::Schema::METRICS 2 0 2
Condition33%2/6
$self->{"_async_db"} and $self->{"_async_db"}{"_enable_metrics"} and defined $DBIx::Class::Async::Schema::METRICS
!ll&&!rl&&r
200
$self->{"_async_db"} and $self->{"_async_db"}{"_enable_metrics"}
!ll&&!rl&&r
020
MC/DC0%0/3
$self->{"_async_db"} and $self->{"_async_db"}{"_enable_metrics"} and defined $DBIx::Class::Async::Schema::METRICS
$self->{"_async_db"} $self->{"_async_db"}{"_enable_metrics"} defined $DBIx::Class::Async::Schema::METRICS
Truth table25%1/4
A and B and C
A= $self->{"_async_db"}B= $self->{"_async_db"}{"_enable_metrics"}C= defined $DBIx::Class::Async::Schema::METRICS
ABCresult
0XX0
10X0
1100
1111
782  
783 # 3. Handle different metric types (parity with old design)
784 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
785 # Usage: $schema->_record_metric('inc', 'query_count', 1)
786 0 $METRICS->inc($name, @args);
787 }
788 elsif ($type eq 'observe') {
789 # Usage: $schema->_record_metric('observe', 'query_duration', 0.05)
790 0 $METRICS->observe($name, @args);
791 }
792 elsif ($type eq 'set') {
793 # Usage: $schema->_record_metric('set', 'worker_pool_size', 5)
794 0 $METRICS->set($name, @args);
795 }
796  
797 0 return;
798 }
799  
800 152 ▶sub _resolve_source {
Subroutine _resolve_source: called CC=5 SCAR=16.2
801 152 my ($self, $source_name) = @_;
802  
803 152 ▶ croak "Missing source name." unless defined $source_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $source_name 0 152 152
804  
805 152 my $schema_class = $self->{_async_db}{_schema_class};
806  
807 152 ▶ croak "Schema class not found." unless defined $schema_class;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $schema_class 1 151 152
808  
809 # 1. Ask the main DBIC Schema class for the source metadata
810 # We call this on the class name, not an instance, to stay "light"
811 151 my $source = eval { $schema_class->source($source_name) };
812  
813 151 ▶ if ($@ || !$source) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ or not $source) 5 146 151
Condition66%2/3
$@ or not $source
l!l&&r!l&&!r
50146
MC/DC50%1/2
$@ or not $source
$@ not $source
Truth table66%2/3
A or not(B)
A= $@B= not $source
ABresult
1X1
011
000
814 5 croak "Could not resolve source '$source_name' in $schema_class: $@";
815 }
816  
817 # 2. Extract only what we need for the Async side
818 return {
819 result_class => $source->result_class,
820 columns => [ $source->columns ],
821 relationships => {
822 # We map relationships to know how to handle joins/prefetch later
823 146 map { $_ => $source->relationship_info($_) } $source->relationships
824 },
825 };
826 }
827  
828 116 ▶sub _build_inflator_map {
Subroutine _build_inflator_map: called CC=7 SCAR=20.0
829 116 my ($self, $schema) = @_;
830  
831 116 my $map = {};
832 116 foreach my $source_name ($schema->sources) {
833 1150 my $source = $schema->source($source_name);
834 1150 foreach my $col ($source->columns) {
835 4945 my $info = $source->column_info($col);
836  
837 # Extract both inflate and deflate coderefs
838 4945 ▶ if ($info->{deflate} || $info->{inflate}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($info->{'deflate'} or $info->{'inflate'}) { } 0 4945 4945
elsif ($info->{'serializer_class'} and $info->{'serializer_class'} eq 'JSON') { } 115 9660 9775
Condition33%1/3
$info->{"deflate"} or $info->{"inflate"}
l!l&&r!l&&!r
004945
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
839 $map->{$source_name}{$col} = {
840 deflate => $info->{deflate},
841 inflate => $info->{inflate},
842 0 };
843 }
844 # Explicit check for JSON Serializer
845 ▶ elsif ($info->{serializer_class}
Condition66%2/3
$info->{"serializer_class"} and $info->{"serializer_class"} eq "JSON"
!ll&&!rl&&r
48300115
MC/DC50%1/2
$info->{"serializer_class"} and $info->{"serializer_class"} eq "JSON"
$info->{"serializer_class"} $info->{"serializer_class"} eq "JSON"
Truth table66%2/3
A and B
A= $info->{"serializer_class"}B= $info->{"serializer_class"} eq "JSON"
ABresult
0X0
100
111
846 && $info->{serializer_class} eq 'JSON') {
847 115 require JSON;
848 115 my $json = JSON->new->utf8->allow_nonref;
849 $map->{$source_name}{$col} = {
850 817 ▶ inflate => sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
851 817 my $val = shift;
852 817 ▶ return $val if !defined $val || ref($val);
Branch: 1 branch
BranchTrueFalseTotal
if not defined $val or ref $val 811 6 817
Condition100%3/3
not defined $val or ref $val
l!l&&r!l&&!r
80926
MC/DC100%2/2
not defined $val or ref $val
not defined $val ref $val
Truth table100%3/3
not(A) or B
A= not defined $valB= ref $val
ABresult
1X1
011
000
853  
854 6 my $decoded;
855 eval {
856 6 $decoded = $json->decode($val); 1;
857 }
858 6 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $decoded = $json->decode($val); 1 } } or do { warn "Failed to inflate JSON in ${col}: $@ (Value: $val)"; return $val } 6 0 6
859 0 warn "Failed to inflate JSON in $col: $@ (Value: $val)";
860 0 return $val;
861 };
862 6 return $decoded;
863 },
864 8 ▶ deflate => sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
865 8 my $val = shift;
866 8 ▶ return $val if !defined $val || !ref($val);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val and ref $val 5 3 8
Condition66%2/3
defined $val and ref $val
!ll&&!rl&&r
503
MC/DC50%1/2
defined $val and ref $val
defined $val ref $val
Truth table66%2/3
A and B
A= defined $valB= ref $val
ABresult
0X0
100
111
867  
868 3 return $json->encode($val);
869 },
870 115 };
871 }
872 }
873 }
874  
875 116 return $map;
876 }
877  
878 =head1 METADATA & REFLECTION
879  
880 =over 4
881  
882 =item B<source( $source_name )>
883  
884 Returns the L<DBIx::Class::ResultSource> for the given name.
885  
886 Unlike standard DBIC, this uses a B<persistent metadata provider> (a cached
887 internal schema) to ensure that ResultSource objects remain stable across
888 async calls without re-connecting to the database unnecessarily.
889  
890 =item B<sources()>
891  
892 Returns a list of all source names available in the schema. This creates a
893 temporary, light-weight connection to extract the current schema structure
894 and then immediately disconnects to save resources.
895  
896 =item B<class( $source_name )>
897  
898 Returns the Result Class string (e.g., C<MyApp::Schema::Result::User>) for
899 the given source. Useful for dynamic inspections.
900  
901 =item B<schema_class()>
902  
903 Returns the name of the base L<DBIx::Class> schema class being proxied.
904  
905 =item B<schema_version()>
906  
907 Returns the version number defined in your DBIC Schema class, if available.
908  
909 =back
910  
911 =head1 TRANSACTION MANAGEMENT
912  
913 =over 4
914  
915 =item B<txn_begin / txn_commit / txn_rollback>
916  
917 These methods return L<Future> objects. Because workers are persistent,
918 calling C<txn_begin> pins your current logic to a specific worker until
919 C<commit> or C<rollback> is called.
920  
921 B<Note:> Use these carefully in an async loop to avoid "Worker Starvation"
922 where all workers are waiting on long-running manual transactions.
923  
924 =item B<txn_batch( @operations | \@operations )>
925  
926 The high-performance alternative to manual transactions. It sends a "bundle"
927 of operations to a worker to be executed in a single atomic block.
928  
929 $schema->txn_batch(
930 { type => 'create',
931 resultset => 'User',
932 data => { name => 'Alice' }
933 },
934 { type => 'update',
935 resultset => 'Stats',
936 data => { count => 1 },
937 where => { id => 5 }
938 }
939 );
940  
941 =back
942  
943 =head1 LIFECYCLE & STATE
944  
945 =over 4
946  
947 =item B<clone( workers =E<gt> $count )>
948  
949 Creates a fresh instance of the Async Schema. This is useful if you need a
950 separate pool of workers for "heavy" reporting queries vs. "light" web queries.
951  
952 =item B<disconnect()>
953  
954 Gracefully shuts down all background worker processes and flushes the metadata
955 caches. Use this during app shutdown to prevent zombie processes.
956  
957 =item B<storage()>
958  
959 Returns the C<DBIx::Class::Async::Storage::DBI> wrapper. This is provided for
960 compatibility with components that expect to inspect the DBIC storage layer.
961  
962 =back
963  
964 =head1 UTILITIES
965  
966 =over 4
967  
968 =item B<populate( $source_name, \@data )>
969  
970 Performs a high-speed bulk insert. This delegates to the ResultSet's C<populate>
971 logic and is significantly faster than calling C<create> in a loop.
972  
973 =item B<search_with_prefetch( $source_name, \%cond, \@prefetch, \%attrs )>
974  
975 A specialised shortcut for complex joins. It forces C<collapse =E<gt> 1> to ensure
976 that the data structure returned from the worker process is properly "folded"
977 into objects, preventing Cartesian product issues over IPC.
978  
979 =back
980  
981 =head1 FUTURE HANDLING & UNWRAPPING
982  
983 This package provides methods to handle L<Future> objects, including recursive
984 unwrapping for complex async operations and methods for parallel execution.
985  
986 =head2 await
987  
988 my $data = $schema->await($future);
989 my @data_list = $schema->await($future);
990  
991 Suspends the current process, running the underlying L<IO::Async::Loop>
992 until the provided C<Future> is ready.
993  
994 This method implements recursive unwrapping of nested Futures. If the
995 top-level Future resolves to another Future (e.g., a C<txn_do> call), this
996 method will continue to resolve them until the final data payload is reached.
997  
998 Throws an exception immediately if the Future chain fails.
999  
1000 Returns the final B<"leaf"> value(s) to the caller. The return value respects
1001 the context of the caller (list or scalar).
1002  
1003 =head2 run_parallel
1004  
1005 my $combined_future = $schema->run_parallel(
1006 sub { $_[0]->resultset('User')->find_future(1) },
1007 sub { $_[0]->resultset('Log')->count_future() },
1008 );
1009  
1010 Takes a list of coderefs, executes them concurrently passing the schema
1011 object as the first argument, and returns a single L<Future>. This returned
1012 Future resolves to a list of all results when all tasks have completed.
1013  
1014 B<Note>: The coderefs passed to this method must return a L<Future> object.
1015 Typically, you would use async methods like C<find_future> or C<search_future>
1016 within these coderefs.
1017  
1018 =head2 await_all
1019  
1020 my ($user, $log_count) = $schema->await_all($combined_future);
1021 # OR
1022 my ($user, $log_count) = $schema->await_all($f1, $f2);
1023  
1024 Takes a single combined L<Future> (like one returned by L</run_parallel>)
1025 or a list of individual L<Future> objects.
1026  
1027 It uses L</await> to synchronously wait for all provided Futures to resolve,
1028 and returns the final data results in the same order as the inputs.
1029  
1030 Throws an exception if any of the Futures fail.
1031  
1032 =head1 CUSTOM INFLATION & SERIALISATION
1033  
1034 Because this module uses a Worker-Pool architecture, data must travel across
1035 process boundaries. Standard Perl objects (like L<DateTime> or L<JSON> blobs)
1036 cannot simply be "shared" as live memory.
1037  
1038 C<DBIx::Class::Async::Schema> automatically detects your DBIC C<inflate_column>
1039 definitions and mirrors them in the Worker processes.
1040  
1041 =head2 How it works
1042  
1043 =over 4
1044  
1045 =item 1. Deflation (Main to Worker)
1046  
1047 When you pass an object to C<create> or C<update>, the bridge deflates it into
1048 a storable format before sending it to the worker.
1049  
1050 =item 2. Inflation (Worker to Main)
1051  
1052 When results come back, the bridge automatically re-applies your C<inflate> coderefs
1053 to turn raw strings back into rich objects.
1054  
1055 =back
1056  
1057 =head2 JSON Support
1058  
1059 The new design includes built-in support for C<serializer_class =E<gt> 'JSON'>.
1060 If detected in your ResultSource metadata, it will automatically handle the
1061 C<decode>/C<encode> cycle using L<JSON> in a non-blocking manner.
1062  
1063 =head2 Manual Registration
1064  
1065 If you have complex objects that aren't handled by standard DBIC inflation,
1066 you can register them manually:
1067  
1068 $schema->inflate_column('User', 'preferences', {
1069 inflate => sub { my $val = shift; decode_json($val) },
1070 deflate => sub { my $obj = shift; encode_json($obj) },
1071 });
1072  
1073 =head1 PERFORMANCE TIPS
1074  
1075 =head2 Worker Count
1076  
1077 Adjust the C<workers> parameter based on your database connection limits.
1078 Typically B<2-4 workers per CPU core> works well. Each worker maintains its
1079 own persistent DB connection.
1080  
1081 =head2 Prefetching
1082  
1083 Use C<search_with_prefetch> to fetch related data in one trip across the
1084 process boundary. This significantly reduces the overhead of IPC (Inter-Process
1085 Communication).
1086  
1087 =head1 ERROR HANDLING
1088  
1089 All methods return L<Future> objects. Errors from workers (SQL errors,
1090 timeouts, connection drops) are propagated as Future failures. Use
1091 C<< ->catch >> or C<try/catch> with C<await>.
1092  
1093 =head1 STATISTICS & METRICS
1094  
1095 If C<enable_metrics> is enabled, you can query the internal state:
1096  
1097 =over 4
1098  
1099 =item * C<total_queries()>: Total operations processed.
1100  
1101 =item * C<cache_hits()>: Operations resolved via the internal cache.
1102  
1103 =item * C<error_count()>: Total failed operations.
1104  
1105 =back
1106  
1107 =head1 EXTENSIBILITY & AUTOLOAD
1108  
1109 If you call a method on this object that is not defined in the Async package,
1110 it will attempt to proxy the call to the B<Native DBIC Schema>.
1111  
1112 This allows you to use custom methods defined in your C<MyApp::Schema> class
1113 seamlessly. However, be aware that calls made via C<AUTOLOAD> are executed in
1114 the B<Parent Process context> and may be blocking unless they specifically
1115 return a L<Future>.
1116  
1117 =head1 AUTHOR
1118  
1119 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
1120  
1121 =head1 REPOSITORY
1122  
1123 L<https://github.com/manwar/DBIx-Class-Async>
1124  
1125 =head1 BUGS
1126  
1127 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/DBIx-Class-Async/issues>.
1128 I will be notified and then you'll automatically be notified of progress on your
1129 bug as I make changes.
1130  
1131 =head1 SUPPORT
1132  
1133 You can find documentation for this module with the perldoc command.
1134  
1135 perldoc DBIx::Class::Async::Schema
1136  
1137 You can also look for information at:
1138  
1139 =over 4
1140  
1141 =item * BUG Report
1142  
1143 L<https://github.com/manwar/DBIx-Class-Async/issues>
1144  
1145 =item * CPAN Ratings
1146  
1147 L<http://cpanratings.perl.org/d/DBIx-Class-Async>
1148  
1149 =item * Search MetaCPAN
1150  
1151 L<https://metacpan.org/dist/DBIx-Class-Async/>
1152  
1153 =back
1154  
1155 =head1 LICENSE AND COPYRIGHT
1156  
1157 Copyright (C) 2026 Mohammad Sajid Anwar.
1158  
1159 This program is free software; you can redistribute it and / or modify it under
1160 the terms of the the Artistic License (2.0). You may obtain a copy of the full
1161 license at:
1162 L<http://www.perlfoundation.org/artistic_license_2_0>
1163 Any use, modification, and distribution of the Standard or Modified Versions is
1164 governed by this Artistic License.By using, modifying or distributing the Package,
1165 you accept this license. Do not use, modify, or distribute the Package, if you do
1166 not accept this license.
1167 If your Modified Version has been derived from a Modified Version made by someone
1168 other than you,you are nevertheless required to ensure that your Modified Version
1169 complies with the requirements of this license.
1170 This license does not grant you the right to use any trademark, service mark,
1171 tradename, or logo of the Copyright Holder.
1172 This license includes the non-exclusive, worldwide, free-of-charge patent license
1173 to make, have made, use, offer to sell, sell, import and otherwise transfer the
1174 Package with respect to any patent claims licensable by the Copyright Holder that
1175 are necessarily infringed by the Package. If you institute patent litigation
1176 (including a cross-claim or counterclaim) against any party alleging that the
1177 Package constitutes direct or contributory patent infringement,then this Artistic
1178 License to you shall terminate on the date that such litigation is filed.
1179 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND
1180 CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED
1181 WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
1182 NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS
1183 REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT,
1184 INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE
1185 OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1186  
1187 =cut
1188  
1189 100 1; # End of DBIx::Class::Async::Schema
« Async/Exception/Factory.pm ↑ Summary Async/Storage/DBI.pm »