Async/Schema.pm

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